clang 20.0.0git
CodeGenModule.cpp
Go to the documentation of this file.
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"
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"
37#include "clang/AST/Mangle.h"
45#include "clang/Basic/Module.h"
48#include "clang/Basic/Version.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/ADT/StringSwitch.h"
55#include "llvm/Analysis/TargetLibraryInfo.h"
56#include "llvm/BinaryFormat/ELF.h"
57#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
58#include "llvm/IR/AttributeMask.h"
59#include "llvm/IR/CallingConv.h"
60#include "llvm/IR/DataLayout.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/ProfileSummary.h"
65#include "llvm/ProfileData/InstrProfReader.h"
66#include "llvm/ProfileData/SampleProf.h"
67#include "llvm/Support/CRC.h"
68#include "llvm/Support/CodeGen.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/ConvertUTF.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/TimeProfiler.h"
73#include "llvm/Support/xxhash.h"
74#include "llvm/TargetParser/RISCVISAInfo.h"
75#include "llvm/TargetParser/Triple.h"
76#include "llvm/TargetParser/X86TargetParser.h"
77#include "llvm/Transforms/Utils/BuildLibCalls.h"
78#include <optional>
79
80using namespace clang;
81using namespace CodeGen;
82
83static llvm::cl::opt<bool> LimitedCoverage(
84 "limited-coverage-experimental", llvm::cl::Hidden,
85 llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
86
87static const char AnnotationSection[] = "llvm.metadata";
88
90 switch (CGM.getContext().getCXXABIKind()) {
91 case TargetCXXABI::AppleARM64:
92 case TargetCXXABI::Fuchsia:
93 case TargetCXXABI::GenericAArch64:
94 case TargetCXXABI::GenericARM:
95 case TargetCXXABI::iOS:
96 case TargetCXXABI::WatchOS:
97 case TargetCXXABI::GenericMIPS:
98 case TargetCXXABI::GenericItanium:
99 case TargetCXXABI::WebAssembly:
100 case TargetCXXABI::XL:
101 return CreateItaniumCXXABI(CGM);
102 case TargetCXXABI::Microsoft:
103 return CreateMicrosoftCXXABI(CGM);
104 }
105
106 llvm_unreachable("invalid C++ ABI kind");
107}
108
109static std::unique_ptr<TargetCodeGenInfo>
111 const TargetInfo &Target = CGM.getTarget();
112 const llvm::Triple &Triple = Target.getTriple();
113 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
114
115 switch (Triple.getArch()) {
116 default:
118
119 case llvm::Triple::m68k:
120 return createM68kTargetCodeGenInfo(CGM);
121 case llvm::Triple::mips:
122 case llvm::Triple::mipsel:
123 if (Triple.getOS() == llvm::Triple::NaCl)
125 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
126
127 case llvm::Triple::mips64:
128 case llvm::Triple::mips64el:
129 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
130
131 case llvm::Triple::avr: {
132 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
133 // on avrtiny. For passing return value, R18~R25 are used on avr, and
134 // R22~R25 are used on avrtiny.
135 unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
136 unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
137 return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
138 }
139
140 case llvm::Triple::aarch64:
141 case llvm::Triple::aarch64_32:
142 case llvm::Triple::aarch64_be: {
143 AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
144 if (Target.getABI() == "darwinpcs")
145 Kind = AArch64ABIKind::DarwinPCS;
146 else if (Triple.isOSWindows())
147 return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
148 else if (Target.getABI() == "aapcs-soft")
149 Kind = AArch64ABIKind::AAPCSSoft;
150 else if (Target.getABI() == "pauthtest")
151 Kind = AArch64ABIKind::PAuthTest;
152
153 return createAArch64TargetCodeGenInfo(CGM, Kind);
154 }
155
156 case llvm::Triple::wasm32:
157 case llvm::Triple::wasm64: {
158 WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
159 if (Target.getABI() == "experimental-mv")
160 Kind = WebAssemblyABIKind::ExperimentalMV;
161 return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
162 }
163
164 case llvm::Triple::arm:
165 case llvm::Triple::armeb:
166 case llvm::Triple::thumb:
167 case llvm::Triple::thumbeb: {
168 if (Triple.getOS() == llvm::Triple::Win32)
169 return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
170
171 ARMABIKind Kind = ARMABIKind::AAPCS;
172 StringRef ABIStr = Target.getABI();
173 if (ABIStr == "apcs-gnu")
174 Kind = ARMABIKind::APCS;
175 else if (ABIStr == "aapcs16")
176 Kind = ARMABIKind::AAPCS16_VFP;
177 else if (CodeGenOpts.FloatABI == "hard" ||
178 (CodeGenOpts.FloatABI != "soft" &&
179 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
180 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
181 Triple.getEnvironment() == llvm::Triple::EABIHF)))
182 Kind = ARMABIKind::AAPCS_VFP;
183
184 return createARMTargetCodeGenInfo(CGM, Kind);
185 }
186
187 case llvm::Triple::ppc: {
188 if (Triple.isOSAIX())
189 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
190
191 bool IsSoftFloat =
192 CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
193 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
194 }
195 case llvm::Triple::ppcle: {
196 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
197 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
198 }
199 case llvm::Triple::ppc64:
200 if (Triple.isOSAIX())
201 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
202
203 if (Triple.isOSBinFormatELF()) {
204 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
205 if (Target.getABI() == "elfv2")
206 Kind = PPC64_SVR4_ABIKind::ELFv2;
207 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
208
209 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
210 }
212 case llvm::Triple::ppc64le: {
213 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
214 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
215 if (Target.getABI() == "elfv1")
216 Kind = PPC64_SVR4_ABIKind::ELFv1;
217 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
218
219 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
220 }
221
222 case llvm::Triple::nvptx:
223 case llvm::Triple::nvptx64:
225
226 case llvm::Triple::msp430:
228
229 case llvm::Triple::riscv32:
230 case llvm::Triple::riscv64: {
231 StringRef ABIStr = Target.getABI();
232 unsigned XLen = Target.getPointerWidth(LangAS::Default);
233 unsigned ABIFLen = 0;
234 if (ABIStr.ends_with("f"))
235 ABIFLen = 32;
236 else if (ABIStr.ends_with("d"))
237 ABIFLen = 64;
238 bool EABI = ABIStr.ends_with("e");
239 return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI);
240 }
241
242 case llvm::Triple::systemz: {
243 bool SoftFloat = CodeGenOpts.FloatABI == "soft";
244 bool HasVector = !SoftFloat && Target.getABI() == "vector";
245 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
246 }
247
248 case llvm::Triple::tce:
249 case llvm::Triple::tcele:
250 return createTCETargetCodeGenInfo(CGM);
251
252 case llvm::Triple::x86: {
253 bool IsDarwinVectorABI = Triple.isOSDarwin();
254 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
255
256 if (Triple.getOS() == llvm::Triple::Win32) {
258 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
259 CodeGenOpts.NumRegisterParameters);
260 }
262 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
263 CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
264 }
265
266 case llvm::Triple::x86_64: {
267 StringRef ABI = Target.getABI();
268 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
269 : ABI == "avx" ? X86AVXABILevel::AVX
270 : X86AVXABILevel::None);
271
272 switch (Triple.getOS()) {
273 case llvm::Triple::Win32:
274 return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
275 default:
276 return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
277 }
278 }
279 case llvm::Triple::hexagon:
281 case llvm::Triple::lanai:
283 case llvm::Triple::r600:
285 case llvm::Triple::amdgcn:
287 case llvm::Triple::sparc:
289 case llvm::Triple::sparcv9:
291 case llvm::Triple::xcore:
293 case llvm::Triple::arc:
294 return createARCTargetCodeGenInfo(CGM);
295 case llvm::Triple::spir:
296 case llvm::Triple::spir64:
298 case llvm::Triple::spirv32:
299 case llvm::Triple::spirv64:
301 case llvm::Triple::ve:
302 return createVETargetCodeGenInfo(CGM);
303 case llvm::Triple::csky: {
304 bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
305 bool hasFP64 =
306 Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
307 return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
308 : hasFP64 ? 64
309 : 32);
310 }
311 case llvm::Triple::bpfeb:
312 case llvm::Triple::bpfel:
313 return createBPFTargetCodeGenInfo(CGM);
314 case llvm::Triple::loongarch32:
315 case llvm::Triple::loongarch64: {
316 StringRef ABIStr = Target.getABI();
317 unsigned ABIFRLen = 0;
318 if (ABIStr.ends_with("f"))
319 ABIFRLen = 32;
320 else if (ABIStr.ends_with("d"))
321 ABIFRLen = 64;
323 CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
324 }
325 }
326}
327
329 if (!TheTargetCodeGenInfo)
330 TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
331 return *TheTargetCodeGenInfo;
332}
333
334CodeGenModule::CodeGenModule(ASTContext &C,
336 const HeaderSearchOptions &HSO,
337 const PreprocessorOptions &PPO,
338 const CodeGenOptions &CGO, llvm::Module &M,
339 DiagnosticsEngine &diags,
340 CoverageSourceInfo *CoverageInfo)
341 : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
342 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
343 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
344 VMContext(M.getContext()), VTables(*this),
345 SanitizerMD(new SanitizerMetadata(*this)) {
346
347 // Initialize the type cache.
348 Types.reset(new CodeGenTypes(*this));
349 llvm::LLVMContext &LLVMContext = M.getContext();
350 VoidTy = llvm::Type::getVoidTy(LLVMContext);
351 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
352 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
353 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
354 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
355 HalfTy = llvm::Type::getHalfTy(LLVMContext);
356 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
357 FloatTy = llvm::Type::getFloatTy(LLVMContext);
358 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
359 PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
361 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
362 .getQuantity();
364 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
366 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
367 CharTy =
368 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
369 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
370 IntPtrTy = llvm::IntegerType::get(LLVMContext,
371 C.getTargetInfo().getMaxPointerWidth());
372 Int8PtrTy = llvm::PointerType::get(LLVMContext,
373 C.getTargetAddressSpace(LangAS::Default));
374 const llvm::DataLayout &DL = M.getDataLayout();
376 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
378 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
379 ConstGlobalsPtrTy = llvm::PointerType::get(
380 LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
382
383 // Build C++20 Module initializers.
384 // TODO: Add Microsoft here once we know the mangling required for the
385 // initializers.
386 CXX20ModuleInits =
387 LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
389
390 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
391
392 if (LangOpts.ObjC)
393 createObjCRuntime();
394 if (LangOpts.OpenCL)
395 createOpenCLRuntime();
396 if (LangOpts.OpenMP)
397 createOpenMPRuntime();
398 if (LangOpts.CUDA)
399 createCUDARuntime();
400 if (LangOpts.HLSL)
401 createHLSLRuntime();
402
403 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
404 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
405 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
406 TBAA.reset(new CodeGenTBAA(Context, getTypes(), TheModule, CodeGenOpts,
407 getLangOpts()));
408
409 // If debug info or coverage generation is enabled, create the CGDebugInfo
410 // object.
411 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
412 CodeGenOpts.CoverageNotesFile.size() ||
413 CodeGenOpts.CoverageDataFile.size())
414 DebugInfo.reset(new CGDebugInfo(*this));
415
416 Block.GlobalUniqueCount = 0;
417
418 if (C.getLangOpts().ObjC)
419 ObjCData.reset(new ObjCEntrypoints());
420
421 if (CodeGenOpts.hasProfileClangUse()) {
422 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
423 CodeGenOpts.ProfileInstrumentUsePath, *FS,
424 CodeGenOpts.ProfileRemappingFile);
425 // We're checking for profile read errors in CompilerInvocation, so if
426 // there was an error it should've already been caught. If it hasn't been
427 // somehow, trip an assertion.
428 assert(ReaderOrErr);
429 PGOReader = std::move(ReaderOrErr.get());
430 }
431
432 // If coverage mapping generation is enabled, create the
433 // CoverageMappingModuleGen object.
434 if (CodeGenOpts.CoverageMapping)
435 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
436
437 // Generate the module name hash here if needed.
438 if (CodeGenOpts.UniqueInternalLinkageNames &&
439 !getModule().getSourceFileName().empty()) {
440 std::string Path = getModule().getSourceFileName();
441 // Check if a path substitution is needed from the MacroPrefixMap.
442 for (const auto &Entry : LangOpts.MacroPrefixMap)
443 if (Path.rfind(Entry.first, 0) != std::string::npos) {
444 Path = Entry.second + Path.substr(Entry.first.size());
445 break;
446 }
447 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
448 }
449
450 // Record mregparm value now so it is visible through all of codegen.
451 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
452 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
453 CodeGenOpts.NumRegisterParameters);
454}
455
457
458void CodeGenModule::createObjCRuntime() {
459 // This is just isGNUFamily(), but we want to force implementors of
460 // new ABIs to decide how best to do this.
461 switch (LangOpts.ObjCRuntime.getKind()) {
463 case ObjCRuntime::GCC:
465 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
466 return;
467
470 case ObjCRuntime::iOS:
472 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
473 return;
474 }
475 llvm_unreachable("bad runtime kind");
476}
477
478void CodeGenModule::createOpenCLRuntime() {
479 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
480}
481
482void CodeGenModule::createOpenMPRuntime() {
483 // Select a specialized code generation class based on the target, if any.
484 // If it does not exist use the default implementation.
485 switch (getTriple().getArch()) {
486 case llvm::Triple::nvptx:
487 case llvm::Triple::nvptx64:
488 case llvm::Triple::amdgcn:
489 assert(getLangOpts().OpenMPIsTargetDevice &&
490 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
491 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
492 break;
493 default:
494 if (LangOpts.OpenMPSimd)
495 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
496 else
497 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
498 break;
499 }
500}
501
502void CodeGenModule::createCUDARuntime() {
503 CUDARuntime.reset(CreateNVCUDARuntime(*this));
504}
505
506void CodeGenModule::createHLSLRuntime() {
507 HLSLRuntime.reset(new CGHLSLRuntime(*this));
508}
509
510void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
511 Replacements[Name] = C;
512}
513
514void CodeGenModule::applyReplacements() {
515 for (auto &I : Replacements) {
516 StringRef MangledName = I.first;
517 llvm::Constant *Replacement = I.second;
518 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
519 if (!Entry)
520 continue;
521 auto *OldF = cast<llvm::Function>(Entry);
522 auto *NewF = dyn_cast<llvm::Function>(Replacement);
523 if (!NewF) {
524 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
525 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
526 } else {
527 auto *CE = cast<llvm::ConstantExpr>(Replacement);
528 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
529 CE->getOpcode() == llvm::Instruction::GetElementPtr);
530 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
531 }
532 }
533
534 // Replace old with new, but keep the old order.
535 OldF->replaceAllUsesWith(Replacement);
536 if (NewF) {
537 NewF->removeFromParent();
538 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
539 NewF);
540 }
541 OldF->eraseFromParent();
542 }
543}
544
545void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
546 GlobalValReplacements.push_back(std::make_pair(GV, C));
547}
548
549void CodeGenModule::applyGlobalValReplacements() {
550 for (auto &I : GlobalValReplacements) {
551 llvm::GlobalValue *GV = I.first;
552 llvm::Constant *C = I.second;
553
554 GV->replaceAllUsesWith(C);
555 GV->eraseFromParent();
556 }
557}
558
559// This is only used in aliases that we created and we know they have a
560// linear structure.
561static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
562 const llvm::Constant *C;
563 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
564 C = GA->getAliasee();
565 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
566 C = GI->getResolver();
567 else
568 return GV;
569
570 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
571 if (!AliaseeGV)
572 return nullptr;
573
574 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
575 if (FinalGV == GV)
576 return nullptr;
577
578 return FinalGV;
579}
580
582 const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location,
583 bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
584 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
585 SourceRange AliasRange) {
586 GV = getAliasedGlobal(Alias);
587 if (!GV) {
588 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
589 return false;
590 }
591
592 if (GV->hasCommonLinkage()) {
593 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
594 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
595 Diags.Report(Location, diag::err_alias_to_common);
596 return false;
597 }
598 }
599
600 if (GV->isDeclaration()) {
601 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
602 Diags.Report(Location, diag::note_alias_requires_mangled_name)
603 << IsIFunc << IsIFunc;
604 // Provide a note if the given function is not found and exists as a
605 // mangled name.
606 for (const auto &[Decl, Name] : MangledDeclNames) {
607 if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
608 if (ND->getName() == GV->getName()) {
609 Diags.Report(Location, diag::note_alias_mangled_name_alternative)
610 << Name
612 AliasRange,
613 (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
614 .str());
615 }
616 }
617 }
618 return false;
619 }
620
621 if (IsIFunc) {
622 // Check resolver function type.
623 const auto *F = dyn_cast<llvm::Function>(GV);
624 if (!F) {
625 Diags.Report(Location, diag::err_alias_to_undefined)
626 << IsIFunc << IsIFunc;
627 return false;
628 }
629
630 llvm::FunctionType *FTy = F->getFunctionType();
631 if (!FTy->getReturnType()->isPointerTy()) {
632 Diags.Report(Location, diag::err_ifunc_resolver_return);
633 return false;
634 }
635 }
636
637 return true;
638}
639
640// Emit a warning if toc-data attribute is requested for global variables that
641// have aliases and remove the toc-data attribute.
642static void checkAliasForTocData(llvm::GlobalVariable *GVar,
643 const CodeGenOptions &CodeGenOpts,
644 DiagnosticsEngine &Diags,
645 SourceLocation Location) {
646 if (GVar->hasAttribute("toc-data")) {
647 auto GVId = GVar->getName();
648 // Is this a global variable specified by the user as local?
649 if ((llvm::binary_search(CodeGenOpts.TocDataVarsUserSpecified, GVId))) {
650 Diags.Report(Location, diag::warn_toc_unsupported_type)
651 << GVId << "the variable has an alias";
652 }
653 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
654 llvm::AttributeSet NewAttributes =
655 CurrAttributes.removeAttribute(GVar->getContext(), "toc-data");
656 GVar->setAttributes(NewAttributes);
657 }
658}
659
660void CodeGenModule::checkAliases() {
661 // Check if the constructed aliases are well formed. It is really unfortunate
662 // that we have to do this in CodeGen, but we only construct mangled names
663 // and aliases during codegen.
664 bool Error = false;
665 DiagnosticsEngine &Diags = getDiags();
666 for (const GlobalDecl &GD : Aliases) {
667 const auto *D = cast<ValueDecl>(GD.getDecl());
668 SourceLocation Location;
670 bool IsIFunc = D->hasAttr<IFuncAttr>();
671 if (const Attr *A = D->getDefiningAttr()) {
672 Location = A->getLocation();
673 Range = A->getRange();
674 } else
675 llvm_unreachable("Not an alias or ifunc?");
676
677 StringRef MangledName = getMangledName(GD);
678 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
679 const llvm::GlobalValue *GV = nullptr;
680 if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV,
681 MangledDeclNames, Range)) {
682 Error = true;
683 continue;
684 }
685
686 if (getContext().getTargetInfo().getTriple().isOSAIX())
687 if (const llvm::GlobalVariable *GVar =
688 dyn_cast<const llvm::GlobalVariable>(GV))
689 checkAliasForTocData(const_cast<llvm::GlobalVariable *>(GVar),
690 getCodeGenOpts(), Diags, Location);
691
692 llvm::Constant *Aliasee =
693 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
694 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
695
696 llvm::GlobalValue *AliaseeGV;
697 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
698 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
699 else
700 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
701
702 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
703 StringRef AliasSection = SA->getName();
704 if (AliasSection != AliaseeGV->getSection())
705 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
706 << AliasSection << IsIFunc << IsIFunc;
707 }
708
709 // We have to handle alias to weak aliases in here. LLVM itself disallows
710 // this since the object semantics would not match the IL one. For
711 // compatibility with gcc we implement it by just pointing the alias
712 // to its aliasee's aliasee. We also warn, since the user is probably
713 // expecting the link to be weak.
714 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
715 if (GA->isInterposable()) {
716 Diags.Report(Location, diag::warn_alias_to_weak_alias)
717 << GV->getName() << GA->getName() << IsIFunc;
718 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
719 GA->getAliasee(), Alias->getType());
720
721 if (IsIFunc)
722 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
723 else
724 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
725 }
726 }
727 // ifunc resolvers are usually implemented to run before sanitizer
728 // initialization. Disable instrumentation to prevent the ordering issue.
729 if (IsIFunc)
730 cast<llvm::Function>(Aliasee)->addFnAttr(
731 llvm::Attribute::DisableSanitizerInstrumentation);
732 }
733 if (!Error)
734 return;
735
736 for (const GlobalDecl &GD : Aliases) {
737 StringRef MangledName = getMangledName(GD);
738 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
739 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
740 Alias->eraseFromParent();
741 }
742}
743
745 DeferredDeclsToEmit.clear();
746 EmittedDeferredDecls.clear();
747 DeferredAnnotations.clear();
748 if (OpenMPRuntime)
749 OpenMPRuntime->clear();
750}
751
753 StringRef MainFile) {
754 if (!hasDiagnostics())
755 return;
756 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
757 if (MainFile.empty())
758 MainFile = "<stdin>";
759 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
760 } else {
761 if (Mismatched > 0)
762 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
763
764 if (Missing > 0)
765 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
766 }
767}
768
769static std::optional<llvm::GlobalValue::VisibilityTypes>
771 // Map to LLVM visibility.
772 switch (K) {
774 return std::nullopt;
776 return llvm::GlobalValue::DefaultVisibility;
778 return llvm::GlobalValue::HiddenVisibility;
780 return llvm::GlobalValue::ProtectedVisibility;
781 }
782 llvm_unreachable("unknown option value!");
783}
784
785void setLLVMVisibility(llvm::GlobalValue &GV,
786 std::optional<llvm::GlobalValue::VisibilityTypes> V) {
787 if (!V)
788 return;
789
790 // Reset DSO locality before setting the visibility. This removes
791 // any effects that visibility options and annotations may have
792 // had on the DSO locality. Setting the visibility will implicitly set
793 // appropriate globals to DSO Local; however, this will be pessimistic
794 // w.r.t. to the normal compiler IRGen.
795 GV.setDSOLocal(false);
796 GV.setVisibility(*V);
797}
798
800 llvm::Module &M) {
801 if (!LO.VisibilityFromDLLStorageClass)
802 return;
803
804 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
805 getLLVMVisibility(LO.getDLLExportVisibility());
806
807 std::optional<llvm::GlobalValue::VisibilityTypes>
808 NoDLLStorageClassVisibility =
809 getLLVMVisibility(LO.getNoDLLStorageClassVisibility());
810
811 std::optional<llvm::GlobalValue::VisibilityTypes>
812 ExternDeclDLLImportVisibility =
813 getLLVMVisibility(LO.getExternDeclDLLImportVisibility());
814
815 std::optional<llvm::GlobalValue::VisibilityTypes>
816 ExternDeclNoDLLStorageClassVisibility =
817 getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility());
818
819 for (llvm::GlobalValue &GV : M.global_values()) {
820 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
821 continue;
822
823 if (GV.isDeclarationForLinker())
824 setLLVMVisibility(GV, GV.getDLLStorageClass() ==
825 llvm::GlobalValue::DLLImportStorageClass
826 ? ExternDeclDLLImportVisibility
827 : ExternDeclNoDLLStorageClassVisibility);
828 else
829 setLLVMVisibility(GV, GV.getDLLStorageClass() ==
830 llvm::GlobalValue::DLLExportStorageClass
831 ? DLLExportVisibility
832 : NoDLLStorageClassVisibility);
833
834 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
835 }
836}
837
838static bool isStackProtectorOn(const LangOptions &LangOpts,
839 const llvm::Triple &Triple,
841 if (Triple.isAMDGPU() || Triple.isNVPTX())
842 return false;
843 return LangOpts.getStackProtector() == Mode;
844}
845
848 if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
849 EmitModuleInitializers(Primary);
850 EmitDeferred();
851 DeferredDecls.insert(EmittedDeferredDecls.begin(),
852 EmittedDeferredDecls.end());
853 EmittedDeferredDecls.clear();
854 EmitVTablesOpportunistically();
855 applyGlobalValReplacements();
856 applyReplacements();
857 emitMultiVersionFunctions();
858
859 if (Context.getLangOpts().IncrementalExtensions &&
860 GlobalTopLevelStmtBlockInFlight.first) {
861 const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
862 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
863 GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
864 }
865
866 // Module implementations are initialized the same way as a regular TU that
867 // imports one or more modules.
868 if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
869 EmitCXXModuleInitFunc(Primary);
870 else
871 EmitCXXGlobalInitFunc();
872 EmitCXXGlobalCleanUpFunc();
873 registerGlobalDtorsWithAtExit();
874 EmitCXXThreadLocalInitFunc();
875 if (ObjCRuntime)
876 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
877 AddGlobalCtor(ObjCInitFunction);
878 if (Context.getLangOpts().CUDA && CUDARuntime) {
879 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
880 AddGlobalCtor(CudaCtorFunction);
881 }
882 if (OpenMPRuntime) {
883 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
884 OpenMPRuntime->clear();
885 }
886 if (PGOReader) {
887 getModule().setProfileSummary(
888 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
889 llvm::ProfileSummary::PSK_Instr);
890 if (PGOStats.hasDiagnostics())
891 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
892 }
893 llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
894 return L.LexOrder < R.LexOrder;
895 });
896 EmitCtorList(GlobalCtors, "llvm.global_ctors");
897 EmitCtorList(GlobalDtors, "llvm.global_dtors");
899 EmitStaticExternCAliases();
900 checkAliases();
904 if (CoverageMapping)
905 CoverageMapping->emit();
906 if (CodeGenOpts.SanitizeCfiCrossDso) {
909 }
910 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
912 emitAtAvailableLinkGuard();
913 if (Context.getTargetInfo().getTriple().isWasm())
915
916 if (getTriple().isAMDGPU() ||
917 (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD)) {
918 // Emit amdhsa_code_object_version module flag, which is code object version
919 // times 100.
920 if (getTarget().getTargetOpts().CodeObjectVersion !=
921 llvm::CodeObjectVersionKind::COV_None) {
922 getModule().addModuleFlag(llvm::Module::Error,
923 "amdhsa_code_object_version",
924 getTarget().getTargetOpts().CodeObjectVersion);
925 }
926
927 // Currently, "-mprintf-kind" option is only supported for HIP
928 if (LangOpts.HIP) {
929 auto *MDStr = llvm::MDString::get(
930 getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
932 ? "hostcall"
933 : "buffered");
934 getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
935 MDStr);
936 }
937 }
938
939 // Emit a global array containing all external kernels or device variables
940 // used by host functions and mark it as used for CUDA/HIP. This is necessary
941 // to get kernels or device variables in archives linked in even if these
942 // kernels or device variables are only used in host functions.
943 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
945 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
946 GlobalDecl GD;
947 if (auto *FD = dyn_cast<FunctionDecl>(D))
949 else
950 GD = GlobalDecl(D);
951 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
953 }
954
955 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
956
957 auto *GV = new llvm::GlobalVariable(
958 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
959 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
961 }
962 if (LangOpts.HIP && !getLangOpts().OffloadingNewDriver) {
963 // Emit a unique ID so that host and device binaries from the same
964 // compilation unit can be associated.
965 auto *GV = new llvm::GlobalVariable(
966 getModule(), Int8Ty, false, llvm::GlobalValue::ExternalLinkage,
967 llvm::Constant::getNullValue(Int8Ty),
968 "__hip_cuid_" + getContext().getCUIDHash());
970 }
971 emitLLVMUsed();
972 if (SanStats)
973 SanStats->finish();
974
975 if (CodeGenOpts.Autolink &&
976 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
977 EmitModuleLinkOptions();
978 }
979
980 // On ELF we pass the dependent library specifiers directly to the linker
981 // without manipulating them. This is in contrast to other platforms where
982 // they are mapped to a specific linker option by the compiler. This
983 // difference is a result of the greater variety of ELF linkers and the fact
984 // that ELF linkers tend to handle libraries in a more complicated fashion
985 // than on other platforms. This forces us to defer handling the dependent
986 // libs to the linker.
987 //
988 // CUDA/HIP device and host libraries are different. Currently there is no
989 // way to differentiate dependent libraries for host or device. Existing
990 // usage of #pragma comment(lib, *) is intended for host libraries on
991 // Windows. Therefore emit llvm.dependent-libraries only for host.
992 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
993 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
994 for (auto *MD : ELFDependentLibraries)
995 NMD->addOperand(MD);
996 }
997
998 if (CodeGenOpts.DwarfVersion) {
999 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
1000 CodeGenOpts.DwarfVersion);
1001 }
1002
1003 if (CodeGenOpts.Dwarf64)
1004 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
1005
1006 if (Context.getLangOpts().SemanticInterposition)
1007 // Require various optimization to respect semantic interposition.
1008 getModule().setSemanticInterposition(true);
1009
1010 if (CodeGenOpts.EmitCodeView) {
1011 // Indicate that we want CodeView in the metadata.
1012 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
1013 }
1014 if (CodeGenOpts.CodeViewGHash) {
1015 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
1016 }
1017 if (CodeGenOpts.ControlFlowGuard) {
1018 // Function ID tables and checks for Control Flow Guard (cfguard=2).
1019 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
1020 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1021 // Function ID tables for Control Flow Guard (cfguard=1).
1022 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
1023 }
1024 if (CodeGenOpts.EHContGuard) {
1025 // Function ID tables for EH Continuation Guard.
1026 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
1027 }
1028 if (Context.getLangOpts().Kernel) {
1029 // Note if we are compiling with /kernel.
1030 getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
1031 }
1032 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1033 // We don't support LTO with 2 with different StrictVTablePointers
1034 // FIXME: we could support it by stripping all the information introduced
1035 // by StrictVTablePointers.
1036
1037 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
1038
1039 llvm::Metadata *Ops[2] = {
1040 llvm::MDString::get(VMContext, "StrictVTablePointers"),
1041 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1042 llvm::Type::getInt32Ty(VMContext), 1))};
1043
1044 getModule().addModuleFlag(llvm::Module::Require,
1045 "StrictVTablePointersRequirement",
1046 llvm::MDNode::get(VMContext, Ops));
1047 }
1048 if (getModuleDebugInfo())
1049 // We support a single version in the linked module. The LLVM
1050 // parser will drop debug info with a different version number
1051 // (and warn about it, too).
1052 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
1053 llvm::DEBUG_METADATA_VERSION);
1054
1055 // We need to record the widths of enums and wchar_t, so that we can generate
1056 // the correct build attributes in the ARM backend. wchar_size is also used by
1057 // TargetLibraryInfo.
1058 uint64_t WCharWidth =
1059 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1060 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
1061
1062 if (getTriple().isOSzOS()) {
1063 getModule().addModuleFlag(llvm::Module::Warning,
1064 "zos_product_major_version",
1065 uint32_t(CLANG_VERSION_MAJOR));
1066 getModule().addModuleFlag(llvm::Module::Warning,
1067 "zos_product_minor_version",
1068 uint32_t(CLANG_VERSION_MINOR));
1069 getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel",
1070 uint32_t(CLANG_VERSION_PATCHLEVEL));
1071 std::string ProductId = getClangVendor() + "clang";
1072 getModule().addModuleFlag(llvm::Module::Error, "zos_product_id",
1073 llvm::MDString::get(VMContext, ProductId));
1074
1075 // Record the language because we need it for the PPA2.
1076 StringRef lang_str = languageToString(
1078 getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language",
1079 llvm::MDString::get(VMContext, lang_str));
1080
1081 time_t TT = PreprocessorOpts.SourceDateEpoch
1082 ? *PreprocessorOpts.SourceDateEpoch
1083 : std::time(nullptr);
1084 getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time",
1085 static_cast<uint64_t>(TT));
1086
1087 // Multiple modes will be supported here.
1088 getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode",
1089 llvm::MDString::get(VMContext, "ascii"));
1090 }
1091
1092 llvm::Triple T = Context.getTargetInfo().getTriple();
1093 if (T.isARM() || T.isThumb()) {
1094 // The minimum width of an enum in bytes
1095 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1096 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
1097 }
1098
1099 if (T.isRISCV()) {
1100 StringRef ABIStr = Target.getABI();
1101 llvm::LLVMContext &Ctx = TheModule.getContext();
1102 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
1103 llvm::MDString::get(Ctx, ABIStr));
1104
1105 // Add the canonical ISA string as metadata so the backend can set the ELF
1106 // attributes correctly. We use AppendUnique so LTO will keep all of the
1107 // unique ISA strings that were linked together.
1108 const std::vector<std::string> &Features =
1110 auto ParseResult =
1111 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
1112 if (!errorToBool(ParseResult.takeError()))
1113 getModule().addModuleFlag(
1114 llvm::Module::AppendUnique, "riscv-isa",
1115 llvm::MDNode::get(
1116 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1117 }
1118
1119 if (CodeGenOpts.SanitizeCfiCrossDso) {
1120 // Indicate that we want cross-DSO control flow integrity checks.
1121 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
1122 }
1123
1124 if (CodeGenOpts.WholeProgramVTables) {
1125 // Indicate whether VFE was enabled for this module, so that the
1126 // vcall_visibility metadata added under whole program vtables is handled
1127 // appropriately in the optimizer.
1128 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
1129 CodeGenOpts.VirtualFunctionElimination);
1130 }
1131
1132 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1133 getModule().addModuleFlag(llvm::Module::Override,
1134 "CFI Canonical Jump Tables",
1135 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1136 }
1137
1138 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1139 getModule().addModuleFlag(llvm::Module::Override, "cfi-normalize-integers",
1140 1);
1141 }
1142
1143 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1144 getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1145 // KCFI assumes patchable-function-prefix is the same for all indirectly
1146 // called functions. Store the expected offset for code generation.
1147 if (CodeGenOpts.PatchableFunctionEntryOffset)
1148 getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1149 CodeGenOpts.PatchableFunctionEntryOffset);
1150 }
1151
1152 if (CodeGenOpts.CFProtectionReturn &&
1153 Target.checkCFProtectionReturnSupported(getDiags())) {
1154 // Indicate that we want to instrument return control flow protection.
1155 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
1156 1);
1157 }
1158
1159 if (CodeGenOpts.CFProtectionBranch &&
1160 Target.checkCFProtectionBranchSupported(getDiags())) {
1161 // Indicate that we want to instrument branch control flow protection.
1162 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
1163 1);
1164 }
1165
1166 if (CodeGenOpts.FunctionReturnThunks)
1167 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
1168
1169 if (CodeGenOpts.IndirectBranchCSPrefix)
1170 getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1171
1172 // Add module metadata for return address signing (ignoring
1173 // non-leaf/all) and stack tagging. These are actually turned on by function
1174 // attributes, but we use module metadata to emit build attributes. This is
1175 // needed for LTO, where the function attributes are inside bitcode
1176 // serialised into a global variable by the time build attributes are
1177 // emitted, so we can't access them. LTO objects could be compiled with
1178 // different flags therefore module flags are set to "Min" behavior to achieve
1179 // the same end result of the normal build where e.g BTI is off if any object
1180 // doesn't support it.
1181 if (Context.getTargetInfo().hasFeature("ptrauth") &&
1182 LangOpts.getSignReturnAddressScope() !=
1184 getModule().addModuleFlag(llvm::Module::Override,
1185 "sign-return-address-buildattr", 1);
1186 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1187 getModule().addModuleFlag(llvm::Module::Override,
1188 "tag-stack-memory-buildattr", 1);
1189
1190 if (T.isARM() || T.isThumb() || T.isAArch64()) {
1191 if (LangOpts.BranchTargetEnforcement)
1192 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1193 1);
1194 if (LangOpts.BranchProtectionPAuthLR)
1195 getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr",
1196 1);
1197 if (LangOpts.GuardedControlStack)
1198 getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1);
1199 if (LangOpts.hasSignReturnAddress())
1200 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
1201 if (LangOpts.isSignReturnAddressScopeAll())
1202 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1203 1);
1204 if (!LangOpts.isSignReturnAddressWithAKey())
1205 getModule().addModuleFlag(llvm::Module::Min,
1206 "sign-return-address-with-bkey", 1);
1207
1208 if (getTriple().isOSLinux()) {
1209 assert(getTriple().isOSBinFormatELF());
1210 using namespace llvm::ELF;
1211 uint64_t PAuthABIVersion =
1212 (LangOpts.PointerAuthIntrinsics
1213 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1214 (LangOpts.PointerAuthCalls
1215 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1216 (LangOpts.PointerAuthReturns
1217 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1218 (LangOpts.PointerAuthAuthTraps
1219 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1220 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1221 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1222 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1223 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1224 (LangOpts.PointerAuthInitFini
1225 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1226 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1227 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1228 (LangOpts.PointerAuthELFGOT
1229 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1230 (LangOpts.PointerAuthIndirectGotos
1231 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1232 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1233 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1234 (LangOpts.PointerAuthFunctionTypeDiscrimination
1235 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1236 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1237 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1238 "Update when new enum items are defined");
1239 if (PAuthABIVersion != 0) {
1240 getModule().addModuleFlag(llvm::Module::Error,
1241 "aarch64-elf-pauthabi-platform",
1242 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1243 getModule().addModuleFlag(llvm::Module::Error,
1244 "aarch64-elf-pauthabi-version",
1245 PAuthABIVersion);
1246 }
1247 }
1248 }
1249
1250 if (CodeGenOpts.StackClashProtector)
1251 getModule().addModuleFlag(
1252 llvm::Module::Override, "probe-stack",
1253 llvm::MDString::get(TheModule.getContext(), "inline-asm"));
1254
1255 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1256 getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
1257 CodeGenOpts.StackProbeSize);
1258
1259 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1260 llvm::LLVMContext &Ctx = TheModule.getContext();
1261 getModule().addModuleFlag(
1262 llvm::Module::Error, "MemProfProfileFilename",
1263 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1264 }
1265
1266 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
1267 // Indicate whether __nvvm_reflect should be configured to flush denormal
1268 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
1269 // property.)
1270 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
1271 CodeGenOpts.FP32DenormalMode.Output !=
1272 llvm::DenormalMode::IEEE);
1273 }
1274
1275 if (LangOpts.EHAsynch)
1276 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1277
1278 // Indicate whether this Module was compiled with -fopenmp
1279 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1280 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
1281 if (getLangOpts().OpenMPIsTargetDevice)
1282 getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1283 LangOpts.OpenMP);
1284
1285 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
1286 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
1287 EmitOpenCLMetadata();
1288 // Emit SPIR version.
1289 if (getTriple().isSPIR()) {
1290 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
1291 // opencl.spir.version named metadata.
1292 // C++ for OpenCL has a distinct mapping for version compatibility with
1293 // OpenCL.
1294 auto Version = LangOpts.getOpenCLCompatibleVersion();
1295 llvm::Metadata *SPIRVerElts[] = {
1296 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1297 Int32Ty, Version / 100)),
1298 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1299 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1300 llvm::NamedMDNode *SPIRVerMD =
1301 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
1302 llvm::LLVMContext &Ctx = TheModule.getContext();
1303 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1304 }
1305 }
1306
1307 // HLSL related end of code gen work items.
1308 if (LangOpts.HLSL)
1310
1311 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1312 assert(PLevel < 3 && "Invalid PIC Level");
1313 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
1314 if (Context.getLangOpts().PIE)
1315 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
1316 }
1317
1318 if (getCodeGenOpts().CodeModel.size() > 0) {
1319 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
1320 .Case("tiny", llvm::CodeModel::Tiny)
1321 .Case("small", llvm::CodeModel::Small)
1322 .Case("kernel", llvm::CodeModel::Kernel)
1323 .Case("medium", llvm::CodeModel::Medium)
1324 .Case("large", llvm::CodeModel::Large)
1325 .Default(~0u);
1326 if (CM != ~0u) {
1327 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
1328 getModule().setCodeModel(codeModel);
1329
1330 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1331 Context.getTargetInfo().getTriple().getArch() ==
1332 llvm::Triple::x86_64) {
1333 getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold);
1334 }
1335 }
1336 }
1337
1338 if (CodeGenOpts.NoPLT)
1339 getModule().setRtLibUseGOT();
1340 if (getTriple().isOSBinFormatELF() &&
1341 CodeGenOpts.DirectAccessExternalData !=
1342 getModule().getDirectAccessExternalData()) {
1343 getModule().setDirectAccessExternalData(
1344 CodeGenOpts.DirectAccessExternalData);
1345 }
1346 if (CodeGenOpts.UnwindTables)
1347 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1348
1349 switch (CodeGenOpts.getFramePointer()) {
1351 // 0 ("none") is the default.
1352 break;
1354 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1355 break;
1357 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1358 break;
1360 getModule().setFramePointer(llvm::FramePointerKind::All);
1361 break;
1362 }
1363
1364 SimplifyPersonality();
1365
1366 if (getCodeGenOpts().EmitDeclMetadata)
1367 EmitDeclMetadata();
1368
1369 if (getCodeGenOpts().CoverageNotesFile.size() ||
1370 getCodeGenOpts().CoverageDataFile.size())
1371 EmitCoverageFile();
1372
1373 if (CGDebugInfo *DI = getModuleDebugInfo())
1374 DI->finalize();
1375
1376 if (getCodeGenOpts().EmitVersionIdentMetadata)
1377 EmitVersionIdentMetadata();
1378
1379 if (!getCodeGenOpts().RecordCommandLine.empty())
1380 EmitCommandLineMetadata();
1381
1382 if (!getCodeGenOpts().StackProtectorGuard.empty())
1383 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1384 if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1385 getModule().setStackProtectorGuardReg(
1386 getCodeGenOpts().StackProtectorGuardReg);
1387 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1388 getModule().setStackProtectorGuardSymbol(
1389 getCodeGenOpts().StackProtectorGuardSymbol);
1390 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1391 getModule().setStackProtectorGuardOffset(
1392 getCodeGenOpts().StackProtectorGuardOffset);
1393 if (getCodeGenOpts().StackAlignment)
1394 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1395 if (getCodeGenOpts().SkipRaxSetup)
1396 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1397 if (getLangOpts().RegCall4)
1398 getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1399
1400 if (getContext().getTargetInfo().getMaxTLSAlign())
1401 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
1402 getContext().getTargetInfo().getMaxTLSAlign());
1403
1405
1406 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
1407
1408 EmitBackendOptionsMetadata(getCodeGenOpts());
1409
1410 // If there is device offloading code embed it in the host now.
1411 EmbedObject(&getModule(), CodeGenOpts, getDiags());
1412
1413 // Set visibility from DLL storage class
1414 // We do this at the end of LLVM IR generation; after any operation
1415 // that might affect the DLL storage class or the visibility, and
1416 // before anything that might act on these.
1418
1419 // Check the tail call symbols are truly undefined.
1420 if (getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1421 for (auto &I : MustTailCallUndefinedGlobals) {
1422 if (!I.first->isDefined())
1423 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1424 else {
1425 StringRef MangledName = getMangledName(GlobalDecl(I.first));
1426 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1427 if (!Entry || Entry->isWeakForLinker() ||
1428 Entry->isDeclarationForLinker())
1429 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1430 }
1431 }
1432 }
1433}
1434
1435void CodeGenModule::EmitOpenCLMetadata() {
1436 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
1437 // opencl.ocl.version named metadata node.
1438 // C++ for OpenCL has a distinct mapping for versions compatible with OpenCL.
1439 auto CLVersion = LangOpts.getOpenCLCompatibleVersion();
1440
1441 auto EmitVersion = [this](StringRef MDName, int Version) {
1442 llvm::Metadata *OCLVerElts[] = {
1443 llvm::ConstantAsMetadata::get(
1444 llvm::ConstantInt::get(Int32Ty, Version / 100)),
1445 llvm::ConstantAsMetadata::get(
1446 llvm::ConstantInt::get(Int32Ty, (Version % 100) / 10))};
1447 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1448 llvm::LLVMContext &Ctx = TheModule.getContext();
1449 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1450 };
1451
1452 EmitVersion("opencl.ocl.version", CLVersion);
1453 if (LangOpts.OpenCLCPlusPlus) {
1454 // In addition to the OpenCL compatible version, emit the C++ version.
1455 EmitVersion("opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1456 }
1457}
1458
1459void CodeGenModule::EmitBackendOptionsMetadata(
1460 const CodeGenOptions &CodeGenOpts) {
1461 if (getTriple().isRISCV()) {
1462 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
1463 CodeGenOpts.SmallDataLimit);
1464 }
1465}
1466
1468 // Make sure that this type is translated.
1470}
1471
1473 // Make sure that this type is translated.
1475}
1476
1478 if (!TBAA)
1479 return nullptr;
1480 return TBAA->getTypeInfo(QTy);
1481}
1482
1484 if (!TBAA)
1485 return TBAAAccessInfo();
1486 if (getLangOpts().CUDAIsDevice) {
1487 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1488 // access info.
1489 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1490 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1491 nullptr)
1492 return TBAAAccessInfo();
1493 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1494 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1495 nullptr)
1496 return TBAAAccessInfo();
1497 }
1498 }
1499 return TBAA->getAccessInfo(AccessType);
1500}
1501
1504 if (!TBAA)
1505 return TBAAAccessInfo();
1506 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1507}
1508
1510 if (!TBAA)
1511 return nullptr;
1512 return TBAA->getTBAAStructInfo(QTy);
1513}
1514
1516 if (!TBAA)
1517 return nullptr;
1518 return TBAA->getBaseTypeInfo(QTy);
1519}
1520
1522 if (!TBAA)
1523 return nullptr;
1524 return TBAA->getAccessTagInfo(Info);
1525}
1526
1529 if (!TBAA)
1530 return TBAAAccessInfo();
1531 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1532}
1533
1536 TBAAAccessInfo InfoB) {
1537 if (!TBAA)
1538 return TBAAAccessInfo();
1539 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1540}
1541
1544 TBAAAccessInfo SrcInfo) {
1545 if (!TBAA)
1546 return TBAAAccessInfo();
1547 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1548}
1549
1551 TBAAAccessInfo TBAAInfo) {
1552 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1553 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1554}
1555
1557 llvm::Instruction *I, const CXXRecordDecl *RD) {
1558 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1559 llvm::MDNode::get(getLLVMContext(), {}));
1560}
1561
1562void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1563 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1564 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1565}
1566
1567/// ErrorUnsupported - Print out an error that codegen doesn't support the
1568/// specified stmt yet.
1569void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1571 "cannot compile this %0 yet");
1572 std::string Msg = Type;
1573 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
1574 << Msg << S->getSourceRange();
1575}
1576
1577/// ErrorUnsupported - Print out an error that codegen doesn't support the
1578/// specified decl yet.
1579void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1581 "cannot compile this %0 yet");
1582 std::string Msg = Type;
1583 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
1584}
1585
1586llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1587 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1588}
1589
1590void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1591 const NamedDecl *D) const {
1592 // Internal definitions always have default visibility.
1593 if (GV->hasLocalLinkage()) {
1594 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1595 return;
1596 }
1597 if (!D)
1598 return;
1599
1600 // Set visibility for definitions, and for declarations if requested globally
1601 // or set explicitly.
1602 LinkageInfo LV = D->getLinkageAndVisibility();
1603
1604 // OpenMP declare target variables must be visible to the host so they can
1605 // be registered. We require protected visibility unless the variable has
1606 // the DT_nohost modifier and does not need to be registered.
1607 if (Context.getLangOpts().OpenMP &&
1608 Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
1609 D->hasAttr<OMPDeclareTargetDeclAttr>() &&
1610 D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1611 OMPDeclareTargetDeclAttr::DT_NoHost &&
1613 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1614 return;
1615 }
1616
1617 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1618 // Reject incompatible dlllstorage and visibility annotations.
1619 if (!LV.isVisibilityExplicit())
1620 return;
1621 if (GV->hasDLLExportStorageClass()) {
1622 if (LV.getVisibility() == HiddenVisibility)
1624 diag::err_hidden_visibility_dllexport);
1625 } else if (LV.getVisibility() != DefaultVisibility) {
1627 diag::err_non_default_visibility_dllimport);
1628 }
1629 return;
1630 }
1631
1632 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1633 !GV->isDeclarationForLinker())
1634 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1635}
1636
1638 llvm::GlobalValue *GV) {
1639 if (GV->hasLocalLinkage())
1640 return true;
1641
1642 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1643 return true;
1644
1645 // DLLImport explicitly marks the GV as external.
1646 if (GV->hasDLLImportStorageClass())
1647 return false;
1648
1649 const llvm::Triple &TT = CGM.getTriple();
1650 const auto &CGOpts = CGM.getCodeGenOpts();
1651 if (TT.isWindowsGNUEnvironment()) {
1652 // In MinGW, variables without DLLImport can still be automatically
1653 // imported from a DLL by the linker; don't mark variables that
1654 // potentially could come from another DLL as DSO local.
1655
1656 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1657 // (and this actually happens in the public interface of libstdc++), so
1658 // such variables can't be marked as DSO local. (Native TLS variables
1659 // can't be dllimported at all, though.)
1660 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1661 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) &&
1662 CGOpts.AutoImport)
1663 return false;
1664 }
1665
1666 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1667 // remain unresolved in the link, they can be resolved to zero, which is
1668 // outside the current DSO.
1669 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1670 return false;
1671
1672 // Every other GV is local on COFF.
1673 // Make an exception for windows OS in the triple: Some firmware builds use
1674 // *-win32-macho triples. This (accidentally?) produced windows relocations
1675 // without GOT tables in older clang versions; Keep this behaviour.
1676 // FIXME: even thread local variables?
1677 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1678 return true;
1679
1680 // Only handle COFF and ELF for now.
1681 if (!TT.isOSBinFormatELF())
1682 return false;
1683
1684 // If this is not an executable, don't assume anything is local.
1685 llvm::Reloc::Model RM = CGOpts.RelocationModel;
1686 const auto &LOpts = CGM.getLangOpts();
1687 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1688 // On ELF, if -fno-semantic-interposition is specified and the target
1689 // supports local aliases, there will be neither CC1
1690 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1691 // dso_local on the function if using a local alias is preferable (can avoid
1692 // PLT indirection).
1693 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1694 return false;
1695 return !(CGM.getLangOpts().SemanticInterposition ||
1696 CGM.getLangOpts().HalfNoSemanticInterposition);
1697 }
1698
1699 // A definition cannot be preempted from an executable.
1700 if (!GV->isDeclarationForLinker())
1701 return true;
1702
1703 // Most PIC code sequences that assume that a symbol is local cannot produce a
1704 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1705 // depended, it seems worth it to handle it here.
1706 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1707 return false;
1708
1709 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1710 if (TT.isPPC64())
1711 return false;
1712
1713 if (CGOpts.DirectAccessExternalData) {
1714 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1715 // for non-thread-local variables. If the symbol is not defined in the
1716 // executable, a copy relocation will be needed at link time. dso_local is
1717 // excluded for thread-local variables because they generally don't support
1718 // copy relocations.
1719 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1720 if (!Var->isThreadLocal())
1721 return true;
1722
1723 // -fno-pic sets dso_local on a function declaration to allow direct
1724 // accesses when taking its address (similar to a data symbol). If the
1725 // function is not defined in the executable, a canonical PLT entry will be
1726 // needed at link time. -fno-direct-access-external-data can avoid the
1727 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1728 // it could just cause trouble without providing perceptible benefits.
1729 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1730 return true;
1731 }
1732
1733 // If we can use copy relocations we can assume it is local.
1734
1735 // Otherwise don't assume it is local.
1736 return false;
1737}
1738
1739void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1740 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1741}
1742
1743void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1744 GlobalDecl GD) const {
1745 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1746 // C++ destructors have a few C++ ABI specific special cases.
1747 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1749 return;
1750 }
1752}
1753
1754void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1755 const NamedDecl *D) const {
1756 if (D && D->isExternallyVisible()) {
1757 if (D->hasAttr<DLLImportAttr>())
1758 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1759 else if ((D->hasAttr<DLLExportAttr>() ||
1761 !GV->isDeclarationForLinker())
1762 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1763 }
1764}
1765
1766void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1767 GlobalDecl GD) const {
1768 setDLLImportDLLExport(GV, GD);
1769 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1770}
1771
1772void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1773 const NamedDecl *D) const {
1775 setGVPropertiesAux(GV, D);
1776}
1777
1778void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1779 const NamedDecl *D) const {
1781 setDSOLocal(GV);
1782 GV->setPartition(CodeGenOpts.SymbolPartition);
1783}
1784
1785static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1786 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1787 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1788 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1789 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1790 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1791}
1792
1793llvm::GlobalVariable::ThreadLocalMode
1795 switch (CodeGenOpts.getDefaultTLSModel()) {
1797 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1799 return llvm::GlobalVariable::LocalDynamicTLSModel;
1801 return llvm::GlobalVariable::InitialExecTLSModel;
1803 return llvm::GlobalVariable::LocalExecTLSModel;
1804 }
1805 llvm_unreachable("Invalid TLS model!");
1806}
1807
1808void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1809 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1810
1811 llvm::GlobalValue::ThreadLocalMode TLM;
1812 TLM = GetDefaultLLVMTLSModel();
1813
1814 // Override the TLS model if it is explicitly specified.
1815 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1816 TLM = GetLLVMTLSModel(Attr->getModel());
1817 }
1818
1819 GV->setThreadLocalMode(TLM);
1820}
1821
1822static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1823 StringRef Name) {
1824 const TargetInfo &Target = CGM.getTarget();
1825 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1826}
1827
1829 const CPUSpecificAttr *Attr,
1830 unsigned CPUIndex,
1831 raw_ostream &Out) {
1832 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1833 // supported.
1834 if (Attr)
1835 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1836 else if (CGM.getTarget().supportsIFunc())
1837 Out << ".resolver";
1838}
1839
1840// Returns true if GD is a function decl with internal linkage and
1841// needs a unique suffix after the mangled name.
1843 CodeGenModule &CGM) {
1844 const Decl *D = GD.getDecl();
1845 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1846 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1847}
1848
1849static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1850 const NamedDecl *ND,
1851 bool OmitMultiVersionMangling = false) {
1852 SmallString<256> Buffer;
1853 llvm::raw_svector_ostream Out(Buffer);
1855 if (!CGM.getModuleNameHash().empty())
1857 bool ShouldMangle = MC.shouldMangleDeclName(ND);
1858 if (ShouldMangle)
1859 MC.mangleName(GD.getWithDecl(ND), Out);
1860 else {
1861 IdentifierInfo *II = ND->getIdentifier();
1862 assert(II && "Attempt to mangle unnamed decl.");
1863 const auto *FD = dyn_cast<FunctionDecl>(ND);
1864
1865 if (FD &&
1866 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1867 if (CGM.getLangOpts().RegCall4)
1868 Out << "__regcall4__" << II->getName();
1869 else
1870 Out << "__regcall3__" << II->getName();
1871 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1873 Out << "__device_stub__" << II->getName();
1874 } else {
1875 Out << II->getName();
1876 }
1877 }
1878
1879 // Check if the module name hash should be appended for internal linkage
1880 // symbols. This should come before multi-version target suffixes are
1881 // appended. This is to keep the name and module hash suffix of the
1882 // internal linkage function together. The unique suffix should only be
1883 // added when name mangling is done to make sure that the final name can
1884 // be properly demangled. For example, for C functions without prototypes,
1885 // name mangling is not done and the unique suffix should not be appeneded
1886 // then.
1887 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1888 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1889 "Hash computed when not explicitly requested");
1890 Out << CGM.getModuleNameHash();
1891 }
1892
1893 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1894 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1895 switch (FD->getMultiVersionKind()) {
1899 FD->getAttr<CPUSpecificAttr>(),
1900 GD.getMultiVersionIndex(), Out);
1901 break;
1903 auto *Attr = FD->getAttr<TargetAttr>();
1904 assert(Attr && "Expected TargetAttr to be present "
1905 "for attribute mangling");
1906 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1907 Info.appendAttributeMangling(Attr, Out);
1908 break;
1909 }
1911 auto *Attr = FD->getAttr<TargetVersionAttr>();
1912 assert(Attr && "Expected TargetVersionAttr to be present "
1913 "for attribute mangling");
1914 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1915 Info.appendAttributeMangling(Attr, Out);
1916 break;
1917 }
1919 auto *Attr = FD->getAttr<TargetClonesAttr>();
1920 assert(Attr && "Expected TargetClonesAttr to be present "
1921 "for attribute mangling");
1922 unsigned Index = GD.getMultiVersionIndex();
1923 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1924 Info.appendAttributeMangling(Attr, Index, Out);
1925 break;
1926 }
1928 llvm_unreachable("None multiversion type isn't valid here");
1929 }
1930 }
1931
1932 // Make unique name for device side static file-scope variable for HIP.
1933 if (CGM.getContext().shouldExternalize(ND) &&
1934 CGM.getLangOpts().GPURelocatableDeviceCode &&
1935 CGM.getLangOpts().CUDAIsDevice)
1937
1938 return std::string(Out.str());
1939}
1940
1941void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1942 const FunctionDecl *FD,
1943 StringRef &CurName) {
1944 if (!FD->isMultiVersion())
1945 return;
1946
1947 // Get the name of what this would be without the 'target' attribute. This
1948 // allows us to lookup the version that was emitted when this wasn't a
1949 // multiversion function.
1950 std::string NonTargetName =
1951 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1952 GlobalDecl OtherGD;
1953 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1954 assert(OtherGD.getCanonicalDecl()
1955 .getDecl()
1956 ->getAsFunction()
1957 ->isMultiVersion() &&
1958 "Other GD should now be a multiversioned function");
1959 // OtherFD is the version of this function that was mangled BEFORE
1960 // becoming a MultiVersion function. It potentially needs to be updated.
1961 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1962 .getDecl()
1963 ->getAsFunction()
1965 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1966 // This is so that if the initial version was already the 'default'
1967 // version, we don't try to update it.
1968 if (OtherName != NonTargetName) {
1969 // Remove instead of erase, since others may have stored the StringRef
1970 // to this.
1971 const auto ExistingRecord = Manglings.find(NonTargetName);
1972 if (ExistingRecord != std::end(Manglings))
1973 Manglings.remove(&(*ExistingRecord));
1974 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1975 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
1976 Result.first->first();
1977 // If this is the current decl is being created, make sure we update the name.
1978 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
1979 CurName = OtherNameRef;
1980 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1981 Entry->setName(OtherName);
1982 }
1983 }
1984}
1985
1987 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1988
1989 // Some ABIs don't have constructor variants. Make sure that base and
1990 // complete constructors get mangled the same.
1991 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1992 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1993 CXXCtorType OrigCtorType = GD.getCtorType();
1994 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1995 if (OrigCtorType == Ctor_Base)
1996 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1997 }
1998 }
1999
2000 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
2001 // static device variable depends on whether the variable is referenced by
2002 // a host or device host function. Therefore the mangled name cannot be
2003 // cached.
2004 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
2005 auto FoundName = MangledDeclNames.find(CanonicalGD);
2006 if (FoundName != MangledDeclNames.end())
2007 return FoundName->second;
2008 }
2009
2010 // Keep the first result in the case of a mangling collision.
2011 const auto *ND = cast<NamedDecl>(GD.getDecl());
2012 std::string MangledName = getMangledNameImpl(*this, GD, ND);
2013
2014 // Ensure either we have different ABIs between host and device compilations,
2015 // says host compilation following MSVC ABI but device compilation follows
2016 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
2017 // mangling should be the same after name stubbing. The later checking is
2018 // very important as the device kernel name being mangled in host-compilation
2019 // is used to resolve the device binaries to be executed. Inconsistent naming
2020 // result in undefined behavior. Even though we cannot check that naming
2021 // directly between host- and device-compilations, the host- and
2022 // device-mangling in host compilation could help catching certain ones.
2023 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2024 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
2025 (getContext().getAuxTargetInfo() &&
2026 (getContext().getAuxTargetInfo()->getCXXABI() !=
2027 getContext().getTargetInfo().getCXXABI())) ||
2028 getCUDARuntime().getDeviceSideName(ND) ==
2030 *this,
2032 ND));
2033
2034 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2035 return MangledDeclNames[CanonicalGD] = Result.first->first();
2036}
2037
2039 const BlockDecl *BD) {
2040 MangleContext &MangleCtx = getCXXABI().getMangleContext();
2041 const Decl *D = GD.getDecl();
2042
2043 SmallString<256> Buffer;
2044 llvm::raw_svector_ostream Out(Buffer);
2045 if (!D)
2046 MangleCtx.mangleGlobalBlock(BD,
2047 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2048 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2049 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
2050 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2051 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
2052 else
2053 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
2054
2055 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2056 return Result.first->first();
2057}
2058
2060 auto it = MangledDeclNames.begin();
2061 while (it != MangledDeclNames.end()) {
2062 if (it->second == Name)
2063 return it->first;
2064 it++;
2065 }
2066 return GlobalDecl();
2067}
2068
2069llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
2070 return getModule().getNamedValue(Name);
2071}
2072
2073/// AddGlobalCtor - Add a function to the list that will be called before
2074/// main() runs.
2075void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2076 unsigned LexOrder,
2077 llvm::Constant *AssociatedData) {
2078 // FIXME: Type coercion of void()* types.
2079 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
2080}
2081
2082/// AddGlobalDtor - Add a function to the list that will be called
2083/// when the module is unloaded.
2084void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2085 bool IsDtorAttrFunc) {
2086 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2087 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
2088 DtorsUsingAtExit[Priority].push_back(Dtor);
2089 return;
2090 }
2091
2092 // FIXME: Type coercion of void()* types.
2093 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
2094}
2095
2096void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
2097 if (Fns.empty()) return;
2098
2099 const PointerAuthSchema &InitFiniAuthSchema =
2101
2102 // Ctor function type is ptr.
2103 llvm::PointerType *PtrTy = llvm::PointerType::get(
2104 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2105
2106 // Get the type of a ctor entry, { i32, ptr, ptr }.
2107 llvm::StructType *CtorStructTy = llvm::StructType::get(Int32Ty, PtrTy, PtrTy);
2108
2109 // Construct the constructor and destructor arrays.
2110 ConstantInitBuilder Builder(*this);
2111 auto Ctors = Builder.beginArray(CtorStructTy);
2112 for (const auto &I : Fns) {
2113 auto Ctor = Ctors.beginStruct(CtorStructTy);
2114 Ctor.addInt(Int32Ty, I.Priority);
2115 if (InitFiniAuthSchema) {
2116 llvm::Constant *StorageAddress =
2117 (InitFiniAuthSchema.isAddressDiscriminated()
2118 ? llvm::ConstantExpr::getIntToPtr(
2119 llvm::ConstantInt::get(
2120 IntPtrTy,
2121 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2122 PtrTy)
2123 : nullptr);
2124 llvm::Constant *SignedCtorPtr = getConstantSignedPointer(
2125 I.Initializer, InitFiniAuthSchema.getKey(), StorageAddress,
2126 llvm::ConstantInt::get(
2127 SizeTy, InitFiniAuthSchema.getConstantDiscrimination()));
2128 Ctor.add(SignedCtorPtr);
2129 } else {
2130 Ctor.add(I.Initializer);
2131 }
2132 if (I.AssociatedData)
2133 Ctor.add(I.AssociatedData);
2134 else
2135 Ctor.addNullPointer(PtrTy);
2136 Ctor.finishAndAddTo(Ctors);
2137 }
2138
2139 auto List = Ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
2140 /*constant*/ false,
2141 llvm::GlobalValue::AppendingLinkage);
2142
2143 // The LTO linker doesn't seem to like it when we set an alignment
2144 // on appending variables. Take it off as a workaround.
2145 List->setAlignment(std::nullopt);
2146
2147 Fns.clear();
2148}
2149
2150llvm::GlobalValue::LinkageTypes
2152 const auto *D = cast<FunctionDecl>(GD.getDecl());
2153
2155
2156 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2158
2160}
2161
2162llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
2163 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2164 if (!MDS) return nullptr;
2165
2166 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
2167}
2168
2170 if (auto *FnType = T->getAs<FunctionProtoType>())
2172 FnType->getReturnType(), FnType->getParamTypes(),
2173 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2174
2175 std::string OutName;
2176 llvm::raw_string_ostream Out(OutName);
2178 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2179
2180 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2181 Out << ".normalized";
2182
2183 return llvm::ConstantInt::get(Int32Ty,
2184 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2185}
2186
2188 const CGFunctionInfo &Info,
2189 llvm::Function *F, bool IsThunk) {
2190 unsigned CallingConv;
2191 llvm::AttributeList PAL;
2192 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2193 /*AttrOnCallSite=*/false, IsThunk);
2194 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
2195 getTarget().getTriple().isWindowsArm64EC()) {
2197 if (const Decl *D = GD.getDecl())
2198 Loc = D->getLocation();
2199
2200 Error(Loc, "__vectorcall calling convention is not currently supported");
2201 }
2202 F->setAttributes(PAL);
2203 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2204}
2205
2206static void removeImageAccessQualifier(std::string& TyName) {
2207 std::string ReadOnlyQual("__read_only");
2208 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2209 if (ReadOnlyPos != std::string::npos)
2210 // "+ 1" for the space after access qualifier.
2211 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2212 else {
2213 std::string WriteOnlyQual("__write_only");
2214 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2215 if (WriteOnlyPos != std::string::npos)
2216 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2217 else {
2218 std::string ReadWriteQual("__read_write");
2219 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2220 if (ReadWritePos != std::string::npos)
2221 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2222 }
2223 }
2224}
2225
2226// Returns the address space id that should be produced to the
2227// kernel_arg_addr_space metadata. This is always fixed to the ids
2228// as specified in the SPIR 2.0 specification in order to differentiate
2229// for example in clGetKernelArgInfo() implementation between the address
2230// spaces with targets without unique mapping to the OpenCL address spaces
2231// (basically all single AS CPUs).
2232static unsigned ArgInfoAddressSpace(LangAS AS) {
2233 switch (AS) {
2235 return 1;
2237 return 2;
2239 return 3;
2241 return 4; // Not in SPIR 2.0 specs.
2243 return 5;
2245 return 6;
2246 default:
2247 return 0; // Assume private.
2248 }
2249}
2250
2252 const FunctionDecl *FD,
2253 CodeGenFunction *CGF) {
2254 assert(((FD && CGF) || (!FD && !CGF)) &&
2255 "Incorrect use - FD and CGF should either be both null or not!");
2256 // Create MDNodes that represent the kernel arg metadata.
2257 // Each MDNode is a list in the form of "key", N number of values which is
2258 // the same number of values as their are kernel arguments.
2259
2260 const PrintingPolicy &Policy = Context.getPrintingPolicy();
2261
2262 // MDNode for the kernel argument address space qualifiers.
2264
2265 // MDNode for the kernel argument access qualifiers (images only).
2267
2268 // MDNode for the kernel argument type names.
2270
2271 // MDNode for the kernel argument base type names.
2272 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2273
2274 // MDNode for the kernel argument type qualifiers.
2276
2277 // MDNode for the kernel argument names.
2279
2280 if (FD && CGF)
2281 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2282 const ParmVarDecl *parm = FD->getParamDecl(i);
2283 // Get argument name.
2284 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2285
2286 if (!getLangOpts().OpenCL)
2287 continue;
2288 QualType ty = parm->getType();
2289 std::string typeQuals;
2290
2291 // Get image and pipe access qualifier:
2292 if (ty->isImageType() || ty->isPipeType()) {
2293 const Decl *PDecl = parm;
2294 if (const auto *TD = ty->getAs<TypedefType>())
2295 PDecl = TD->getDecl();
2296 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2297 if (A && A->isWriteOnly())
2298 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2299 else if (A && A->isReadWrite())
2300 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2301 else
2302 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2303 } else
2304 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2305
2306 auto getTypeSpelling = [&](QualType Ty) {
2307 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2308
2309 if (Ty.isCanonical()) {
2310 StringRef typeNameRef = typeName;
2311 // Turn "unsigned type" to "utype"
2312 if (typeNameRef.consume_front("unsigned "))
2313 return std::string("u") + typeNameRef.str();
2314 if (typeNameRef.consume_front("signed "))
2315 return typeNameRef.str();
2316 }
2317
2318 return typeName;
2319 };
2320
2321 if (ty->isPointerType()) {
2322 QualType pointeeTy = ty->getPointeeType();
2323
2324 // Get address qualifier.
2325 addressQuals.push_back(
2326 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2327 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2328
2329 // Get argument type name.
2330 std::string typeName = getTypeSpelling(pointeeTy) + "*";
2331 std::string baseTypeName =
2332 getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2333 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2334 argBaseTypeNames.push_back(
2335 llvm::MDString::get(VMContext, baseTypeName));
2336
2337 // Get argument type qualifiers:
2338 if (ty.isRestrictQualified())
2339 typeQuals = "restrict";
2340 if (pointeeTy.isConstQualified() ||
2342 typeQuals += typeQuals.empty() ? "const" : " const";
2343 if (pointeeTy.isVolatileQualified())
2344 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2345 } else {
2346 uint32_t AddrSpc = 0;
2347 bool isPipe = ty->isPipeType();
2348 if (ty->isImageType() || isPipe)
2350
2351 addressQuals.push_back(
2352 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2353
2354 // Get argument type name.
2355 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2356 std::string typeName = getTypeSpelling(ty);
2357 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2358
2359 // Remove access qualifiers on images
2360 // (as they are inseparable from type in clang implementation,
2361 // but OpenCL spec provides a special query to get access qualifier
2362 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2363 if (ty->isImageType()) {
2365 removeImageAccessQualifier(baseTypeName);
2366 }
2367
2368 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2369 argBaseTypeNames.push_back(
2370 llvm::MDString::get(VMContext, baseTypeName));
2371
2372 if (isPipe)
2373 typeQuals = "pipe";
2374 }
2375 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2376 }
2377
2378 if (getLangOpts().OpenCL) {
2379 Fn->setMetadata("kernel_arg_addr_space",
2380 llvm::MDNode::get(VMContext, addressQuals));
2381 Fn->setMetadata("kernel_arg_access_qual",
2382 llvm::MDNode::get(VMContext, accessQuals));
2383 Fn->setMetadata("kernel_arg_type",
2384 llvm::MDNode::get(VMContext, argTypeNames));
2385 Fn->setMetadata("kernel_arg_base_type",
2386 llvm::MDNode::get(VMContext, argBaseTypeNames));
2387 Fn->setMetadata("kernel_arg_type_qual",
2388 llvm::MDNode::get(VMContext, argTypeQuals));
2389 }
2390 if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2391 getCodeGenOpts().HIPSaveKernelArgName)
2392 Fn->setMetadata("kernel_arg_name",
2393 llvm::MDNode::get(VMContext, argNames));
2394}
2395
2396/// Determines whether the language options require us to model
2397/// unwind exceptions. We treat -fexceptions as mandating this
2398/// except under the fragile ObjC ABI with only ObjC exceptions
2399/// enabled. This means, for example, that C with -fexceptions
2400/// enables this.
2401static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2402 // If exceptions are completely disabled, obviously this is false.
2403 if (!LangOpts.Exceptions) return false;
2404
2405 // If C++ exceptions are enabled, this is true.
2406 if (LangOpts.CXXExceptions) return true;
2407
2408 // If ObjC exceptions are enabled, this depends on the ABI.
2409 if (LangOpts.ObjCExceptions) {
2410 return LangOpts.ObjCRuntime.hasUnwindExceptions();
2411 }
2412
2413 return true;
2414}
2415
2417 const CXXMethodDecl *MD) {
2418 // Check that the type metadata can ever actually be used by a call.
2419 if (!CGM.getCodeGenOpts().LTOUnit ||
2421 return false;
2422
2423 // Only functions whose address can be taken with a member function pointer
2424 // need this sort of type metadata.
2425 return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
2426 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2427}
2428
2431 llvm::SetVector<const CXXRecordDecl *> MostBases;
2432
2433 std::function<void (const CXXRecordDecl *)> CollectMostBases;
2434 CollectMostBases = [&](const CXXRecordDecl *RD) {
2435 if (RD->getNumBases() == 0)
2436 MostBases.insert(RD);
2437 for (const CXXBaseSpecifier &B : RD->bases())
2438 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2439 };
2440 CollectMostBases(RD);
2441 return MostBases.takeVector();
2442}
2443
2445 llvm::Function *F) {
2446 llvm::AttrBuilder B(F->getContext());
2447
2448 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2449 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2450
2451 if (CodeGenOpts.StackClashProtector)
2452 B.addAttribute("probe-stack", "inline-asm");
2453
2454 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2455 B.addAttribute("stack-probe-size",
2456 std::to_string(CodeGenOpts.StackProbeSize));
2457
2458 if (!hasUnwindExceptions(LangOpts))
2459 B.addAttribute(llvm::Attribute::NoUnwind);
2460
2461 if (D && D->hasAttr<NoStackProtectorAttr>())
2462 ; // Do nothing.
2463 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2465 B.addAttribute(llvm::Attribute::StackProtectStrong);
2466 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2467 B.addAttribute(llvm::Attribute::StackProtect);
2469 B.addAttribute(llvm::Attribute::StackProtectStrong);
2470 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
2471 B.addAttribute(llvm::Attribute::StackProtectReq);
2472
2473 if (!D) {
2474 // If we don't have a declaration to control inlining, the function isn't
2475 // explicitly marked as alwaysinline for semantic reasons, and inlining is
2476 // disabled, mark the function as noinline.
2477 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2478 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2479 B.addAttribute(llvm::Attribute::NoInline);
2480
2481 F->addFnAttrs(B);
2482 return;
2483 }
2484
2485 // Handle SME attributes that apply to function definitions,
2486 // rather than to function prototypes.
2487 if (D->hasAttr<ArmLocallyStreamingAttr>())
2488 B.addAttribute("aarch64_pstate_sm_body");
2489
2490 if (auto *Attr = D->getAttr<ArmNewAttr>()) {
2491 if (Attr->isNewZA())
2492 B.addAttribute("aarch64_new_za");
2493 if (Attr->isNewZT0())
2494 B.addAttribute("aarch64_new_zt0");
2495 }
2496
2497 // Track whether we need to add the optnone LLVM attribute,
2498 // starting with the default for this optimization level.
2499 bool ShouldAddOptNone =
2500 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2501 // We can't add optnone in the following cases, it won't pass the verifier.
2502 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2503 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2504
2505 // Add optnone, but do so only if the function isn't always_inline.
2506 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2507 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2508 B.addAttribute(llvm::Attribute::OptimizeNone);
2509
2510 // OptimizeNone implies noinline; we should not be inlining such functions.
2511 B.addAttribute(llvm::Attribute::NoInline);
2512
2513 // We still need to handle naked functions even though optnone subsumes
2514 // much of their semantics.
2515 if (D->hasAttr<NakedAttr>())
2516 B.addAttribute(llvm::Attribute::Naked);
2517
2518 // OptimizeNone wins over OptimizeForSize and MinSize.
2519 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2520 F->removeFnAttr(llvm::Attribute::MinSize);
2521 } else if (D->hasAttr<NakedAttr>()) {
2522 // Naked implies noinline: we should not be inlining such functions.
2523 B.addAttribute(llvm::Attribute::Naked);
2524 B.addAttribute(llvm::Attribute::NoInline);
2525 } else if (D->hasAttr<NoDuplicateAttr>()) {
2526 B.addAttribute(llvm::Attribute::NoDuplicate);
2527 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2528 // Add noinline if the function isn't always_inline.
2529 B.addAttribute(llvm::Attribute::NoInline);
2530 } else if (D->hasAttr<AlwaysInlineAttr>() &&
2531 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2532 // (noinline wins over always_inline, and we can't specify both in IR)
2533 B.addAttribute(llvm::Attribute::AlwaysInline);
2534 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2535 // If we're not inlining, then force everything that isn't always_inline to
2536 // carry an explicit noinline attribute.
2537 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2538 B.addAttribute(llvm::Attribute::NoInline);
2539 } else {
2540 // Otherwise, propagate the inline hint attribute and potentially use its
2541 // absence to mark things as noinline.
2542 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2543 // Search function and template pattern redeclarations for inline.
2544 auto CheckForInline = [](const FunctionDecl *FD) {
2545 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2546 return Redecl->isInlineSpecified();
2547 };
2548 if (any_of(FD->redecls(), CheckRedeclForInline))
2549 return true;
2550 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2551 if (!Pattern)
2552 return false;
2553 return any_of(Pattern->redecls(), CheckRedeclForInline);
2554 };
2555 if (CheckForInline(FD)) {
2556 B.addAttribute(llvm::Attribute::InlineHint);
2557 } else if (CodeGenOpts.getInlining() ==
2559 !FD->isInlined() &&
2560 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2561 B.addAttribute(llvm::Attribute::NoInline);
2562 }
2563 }
2564 }
2565
2566 // Add other optimization related attributes if we are optimizing this
2567 // function.
2568 if (!D->hasAttr<OptimizeNoneAttr>()) {
2569 if (D->hasAttr<ColdAttr>()) {
2570 if (!ShouldAddOptNone)
2571 B.addAttribute(llvm::Attribute::OptimizeForSize);
2572 B.addAttribute(llvm::Attribute::Cold);
2573 }
2574 if (D->hasAttr<HotAttr>())
2575 B.addAttribute(llvm::Attribute::Hot);
2576 if (D->hasAttr<MinSizeAttr>())
2577 B.addAttribute(llvm::Attribute::MinSize);
2578 }
2579
2580 F->addFnAttrs(B);
2581
2582 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2583 if (alignment)
2584 F->setAlignment(llvm::Align(alignment));
2585
2586 if (!D->hasAttr<AlignedAttr>())
2587 if (LangOpts.FunctionAlignment)
2588 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2589
2590 // Some C++ ABIs require 2-byte alignment for member functions, in order to
2591 // reserve a bit for differentiating between virtual and non-virtual member
2592 // functions. If the current target's C++ ABI requires this and this is a
2593 // member function, set its alignment accordingly.
2594 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2595 if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
2596 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2597 }
2598
2599 // In the cross-dso CFI mode with canonical jump tables, we want !type
2600 // attributes on definitions only.
2601 if (CodeGenOpts.SanitizeCfiCrossDso &&
2602 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2603 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2604 // Skip available_externally functions. They won't be codegen'ed in the
2605 // current module anyway.
2606 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2608 }
2609 }
2610
2611 // Emit type metadata on member functions for member function pointer checks.
2612 // These are only ever necessary on definitions; we're guaranteed that the
2613 // definition will be present in the LTO unit as a result of LTO visibility.
2614 auto *MD = dyn_cast<CXXMethodDecl>(D);
2615 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2616 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2617 llvm::Metadata *Id =
2619 MD->getType(), Context.getRecordType(Base).getTypePtr()));
2620 F->addTypeMetadata(0, Id);
2621 }
2622 }
2623}
2624
2625void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2626 const Decl *D = GD.getDecl();
2627 if (isa_and_nonnull<NamedDecl>(D))
2628 setGVProperties(GV, GD);
2629 else
2630 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2631
2632 if (D && D->hasAttr<UsedAttr>())
2634
2635 if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2636 VD &&
2637 ((CodeGenOpts.KeepPersistentStorageVariables &&
2638 (VD->getStorageDuration() == SD_Static ||
2639 VD->getStorageDuration() == SD_Thread)) ||
2640 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2641 VD->getType().isConstQualified())))
2643}
2644
2645bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2646 llvm::AttrBuilder &Attrs,
2647 bool SetTargetFeatures) {
2648 // Add target-cpu and target-features attributes to functions. If
2649 // we have a decl for the function and it has a target attribute then
2650 // parse that and add it to the feature set.
2651 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2652 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2653 std::vector<std::string> Features;
2654 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2655 FD = FD ? FD->getMostRecentDecl() : FD;
2656 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2657 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2658 assert((!TD || !TV) && "both target_version and target specified");
2659 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2660 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2661 bool AddedAttr = false;
2662 if (TD || TV || SD || TC) {
2663 llvm::StringMap<bool> FeatureMap;
2664 getContext().getFunctionFeatureMap(FeatureMap, GD);
2665
2666 // Produce the canonical string for this set of features.
2667 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2668 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2669
2670 // Now add the target-cpu and target-features to the function.
2671 // While we populated the feature map above, we still need to
2672 // get and parse the target attribute so we can get the cpu for
2673 // the function.
2674 if (TD) {
2676 Target.parseTargetAttr(TD->getFeaturesStr());
2677 if (!ParsedAttr.CPU.empty() &&
2678 getTarget().isValidCPUName(ParsedAttr.CPU)) {
2679 TargetCPU = ParsedAttr.CPU;
2680 TuneCPU = ""; // Clear the tune CPU.
2681 }
2682 if (!ParsedAttr.Tune.empty() &&
2683 getTarget().isValidCPUName(ParsedAttr.Tune))
2684 TuneCPU = ParsedAttr.Tune;
2685 }
2686
2687 if (SD) {
2688 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2689 // favor this processor.
2690 TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2691 }
2692 } else {
2693 // Otherwise just add the existing target cpu and target features to the
2694 // function.
2695 Features = getTarget().getTargetOpts().Features;
2696 }
2697
2698 if (!TargetCPU.empty()) {
2699 Attrs.addAttribute("target-cpu", TargetCPU);
2700 AddedAttr = true;
2701 }
2702 if (!TuneCPU.empty()) {
2703 Attrs.addAttribute("tune-cpu", TuneCPU);
2704 AddedAttr = true;
2705 }
2706 if (!Features.empty() && SetTargetFeatures) {
2707 llvm::erase_if(Features, [&](const std::string& F) {
2708 return getTarget().isReadOnlyFeature(F.substr(1));
2709 });
2710 llvm::sort(Features);
2711 Attrs.addAttribute("target-features", llvm::join(Features, ","));
2712 AddedAttr = true;
2713 }
2714
2715 return AddedAttr;
2716}
2717
2718void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2719 llvm::GlobalObject *GO) {
2720 const Decl *D = GD.getDecl();
2721 SetCommonAttributes(GD, GO);
2722
2723 if (D) {
2724 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2725 if (D->hasAttr<RetainAttr>())
2726 addUsedGlobal(GV);
2727 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2728 GV->addAttribute("bss-section", SA->getName());
2729 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2730 GV->addAttribute("data-section", SA->getName());
2731 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2732 GV->addAttribute("rodata-section", SA->getName());
2733 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2734 GV->addAttribute("relro-section", SA->getName());
2735 }
2736
2737 if (auto *F = dyn_cast<llvm::Function>(GO)) {
2738 if (D->hasAttr<RetainAttr>())
2739 addUsedGlobal(F);
2740 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2741 if (!D->getAttr<SectionAttr>())
2742 F->setSection(SA->getName());
2743
2744 llvm::AttrBuilder Attrs(F->getContext());
2745 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2746 // We know that GetCPUAndFeaturesAttributes will always have the
2747 // newest set, since it has the newest possible FunctionDecl, so the
2748 // new ones should replace the old.
2749 llvm::AttributeMask RemoveAttrs;
2750 RemoveAttrs.addAttribute("target-cpu");
2751 RemoveAttrs.addAttribute("target-features");
2752 RemoveAttrs.addAttribute("tune-cpu");
2753 F->removeFnAttrs(RemoveAttrs);
2754 F->addFnAttrs(Attrs);
2755 }
2756 }
2757
2758 if (const auto *CSA = D->getAttr<CodeSegAttr>())
2759 GO->setSection(CSA->getName());
2760 else if (const auto *SA = D->getAttr<SectionAttr>())
2761 GO->setSection(SA->getName());
2762 }
2763
2765}
2766
2768 llvm::Function *F,
2769 const CGFunctionInfo &FI) {
2770 const Decl *D = GD.getDecl();
2771 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2773
2774 F->setLinkage(llvm::Function::InternalLinkage);
2775
2776 setNonAliasAttributes(GD, F);
2777}
2778
2779static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2780 // Set linkage and visibility in case we never see a definition.
2782 // Don't set internal linkage on declarations.
2783 // "extern_weak" is overloaded in LLVM; we probably should have
2784 // separate linkage types for this.
2785 if (isExternallyVisible(LV.getLinkage()) &&
2786 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2787 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2788}
2789
2791 llvm::Function *F) {
2792 // Only if we are checking indirect calls.
2793 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2794 return;
2795
2796 // Non-static class methods are handled via vtable or member function pointer
2797 // checks elsewhere.
2798 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2799 return;
2800
2801 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2802 F->addTypeMetadata(0, MD);
2803 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2804
2805 // Emit a hash-based bit set entry for cross-DSO calls.
2806 if (CodeGenOpts.SanitizeCfiCrossDso)
2807 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2808 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2809}
2810
2811void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2812 llvm::LLVMContext &Ctx = F->getContext();
2813 llvm::MDBuilder MDB(Ctx);
2814 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2815 llvm::MDNode::get(
2816 Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2817}
2818
2819static bool allowKCFIIdentifier(StringRef Name) {
2820 // KCFI type identifier constants are only necessary for external assembly
2821 // functions, which means it's safe to skip unusual names. Subset of
2822 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2823 return llvm::all_of(Name, [](const char &C) {
2824 return llvm::isAlnum(C) || C == '_' || C == '.';
2825 });
2826}
2827
2829 llvm::Module &M = getModule();
2830 for (auto &F : M.functions()) {
2831 // Remove KCFI type metadata from non-address-taken local functions.
2832 bool AddressTaken = F.hasAddressTaken();
2833 if (!AddressTaken && F.hasLocalLinkage())
2834 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2835
2836 // Generate a constant with the expected KCFI type identifier for all
2837 // address-taken function declarations to support annotating indirectly
2838 // called assembly functions.
2839 if (!AddressTaken || !F.isDeclaration())
2840 continue;
2841
2842 const llvm::ConstantInt *Type;
2843 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2844 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2845 else
2846 continue;
2847
2848 StringRef Name = F.getName();
2849 if (!allowKCFIIdentifier(Name))
2850 continue;
2851
2852 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2853 Name + ", " + Twine(Type->getZExtValue()) + "\n")
2854 .str();
2855 M.appendModuleInlineAsm(Asm);
2856 }
2857}
2858
2859void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2860 bool IsIncompleteFunction,
2861 bool IsThunk) {
2862
2863 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2864 // If this is an intrinsic function, set the function's attributes
2865 // to the intrinsic's attributes.
2866 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2867 return;
2868 }
2869
2870 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2871
2872 if (!IsIncompleteFunction)
2873 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2874 IsThunk);
2875
2876 // Add the Returned attribute for "this", except for iOS 5 and earlier
2877 // where substantial code, including the libstdc++ dylib, was compiled with
2878 // GCC and does not actually return "this".
2879 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2880 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2881 assert(!F->arg_empty() &&
2882 F->arg_begin()->getType()
2883 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2884 "unexpected this return");
2885 F->addParamAttr(0, llvm::Attribute::Returned);
2886 }
2887
2888 // Only a few attributes are set on declarations; these may later be
2889 // overridden by a definition.
2890
2891 setLinkageForGV(F, FD);
2892 setGVProperties(F, FD);
2893
2894 // Setup target-specific attributes.
2895 if (!IsIncompleteFunction && F->isDeclaration())
2897
2898 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2899 F->setSection(CSA->getName());
2900 else if (const auto *SA = FD->getAttr<SectionAttr>())
2901 F->setSection(SA->getName());
2902
2903 if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2904 if (EA->isError())
2905 F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2906 else if (EA->isWarning())
2907 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2908 }
2909
2910 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2911 if (FD->isInlineBuiltinDeclaration()) {
2912 const FunctionDecl *FDBody;
2913 bool HasBody = FD->hasBody(FDBody);
2914 (void)HasBody;
2915 assert(HasBody && "Inline builtin declarations should always have an "
2916 "available body!");
2917 if (shouldEmitFunction(FDBody))
2918 F->addFnAttr(llvm::Attribute::NoBuiltin);
2919 }
2920
2922 // A replaceable global allocation function does not act like a builtin by
2923 // default, only if it is invoked by a new-expression or delete-expression.
2924 F->addFnAttr(llvm::Attribute::NoBuiltin);
2925 }
2926
2927 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2928 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2929 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2930 if (MD->isVirtual())
2931 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2932
2933 // Don't emit entries for function declarations in the cross-DSO mode. This
2934 // is handled with better precision by the receiving DSO. But if jump tables
2935 // are non-canonical then we need type metadata in order to produce the local
2936 // jump table.
2937 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2938 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2940
2941 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2942 setKCFIType(FD, F);
2943
2944 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2946
2947 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2948 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2949
2950 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2951 // Annotate the callback behavior as metadata:
2952 // - The callback callee (as argument number).
2953 // - The callback payloads (as argument numbers).
2954 llvm::LLVMContext &Ctx = F->getContext();
2955 llvm::MDBuilder MDB(Ctx);
2956
2957 // The payload indices are all but the first one in the encoding. The first
2958 // identifies the callback callee.
2959 int CalleeIdx = *CB->encoding_begin();
2960 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2961 F->addMetadata(llvm::LLVMContext::MD_callback,
2962 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2963 CalleeIdx, PayloadIndices,
2964 /* VarArgsArePassed */ false)}));
2965 }
2966}
2967
2968void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2969 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2970 "Only globals with definition can force usage.");
2971 LLVMUsed.emplace_back(GV);
2972}
2973
2974void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2975 assert(!GV->isDeclaration() &&
2976 "Only globals with definition can force usage.");
2977 LLVMCompilerUsed.emplace_back(GV);
2978}
2979
2981 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2982 "Only globals with definition can force usage.");
2983 if (getTriple().isOSBinFormatELF())
2984 LLVMCompilerUsed.emplace_back(GV);
2985 else
2986 LLVMUsed.emplace_back(GV);
2987}
2988
2989static void emitUsed(CodeGenModule &CGM, StringRef Name,
2990 std::vector<llvm::WeakTrackingVH> &List) {
2991 // Don't create llvm.used if there is no need.
2992 if (List.empty())
2993 return;
2994
2995 // Convert List to what ConstantArray needs.
2997 UsedArray.resize(List.size());
2998 for (unsigned i = 0, e = List.size(); i != e; ++i) {
2999 UsedArray[i] =
3000 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3001 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
3002 }
3003
3004 if (UsedArray.empty())
3005 return;
3006 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
3007
3008 auto *GV = new llvm::GlobalVariable(
3009 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
3010 llvm::ConstantArray::get(ATy, UsedArray), Name);
3011
3012 GV->setSection("llvm.metadata");
3013}
3014
3015void CodeGenModule::emitLLVMUsed() {
3016 emitUsed(*this, "llvm.used", LLVMUsed);
3017 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
3018}
3019
3021 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
3022 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
3023}
3024
3025void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
3028 if (Opt.empty())
3029 return;
3030 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3031 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
3032}
3033
3035 auto &C = getLLVMContext();
3036 if (getTarget().getTriple().isOSBinFormatELF()) {
3037 ELFDependentLibraries.push_back(
3038 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
3039 return;
3040 }
3041
3044 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3045 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
3046}
3047
3048/// Add link options implied by the given module, including modules
3049/// it depends on, using a postorder walk.
3053 // Import this module's parent.
3054 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
3055 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
3056 }
3057
3058 // Import this module's dependencies.
3059 for (Module *Import : llvm::reverse(Mod->Imports)) {
3060 if (Visited.insert(Import).second)
3061 addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
3062 }
3063
3064 // Add linker options to link against the libraries/frameworks
3065 // described by this module.
3066 llvm::LLVMContext &Context = CGM.getLLVMContext();
3067 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
3068
3069 // For modules that use export_as for linking, use that module
3070 // name instead.
3072 return;
3073
3074 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
3075 // Link against a framework. Frameworks are currently Darwin only, so we
3076 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3077 if (LL.IsFramework) {
3078 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3079 llvm::MDString::get(Context, LL.Library)};
3080
3081 Metadata.push_back(llvm::MDNode::get(Context, Args));
3082 continue;
3083 }
3084
3085 // Link against a library.
3086 if (IsELF) {
3087 llvm::Metadata *Args[2] = {
3088 llvm::MDString::get(Context, "lib"),
3089 llvm::MDString::get(Context, LL.Library),
3090 };
3091 Metadata.push_back(llvm::MDNode::get(Context, Args));
3092 } else {
3094 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
3095 auto *OptString = llvm::MDString::get(Context, Opt);
3096 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3097 }
3098 }
3099}
3100
3101void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
3102 assert(Primary->isNamedModuleUnit() &&
3103 "We should only emit module initializers for named modules.");
3104
3105 // Emit the initializers in the order that sub-modules appear in the
3106 // source, first Global Module Fragments, if present.
3107 if (auto GMF = Primary->getGlobalModuleFragment()) {
3108 for (Decl *D : getContext().getModuleInitializers(GMF)) {
3109 if (isa<ImportDecl>(D))
3110 continue;
3111 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3113 }
3114 }
3115 // Second any associated with the module, itself.
3116 for (Decl *D : getContext().getModuleInitializers(Primary)) {
3117 // Skip import decls, the inits for those are called explicitly.
3118 if (isa<ImportDecl>(D))
3119 continue;
3121 }
3122 // Third any associated with the Privat eMOdule Fragment, if present.
3123 if (auto PMF = Primary->getPrivateModuleFragment()) {
3124 for (Decl *D : getContext().getModuleInitializers(PMF)) {
3125 // Skip import decls, the inits for those are called explicitly.
3126 if (isa<ImportDecl>(D))
3127 continue;
3128 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3130 }
3131 }
3132}
3133
3134void CodeGenModule::EmitModuleLinkOptions() {
3135 // Collect the set of all of the modules we want to visit to emit link
3136 // options, which is essentially the imported modules and all of their
3137 // non-explicit child modules.
3138 llvm::SetVector<clang::Module *> LinkModules;
3141
3142 // Seed the stack with imported modules.
3143 for (Module *M : ImportedModules) {
3144 // Do not add any link flags when an implementation TU of a module imports
3145 // a header of that same module.
3146 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
3147 !getLangOpts().isCompilingModule())
3148 continue;
3149 if (Visited.insert(M).second)
3150 Stack.push_back(M);
3151 }
3152
3153 // Find all of the modules to import, making a little effort to prune
3154 // non-leaf modules.
3155 while (!Stack.empty()) {
3156 clang::Module *Mod = Stack.pop_back_val();
3157
3158 bool AnyChildren = false;
3159
3160 // Visit the submodules of this module.
3161 for (const auto &SM : Mod->submodules()) {
3162 // Skip explicit children; they need to be explicitly imported to be
3163 // linked against.
3164 if (SM->IsExplicit)
3165 continue;
3166
3167 if (Visited.insert(SM).second) {
3168 Stack.push_back(SM);
3169 AnyChildren = true;
3170 }
3171 }
3172
3173 // We didn't find any children, so add this module to the list of
3174 // modules to link against.
3175 if (!AnyChildren) {
3176 LinkModules.insert(Mod);
3177 }
3178 }
3179
3180 // Add link options for all of the imported modules in reverse topological
3181 // order. We don't do anything to try to order import link flags with respect
3182 // to linker options inserted by things like #pragma comment().
3184 Visited.clear();
3185 for (Module *M : LinkModules)
3186 if (Visited.insert(M).second)
3187 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
3188 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3189 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3190
3191 // Add the linker options metadata flag.
3192 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
3193 for (auto *MD : LinkerOptionsMetadata)
3194 NMD->addOperand(MD);
3195}
3196
3197void CodeGenModule::EmitDeferred() {
3198 // Emit deferred declare target declarations.
3199 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
3201
3202 // Emit code for any potentially referenced deferred decls. Since a
3203 // previously unused static decl may become used during the generation of code
3204 // for a static function, iterate until no changes are made.
3205
3206 if (!DeferredVTables.empty()) {
3207 EmitDeferredVTables();
3208
3209 // Emitting a vtable doesn't directly cause more vtables to
3210 // become deferred, although it can cause functions to be
3211 // emitted that then need those vtables.
3212 assert(DeferredVTables.empty());
3213 }
3214
3215 // Emit CUDA/HIP static device variables referenced by host code only.
3216 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3217 // needed for further handling.
3218 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3219 llvm::append_range(DeferredDeclsToEmit,
3220 getContext().CUDADeviceVarODRUsedByHost);
3221
3222 // Stop if we're out of both deferred vtables and deferred declarations.
3223 if (DeferredDeclsToEmit.empty())
3224 return;
3225
3226 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3227 // work, it will not interfere with this.
3228 std::vector<GlobalDecl> CurDeclsToEmit;
3229 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3230
3231 for (GlobalDecl &D : CurDeclsToEmit) {
3232 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3233 // to get GlobalValue with exactly the type we need, not something that
3234 // might had been created for another decl with the same mangled name but
3235 // different type.
3236 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3238
3239 // In case of different address spaces, we may still get a cast, even with
3240 // IsForDefinition equal to true. Query mangled names table to get
3241 // GlobalValue.
3242 if (!GV)
3244
3245 // Make sure GetGlobalValue returned non-null.
3246 assert(GV);
3247
3248 // Check to see if we've already emitted this. This is necessary
3249 // for a couple of reasons: first, decls can end up in the
3250 // deferred-decls queue multiple times, and second, decls can end
3251 // up with definitions in unusual ways (e.g. by an extern inline
3252 // function acquiring a strong function redefinition). Just
3253 // ignore these cases.
3254 if (!GV->isDeclaration())
3255 continue;
3256
3257 // If this is OpenMP, check if it is legal to emit this global normally.
3258 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3259 continue;
3260
3261 // Otherwise, emit the definition and move on to the next one.
3262 EmitGlobalDefinition(D, GV);
3263
3264 // If we found out that we need to emit more decls, do that recursively.
3265 // This has the advantage that the decls are emitted in a DFS and related
3266 // ones are close together, which is convenient for testing.
3267 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3268 EmitDeferred();
3269 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3270 }
3271 }
3272}
3273
3274void CodeGenModule::EmitVTablesOpportunistically() {
3275 // Try to emit external vtables as available_externally if they have emitted
3276 // all inlined virtual functions. It runs after EmitDeferred() and therefore
3277 // is not allowed to create new references to things that need to be emitted
3278 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3279
3280 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3281 && "Only emit opportunistic vtables with optimizations");
3282
3283 for (const CXXRecordDecl *RD : OpportunisticVTables) {
3284 assert(getVTables().isVTableExternal(RD) &&
3285 "This queue should only contain external vtables");
3286 if (getCXXABI().canSpeculativelyEmitVTable(RD))
3287 VTables.GenerateClassData(RD);
3288 }
3289 OpportunisticVTables.clear();
3290}
3291
3293 for (const auto& [MangledName, VD] : DeferredAnnotations) {
3294 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3295 if (GV)
3296 AddGlobalAnnotations(VD, GV);
3297 }
3298 DeferredAnnotations.clear();
3299
3300 if (Annotations.empty())
3301 return;
3302
3303 // Create a new global variable for the ConstantStruct in the Module.
3304 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3305 Annotations[0]->getType(), Annotations.size()), Annotations);
3306 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3307 llvm::GlobalValue::AppendingLinkage,
3308 Array, "llvm.global.annotations");
3309 gv->setSection(AnnotationSection);
3310}
3311
3312llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3313 llvm::Constant *&AStr = AnnotationStrings[Str];
3314 if (AStr)
3315 return AStr;
3316
3317 // Not found yet, create a new global.
3318 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3319 auto *gv = new llvm::GlobalVariable(
3320 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3321 ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3322 ConstGlobalsPtrTy->getAddressSpace());
3323 gv->setSection(AnnotationSection);
3324 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3325 AStr = gv;
3326 return gv;
3327}
3328
3331 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3332 if (PLoc.isValid())
3333 return EmitAnnotationString(PLoc.getFilename());
3334 return EmitAnnotationString(SM.getBufferName(Loc));
3335}
3336
3339 PresumedLoc PLoc = SM.getPresumedLoc(L);
3340 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3341 SM.getExpansionLineNumber(L);
3342 return llvm::ConstantInt::get(Int32Ty, LineNo);
3343}
3344
3345llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3346 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3347 if (Exprs.empty())
3348 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3349
3350 llvm::FoldingSetNodeID ID;
3351 for (Expr *E : Exprs) {
3352 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3353 }
3354 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3355 if (Lookup)
3356 return Lookup;
3357
3359 LLVMArgs.reserve(Exprs.size());
3360 ConstantEmitter ConstEmiter(*this);
3361 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3362 const auto *CE = cast<clang::ConstantExpr>(E);
3363 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3364 CE->getType());
3365 });
3366 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3367 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3368 llvm::GlobalValue::PrivateLinkage, Struct,
3369 ".args");
3370 GV->setSection(AnnotationSection);
3371 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3372
3373 Lookup = GV;
3374 return GV;
3375}
3376
3377llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3378 const AnnotateAttr *AA,
3379 SourceLocation L) {
3380 // Get the globals for file name, annotation, and the line number.
3381 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3382 *UnitGV = EmitAnnotationUnit(L),
3383 *LineNoCst = EmitAnnotationLineNo(L),
3384 *Args = EmitAnnotationArgs(AA);
3385
3386 llvm::Constant *GVInGlobalsAS = GV;
3387 if (GV->getAddressSpace() !=
3388 getDataLayout().getDefaultGlobalsAddressSpace()) {
3389 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3390 GV,
3391 llvm::PointerType::get(
3392 GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3393 }
3394
3395 // Create the ConstantStruct for the global annotation.
3396 llvm::Constant *Fields[] = {
3397 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3398 };
3399 return llvm::ConstantStruct::getAnon(Fields);
3400}
3401
3403 llvm::GlobalValue *GV) {
3404 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3405 // Get the struct elements for these annotations.
3406 for (const auto *I : D->specific_attrs<AnnotateAttr>())
3407 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3408}
3409
3411 SourceLocation Loc) const {
3412 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3413 // NoSanitize by function name.
3414 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3415 return true;
3416 // NoSanitize by location. Check "mainfile" prefix.
3417 auto &SM = Context.getSourceManager();
3418 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3419 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3420 return true;
3421
3422 // Check "src" prefix.
3423 if (Loc.isValid())
3424 return NoSanitizeL.containsLocation(Kind, Loc);
3425 // If location is unknown, this may be a compiler-generated function. Assume
3426 // it's located in the main file.
3427 return NoSanitizeL.containsFile(Kind, MainFile.getName());
3428}
3429
3431 llvm::GlobalVariable *GV,
3433 StringRef Category) const {
3434 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3435 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3436 return true;
3437 auto &SM = Context.getSourceManager();
3438 if (NoSanitizeL.containsMainFile(
3439 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
3440 Category))
3441 return true;
3442 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3443 return true;
3444
3445 // Check global type.
3446 if (!Ty.isNull()) {
3447 // Drill down the array types: if global variable of a fixed type is
3448 // not sanitized, we also don't instrument arrays of them.
3449 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3450 Ty = AT->getElementType();
3452 // Only record types (classes, structs etc.) are ignored.
3453 if (Ty->isRecordType()) {
3454 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3455 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3456 return true;
3457 }
3458 }
3459 return false;
3460}
3461
3463 StringRef Category) const {
3464 const auto &XRayFilter = getContext().getXRayFilter();
3465 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3466 auto Attr = ImbueAttr::NONE;
3467 if (Loc.isValid())
3468 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3469 if (Attr == ImbueAttr::NONE)
3470 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3471 switch (Attr) {
3472 case ImbueAttr::NONE:
3473 return false;
3474 case ImbueAttr::ALWAYS:
3475 Fn->addFnAttr("function-instrument", "xray-always");
3476 break;
3477 case ImbueAttr::ALWAYS_ARG1:
3478 Fn->addFnAttr("function-instrument", "xray-always");
3479 Fn->addFnAttr("xray-log-args", "1");
3480 break;
3481 case ImbueAttr::NEVER:
3482 Fn->addFnAttr("function-instrument", "xray-never");
3483 break;
3484 }
3485 return true;
3486}
3487
3490 SourceLocation Loc) const {
3491 const auto &ProfileList = getContext().getProfileList();
3492 // If the profile list is empty, then instrument everything.
3493 if (ProfileList.isEmpty())
3494 return ProfileList::Allow;
3495 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3496 // First, check the function name.
3497 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3498 return *V;
3499 // Next, check the source location.
3500 if (Loc.isValid())
3501 if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3502 return *V;
3503 // If location is unknown, this may be a compiler-generated function. Assume
3504 // it's located in the main file.
3505 auto &SM = Context.getSourceManager();
3506 if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3507 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3508 return *V;
3509 return ProfileList.getDefault(Kind);
3510}
3511
3514 SourceLocation Loc) const {
3516 if (V != ProfileList::Allow)
3517 return V;
3518
3519 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3520 if (NumGroups > 1) {
3521 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3522 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3523 return ProfileList::Skip;
3524 }
3525 return ProfileList::Allow;
3526}
3527
3528bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3529 // Never defer when EmitAllDecls is specified.
3530 if (LangOpts.EmitAllDecls)
3531 return true;
3532
3533 const auto *VD = dyn_cast<VarDecl>(Global);
3534 if (VD &&
3535 ((CodeGenOpts.KeepPersistentStorageVariables &&
3536 (VD->getStorageDuration() == SD_Static ||
3537 VD->getStorageDuration() == SD_Thread)) ||
3538 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3539 VD->getType().isConstQualified())))
3540 return true;
3541
3543}
3544
3545bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3546 // In OpenMP 5.0 variables and function may be marked as
3547 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3548 // that they must be emitted on the host/device. To be sure we need to have
3549 // seen a declare target with an explicit mentioning of the function, we know
3550 // we have if the level of the declare target attribute is -1. Note that we
3551 // check somewhere else if we should emit this at all.
3552 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3553 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3554 OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3555 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3556 return false;
3557 }
3558
3559 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3561 // Implicit template instantiations may change linkage if they are later
3562 // explicitly instantiated, so they should not be emitted eagerly.
3563 return false;
3564 // Defer until all versions have been semantically checked.
3565 if (FD->hasAttr<TargetVersionAttr>() && !FD->isMultiVersion())
3566 return false;
3567 }
3568 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3569 if (Context.getInlineVariableDefinitionKind(VD) ==
3571 // A definition of an inline constexpr static data member may change
3572 // linkage later if it's redeclared outside the class.
3573 return false;
3574 if (CXX20ModuleInits && VD->getOwningModule() &&
3575 !VD->getOwningModule()->isModuleMapModule()) {
3576 // For CXX20, module-owned initializers need to be deferred, since it is
3577 // not known at this point if they will be run for the current module or
3578 // as part of the initializer for an imported one.
3579 return false;
3580 }
3581 }
3582 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3583 // codegen for global variables, because they may be marked as threadprivate.
3584 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3585 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3586 !Global->getType().isConstantStorage(getContext(), false, false) &&
3587 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3588 return false;
3589
3590 return true;
3591}
3592
3594 StringRef Name = getMangledName(GD);
3595
3596 // The UUID descriptor should be pointer aligned.
3598
3599 // Look for an existing global.
3600 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3601 return ConstantAddress(GV, GV->getValueType(), Alignment);
3602
3603 ConstantEmitter Emitter(*this);
3604 llvm::Constant *Init;
3605
3606 APValue &V = GD->getAsAPValue();
3607 if (!V.isAbsent()) {
3608 // If possible, emit the APValue version of the initializer. In particular,
3609 // this gets the type of the constant right.
3610 Init = Emitter.emitForInitializer(
3611 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3612 } else {
3613 // As a fallback, directly construct the constant.
3614 // FIXME: This may get padding wrong under esoteric struct layout rules.
3615 // MSVC appears to create a complete type 'struct __s_GUID' that it
3616 // presumably uses to represent these constants.
3617 MSGuidDecl::Parts Parts = GD->getParts();
3618 llvm::Constant *Fields[4] = {
3619 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3620 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3621 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3622 llvm::ConstantDataArray::getRaw(
3623 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3624 Int8Ty)};
3625 Init = llvm::ConstantStruct::getAnon(Fields);
3626 }
3627
3628 auto *GV = new llvm::GlobalVariable(
3629 getModule(), Init->getType(),
3630 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3631 if (supportsCOMDAT())
3632 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3633 setDSOLocal(GV);
3634
3635 if (!V.isAbsent()) {
3636 Emitter.finalize(GV);
3637 return ConstantAddress(GV, GV->getValueType(), Alignment);
3638 }
3639
3640 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3641 return ConstantAddress(GV, Ty, Alignment);
3642}
3643
3645 const UnnamedGlobalConstantDecl *GCD) {
3646 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3647
3648 llvm::GlobalVariable **Entry = nullptr;
3649 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3650 if (*Entry)
3651 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3652
3653 ConstantEmitter Emitter(*this);
3654 llvm::Constant *Init;
3655
3656 const APValue &V = GCD->getValue();
3657
3658 assert(!V.isAbsent());
3659 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3660 GCD->getType());
3661
3662 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3663 /*isConstant=*/true,
3664 llvm::GlobalValue::PrivateLinkage, Init,
3665 ".constant");
3666 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3667 GV->setAlignment(Alignment.getAsAlign());
3668
3669 Emitter.finalize(GV);
3670
3671 *Entry = GV;
3672 return ConstantAddress(GV, GV->getValueType(), Alignment);
3673}
3674
3676 const TemplateParamObjectDecl *TPO) {
3677 StringRef Name = getMangledName(TPO);
3678 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3679
3680 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3681 return ConstantAddress(GV, GV->getValueType(), Alignment);
3682
3683 ConstantEmitter Emitter(*this);
3684 llvm::Constant *Init = Emitter.emitForInitializer(
3685 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3686
3687 if (!Init) {
3688 ErrorUnsupported(TPO, "template parameter object");
3689 return ConstantAddress::invalid();
3690 }
3691
3692 llvm::GlobalValue::LinkageTypes Linkage =
3694 ? llvm::GlobalValue::LinkOnceODRLinkage
3695 : llvm::GlobalValue::InternalLinkage;
3696 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3697 /*isConstant=*/true, Linkage, Init, Name);
3698 setGVProperties(GV, TPO);
3699 if (supportsCOMDAT())
3700 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3701 Emitter.finalize(GV);
3702
3703 return ConstantAddress(GV, GV->getValueType(), Alignment);
3704}
3705
3707 const AliasAttr *AA = VD->getAttr<AliasAttr>();
3708 assert(AA && "No alias?");
3709
3710 CharUnits Alignment = getContext().getDeclAlign(VD);
3711 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3712
3713 // See if there is already something with the target's name in the module.
3714 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3715 if (Entry)
3716 return ConstantAddress(Entry, DeclTy, Alignment);
3717
3718 llvm::Constant *Aliasee;
3719 if (isa<llvm::FunctionType>(DeclTy))
3720 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3721 GlobalDecl(cast<FunctionDecl>(VD)),
3722 /*ForVTable=*/false);
3723 else
3724 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3725 nullptr);
3726
3727 auto *F = cast<llvm::GlobalValue>(Aliasee);
3728 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3729 WeakRefReferences.insert(F);
3730
3731 return ConstantAddress(Aliasee, DeclTy, Alignment);
3732}
3733
3734template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
3735 if (!D)
3736 return false;
3737 if (auto *A = D->getAttr<AttrT>())
3738 return A->isImplicit();
3739 return D->isImplicit();
3740}
3741
3742bool CodeGenModule::shouldEmitCUDAGlobalVar(const VarDecl *Global) const {
3743 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
3744 // We need to emit host-side 'shadows' for all global
3745 // device-side variables because the CUDA runtime needs their
3746 // size and host-side address in order to provide access to
3747 // their device-side incarnations.
3748 return !LangOpts.CUDAIsDevice || Global->hasAttr<CUDADeviceAttr>() ||
3749 Global->hasAttr<CUDAConstantAttr>() ||
3750 Global->hasAttr<CUDASharedAttr>() ||
3751 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
3752 Global->getType()->isCUDADeviceBuiltinTextureType();
3753}
3754
3756 const auto *Global = cast<ValueDecl>(GD.getDecl());
3757
3758 // Weak references don't produce any output by themselves.
3759 if (Global->hasAttr<WeakRefAttr>())
3760 return;
3761
3762 // If this is an alias definition (which otherwise looks like a declaration)
3763 // emit it now.
3764 if (Global->hasAttr<AliasAttr>())
3765 return EmitAliasDefinition(GD);
3766
3767 // IFunc like an alias whose value is resolved at runtime by calling resolver.
3768 if (Global->hasAttr<IFuncAttr>())
3769 return emitIFuncDefinition(GD);
3770
3771 // If this is a cpu_dispatch multiversion function, emit the resolver.
3772 if (Global->hasAttr<CPUDispatchAttr>())
3773 return emitCPUDispatchDefinition(GD);
3774
3775 // If this is CUDA, be selective about which declarations we emit.
3776 // Non-constexpr non-lambda implicit host device functions are not emitted
3777 // unless they are used on device side.
3778 if (LangOpts.CUDA) {
3779 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3780 "Expected Variable or Function");
3781 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3782 if (!shouldEmitCUDAGlobalVar(VD))
3783 return;
3784 } else if (LangOpts.CUDAIsDevice) {
3785 const auto *FD = dyn_cast<FunctionDecl>(Global);
3786 if ((!Global->hasAttr<CUDADeviceAttr>() ||
3787 (LangOpts.OffloadImplicitHostDeviceTemplates &&
3788 hasImplicitAttr<CUDAHostAttr>(FD) &&
3789 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
3790 !isLambdaCallOperator(FD) &&
3791 !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3792 !Global->hasAttr<CUDAGlobalAttr>() &&
3793 !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
3794 !Global->hasAttr<CUDAHostAttr>()))
3795 return;
3796 // Device-only functions are the only things we skip.
3797 } else if (!Global->hasAttr<CUDAHostAttr>() &&
3798 Global->hasAttr<CUDADeviceAttr>())
3799 return;
3800 }
3801
3802 if (LangOpts.OpenMP) {
3803 // If this is OpenMP, check if it is legal to emit this global normally.
3804 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3805 return;
3806 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3807 if (MustBeEmitted(Global))
3809 return;
3810 }
3811 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3812 if (MustBeEmitted(Global))
3814 return;
3815 }
3816 }
3817
3818 // Ignore declarations, they will be emitted on their first use.
3819 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3820 // Update deferred annotations with the latest declaration if the function
3821 // function was already used or defined.
3822 if (FD->hasAttr<AnnotateAttr>()) {
3823 StringRef MangledName = getMangledName(GD);
3824 if (GetGlobalValue(MangledName))
3825 DeferredAnnotations[MangledName] = FD;
3826 }
3827
3828 // Forward declarations are emitted lazily on first use.
3829 if (!FD->doesThisDeclarationHaveABody()) {
3831 (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64()))
3832 return;
3833
3834 StringRef MangledName = getMangledName(GD);
3835
3836 // Compute the function info and LLVM type.
3838 llvm::Type *Ty = getTypes().GetFunctionType(FI);
3839
3840 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3841 /*DontDefer=*/false);
3842 return;
3843 }
3844 } else {
3845 const auto *VD = cast<VarDecl>(Global);
3846 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3847 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3849 if (LangOpts.OpenMP) {
3850 // Emit declaration of the must-be-emitted declare target variable.
3851 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3852 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3853
3854 // If this variable has external storage and doesn't require special
3855 // link handling we defer to its canonical definition.
3856 if (VD->hasExternalStorage() &&
3857 Res != OMPDeclareTargetDeclAttr::MT_Link)
3858 return;
3859
3860 bool UnifiedMemoryEnabled =
3862 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3863 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3864 !UnifiedMemoryEnabled) {
3865 (void)GetAddrOfGlobalVar(VD);
3866 } else {
3867 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3868 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3869 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3870 UnifiedMemoryEnabled)) &&
3871 "Link clause or to clause with unified memory expected.");
3873 }
3874
3875 return;
3876 }
3877 }
3878 // If this declaration may have caused an inline variable definition to
3879 // change linkage, make sure that it's emitted.
3880 if (Context.getInlineVariableDefinitionKind(VD) ==
3883 return;
3884 }
3885 }
3886
3887 // Defer code generation to first use when possible, e.g. if this is an inline
3888 // function. If the global must always be emitted, do it eagerly if possible
3889 // to benefit from cache locality.
3890 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3891 // Emit the definition if it can't be deferred.
3892 EmitGlobalDefinition(GD);
3893 addEmittedDeferredDecl(GD);
3894 return;
3895 }
3896
3897 // If we're deferring emission of a C++ variable with an
3898 // initializer, remember the order in which it appeared in the file.
3899 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3900 cast<VarDecl>(Global)->hasInit()) {
3901 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3902 CXXGlobalInits.push_back(nullptr);
3903 }
3904
3905 StringRef MangledName = getMangledName(GD);
3906 if (GetGlobalValue(MangledName) != nullptr) {
3907 // The value has already been used and should therefore be emitted.
3908 addDeferredDeclToEmit(GD);
3909 } else if (MustBeEmitted(Global)) {
3910 // The value must be emitted, but cannot be emitted eagerly.
3911 assert(!MayBeEmittedEagerly(Global));
3912 addDeferredDeclToEmit(GD);
3913 } else {
3914 // Otherwise, remember that we saw a deferred decl with this name. The
3915 // first use of the mangled name will cause it to move into
3916 // DeferredDeclsToEmit.
3917 DeferredDecls[MangledName] = GD;
3918 }
3919}
3920
3921// Check if T is a class type with a destructor that's not dllimport.
3923 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3924 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3925 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3926 return true;
3927
3928 return false;
3929}
3930
3931namespace {
3932 struct FunctionIsDirectlyRecursive
3933 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3934 const StringRef Name;
3935 const Builtin::Context &BI;
3936 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3937 : Name(N), BI(C) {}
3938
3939 bool VisitCallExpr(const CallExpr *E) {
3940 const FunctionDecl *FD = E->getDirectCallee();
3941 if (!FD)
3942 return false;
3943 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3944 if (Attr && Name == Attr->getLabel())
3945 return true;
3946 unsigned BuiltinID = FD->getBuiltinID();
3947 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3948 return false;
3949 StringRef BuiltinName = BI.getName(BuiltinID);
3950 if (BuiltinName.starts_with("__builtin_") &&
3951 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3952 return true;
3953 }
3954 return false;
3955 }
3956
3957 bool VisitStmt(const Stmt *S) {
3958 for (const Stmt *Child : S->children())
3959 if (Child && this->Visit(Child))
3960 return true;
3961 return false;
3962 }
3963 };
3964
3965 // Make sure we're not referencing non-imported vars or functions.
3966 struct DLLImportFunctionVisitor
3967 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3968 bool SafeToInline = true;
3969
3970 bool shouldVisitImplicitCode() const { return true; }
3971
3972 bool VisitVarDecl(VarDecl *VD) {
3973 if (VD->getTLSKind()) {
3974 // A thread-local variable cannot be imported.
3975 SafeToInline = false;
3976 return SafeToInline;
3977 }
3978
3979 // A variable definition might imply a destructor call.
3981 SafeToInline = !HasNonDllImportDtor(VD->getType());
3982
3983 return SafeToInline;
3984 }
3985
3986 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3987 if (const auto *D = E->getTemporary()->getDestructor())
3988 SafeToInline = D->hasAttr<DLLImportAttr>();
3989 return SafeToInline;
3990 }
3991
3992 bool VisitDeclRefExpr(DeclRefExpr *E) {
3993 ValueDecl *VD = E->getDecl();
3994 if (isa<FunctionDecl>(VD))
3995 SafeToInline = VD->hasAttr<DLLImportAttr>();
3996 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3997 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3998 return SafeToInline;
3999 }
4000
4001 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4002 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
4003 return SafeToInline;
4004 }
4005
4006 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4007 CXXMethodDecl *M = E->getMethodDecl();
4008 if (!M) {
4009 // Call through a pointer to member function. This is safe to inline.
4010 SafeToInline = true;
4011 } else {
4012 SafeToInline = M->hasAttr<DLLImportAttr>();
4013 }
4014 return SafeToInline;
4015 }
4016
4017 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4018 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4019 return SafeToInline;
4020 }
4021
4022 bool VisitCXXNewExpr(CXXNewExpr *E) {
4023 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
4024 return SafeToInline;
4025 }
4026 };
4027}
4028
4029// isTriviallyRecursive - Check if this function calls another
4030// decl that, because of the asm attribute or the other decl being a builtin,
4031// ends up pointing to itself.
4032bool
4033CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
4034 StringRef Name;
4035 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4036 // asm labels are a special kind of mangling we have to support.
4037 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
4038 if (!Attr)
4039 return false;
4040 Name = Attr->getLabel();
4041 } else {
4042 Name = FD->getName();
4043 }
4044
4045 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4046 const Stmt *Body = FD->getBody();
4047 return Body ? Walker.Visit(Body) : false;
4048}
4049
4050bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4051 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
4052 return true;
4053
4054 const auto *F = cast<FunctionDecl>(GD.getDecl());
4055 // Inline builtins declaration must be emitted. They often are fortified
4056 // functions.
4057 if (F->isInlineBuiltinDeclaration())
4058 return true;
4059
4060 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4061 return false;
4062
4063 // We don't import function bodies from other named module units since that
4064 // behavior may break ABI compatibility of the current unit.
4065 if (const Module *M = F->getOwningModule();
4066 M && M->getTopLevelModule()->isNamedModule() &&
4067 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4068 // There are practices to mark template member function as always-inline
4069 // and mark the template as extern explicit instantiation but not give
4070 // the definition for member function. So we have to emit the function
4071 // from explicitly instantiation with always-inline.
4072 //
4073 // See https://github.com/llvm/llvm-project/issues/86893 for details.
4074 //
4075 // TODO: Maybe it is better to give it a warning if we call a non-inline
4076 // function from other module units which is marked as always-inline.
4077 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4078 return false;
4079 }
4080 }
4081
4082 if (F->hasAttr<NoInlineAttr>())
4083 return false;
4084
4085 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4086 // Check whether it would be safe to inline this dllimport function.
4087 DLLImportFunctionVisitor Visitor;
4088 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
4089 if (!Visitor.SafeToInline)
4090 return false;
4091
4092 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4093 // Implicit destructor invocations aren't captured in the AST, so the
4094 // check above can't see them. Check for them manually here.
4095 for (const Decl *Member : Dtor->getParent()->decls())
4096 if (isa<FieldDecl>(Member))
4097 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
4098 return false;
4099 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4100 if (HasNonDllImportDtor(B.getType()))
4101 return false;
4102 }
4103 }
4104
4105 // PR9614. Avoid cases where the source code is lying to us. An available
4106 // externally function should have an equivalent function somewhere else,
4107 // but a function that calls itself through asm label/`__builtin_` trickery is
4108 // clearly not equivalent to the real implementation.
4109 // This happens in glibc's btowc and in some configure checks.
4110 return !isTriviallyRecursive(F);
4111}
4112
4113bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4114 return CodeGenOpts.OptimizationLevel > 0;
4115}
4116
4117void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4118 llvm::GlobalValue *GV) {
4119 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4120
4121 if (FD->isCPUSpecificMultiVersion()) {
4122 auto *Spec = FD->getAttr<CPUSpecificAttr>();
4123 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
4124 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4125 } else if (auto *TC = FD->getAttr<TargetClonesAttr>()) {
4126 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4127 // AArch64 favors the default target version over the clone if any.
4128 if ((!TC->isDefaultVersion(I) || !getTarget().getTriple().isAArch64()) &&
4129 TC->isFirstOfVersion(I))
4130 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4131 // Ensure that the resolver function is also emitted.
4132 GetOrCreateMultiVersionResolver(GD);
4133 } else
4134 EmitGlobalFunctionDefinition(GD, GV);
4135
4136 // Defer the resolver emission until we can reason whether the TU
4137 // contains a default target version implementation.
4139 AddDeferredMultiVersionResolverToEmit(GD);
4140}
4141
4142void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4143 const auto *D = cast<ValueDecl>(GD.getDecl());
4144
4145 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
4146 Context.getSourceManager(),
4147 "Generating code for declaration");
4148
4149 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4150 // At -O0, don't generate IR for functions with available_externally
4151 // linkage.
4152 if (!shouldEmitFunction(GD))
4153 return;
4154
4155 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
4156 std::string Name;
4157 llvm::raw_string_ostream OS(Name);
4158 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
4159 /*Qualified=*/true);
4160 return Name;
4161 });
4162
4163 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
4164 // Make sure to emit the definition(s) before we emit the thunks.
4165 // This is necessary for the generation of certain thunks.
4166 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4167 ABI->emitCXXStructor(GD);
4168 else if (FD->isMultiVersion())
4169 EmitMultiVersionFunctionDefinition(GD, GV);
4170 else
4171 EmitGlobalFunctionDefinition(GD, GV);
4172
4173 if (Method->isVirtual())
4174 getVTables().EmitThunks(GD);
4175
4176 return;
4177 }
4178
4179 if (FD->isMultiVersion())
4180 return EmitMultiVersionFunctionDefinition(GD, GV);
4181 return EmitGlobalFunctionDefinition(GD, GV);
4182 }
4183
4184 if (const auto *VD = dyn_cast<VarDecl>(D))
4185 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4186
4187 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
4188}
4189
4190static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4191 llvm::Function *NewFn);
4192
4193static unsigned
4195 const CodeGenFunction::MultiVersionResolverOption &RO) {
4196 unsigned Priority = 0;
4197 unsigned NumFeatures = 0;
4198 for (StringRef Feat : RO.Conditions.Features) {
4199 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
4200 NumFeatures++;
4201 }
4202
4203 if (!RO.Conditions.Architecture.empty())
4204 Priority = std::max(
4205 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
4206
4207 Priority += TI.multiVersionFeatureCost() * NumFeatures;
4208
4209 return Priority;
4210}
4211
4212// Multiversion functions should be at most 'WeakODRLinkage' so that a different
4213// TU can forward declare the function without causing problems. Particularly
4214// in the cases of CPUDispatch, this causes issues. This also makes sure we
4215// work with internal linkage functions, so that the same function name can be
4216// used with internal linkage in multiple TUs.
4217llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
4218 GlobalDecl GD) {
4219 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4221 return llvm::GlobalValue::InternalLinkage;
4222 return llvm::GlobalValue::WeakODRLinkage;
4223}
4224
4225void CodeGenModule::emitMultiVersionFunctions() {
4226 std::vector<GlobalDecl> MVFuncsToEmit;
4227 MultiVersionFuncs.swap(MVFuncsToEmit);
4228 for (GlobalDecl GD : MVFuncsToEmit) {
4229 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4230 assert(FD && "Expected a FunctionDecl");
4231
4232 auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) {
4233 GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, MVIdx};
4234 StringRef MangledName = getMangledName(CurGD);
4235 llvm::Constant *Func = GetGlobalValue(MangledName);
4236 if (!Func) {
4237 if (Decl->isDefined()) {
4238 EmitGlobalFunctionDefinition(CurGD, nullptr);
4239 Func = GetGlobalValue(MangledName);
4240 } else {
4242 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4243 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4244 /*DontDefer=*/false, ForDefinition);
4245 }
4246 assert(Func && "This should have just been created");
4247 }
4248 return cast<llvm::Function>(Func);
4249 };
4250
4251 // For AArch64, a resolver is only emitted if a function marked with
4252 // target_version("default")) or target_clones() is present and defined
4253 // in this TU. For other architectures it is always emitted.
4254 bool ShouldEmitResolver = !getTarget().getTriple().isAArch64();
4256
4258 FD, [&](const FunctionDecl *CurFD) {
4260 bool IsDefined = CurFD->doesThisDeclarationHaveABody();
4261
4262 if (const auto *TA = CurFD->getAttr<TargetAttr>()) {
4263 TA->getAddedFeatures(Feats);
4264 llvm::Function *Func = createFunction(CurFD);
4265 Options.emplace_back(Func, TA->getArchitecture(), Feats);
4266 } else if (const auto *TVA = CurFD->getAttr<TargetVersionAttr>()) {
4267 if (TVA->isDefaultVersion() && IsDefined)
4268 ShouldEmitResolver = true;
4269 TVA->getFeatures(Feats);
4270 llvm::Function *Func = createFunction(CurFD);
4271 Options.emplace_back(Func, /*Architecture*/ "", Feats);
4272 } else if (const auto *TC = CurFD->getAttr<TargetClonesAttr>()) {
4273 if (IsDefined)
4274 ShouldEmitResolver = true;
4275 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4276 if (!TC->isFirstOfVersion(I))
4277 continue;
4278
4279 llvm::Function *Func = createFunction(CurFD, I);
4280 StringRef Architecture;
4281 Feats.clear();
4282 if (getTarget().getTriple().isAArch64())
4283 TC->getFeatures(Feats, I);
4284 else {
4285 StringRef Version = TC->getFeatureStr(I);
4286 if (Version.starts_with("arch="))
4287 Architecture = Version.drop_front(sizeof("arch=") - 1);
4288 else if (Version != "default")
4289 Feats.push_back(Version);
4290 }
4291 Options.emplace_back(Func, Architecture, Feats);
4292 }
4293 } else
4294 llvm_unreachable("unexpected MultiVersionKind");
4295 });
4296
4297 if (!ShouldEmitResolver)
4298 continue;
4299
4300 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4301 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4302 ResolverConstant = IFunc->getResolver();
4303 if (FD->isTargetClonesMultiVersion() &&
4304 !getTarget().getTriple().isAArch64()) {
4305 std::string MangledName = getMangledNameImpl(
4306 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4307 if (!GetGlobalValue(MangledName + ".ifunc")) {
4309 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4310 // In prior versions of Clang, the mangling for ifuncs incorrectly
4311 // included an .ifunc suffix. This alias is generated for backward
4312 // compatibility. It is deprecated, and may be removed in the future.
4313 auto *Alias = llvm::GlobalAlias::create(
4314 DeclTy, 0, getMultiversionLinkage(*this, GD),
4315 MangledName + ".ifunc", IFunc, &getModule());
4316 SetCommonAttributes(FD, Alias);
4317 }
4318 }
4319 }
4320 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4321
4322 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4323
4324 if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
4325 ResolverFunc->setComdat(
4326 getModule().getOrInsertComdat(ResolverFunc->getName()));
4327
4328 const TargetInfo &TI = getTarget();
4329 llvm::stable_sort(
4330 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
4331 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4332 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
4333 });
4334 CodeGenFunction CGF(*this);
4335 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4336 }
4337
4338 // Ensure that any additions to the deferred decls list caused by emitting a
4339 // variant are emitted. This can happen when the variant itself is inline and
4340 // calls a function without linkage.
4341 if (!MVFuncsToEmit.empty())
4342 EmitDeferred();
4343
4344 // Ensure that any additions to the multiversion funcs list from either the
4345 // deferred decls or the multiversion functions themselves are emitted.
4346 if (!MultiVersionFuncs.empty())
4347 emitMultiVersionFunctions();
4348}
4349
4350static void replaceDeclarationWith(llvm::GlobalValue *Old,
4351 llvm::Constant *New) {
4352 assert(cast<llvm::Function>(Old)->isDeclaration() && "Not a declaration");
4353 New->takeName(Old);
4354 Old->replaceAllUsesWith(New);
4355 Old->eraseFromParent();
4356}
4357
4358void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4359 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4360 assert(FD && "Not a FunctionDecl?");
4361 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4362 const auto *DD = FD->getAttr<CPUDispatchAttr>();
4363 assert(DD && "Not a cpu_dispatch Function?");
4364
4366 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4367
4368 StringRef ResolverName = getMangledName(GD);
4369 UpdateMultiVersionNames(GD, FD, ResolverName);
4370
4371 llvm::Type *ResolverType;
4372 GlobalDecl ResolverGD;
4373 if (getTarget().supportsIFunc()) {
4374 ResolverType = llvm::FunctionType::get(
4375 llvm::PointerType::get(DeclTy,
4376 getTypes().getTargetAddressSpace(FD->getType())),
4377 false);
4378 }
4379 else {
4380 ResolverType = DeclTy;
4381 ResolverGD = GD;
4382 }
4383
4384 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4385 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4386 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4387 if (supportsCOMDAT())
4388 ResolverFunc->setComdat(
4389 getModule().getOrInsertComdat(ResolverFunc->getName()));
4390
4392 const TargetInfo &Target = getTarget();
4393 unsigned Index = 0;
4394 for (const IdentifierInfo *II : DD->cpus()) {
4395 // Get the name of the target function so we can look it up/create it.
4396 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4397 getCPUSpecificMangling(*this, II->getName());
4398
4399 llvm::Constant *Func = GetGlobalValue(MangledName);
4400
4401 if (!Func) {
4402 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4403 if (ExistingDecl.getDecl() &&
4404 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4405 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4406 Func = GetGlobalValue(MangledName);
4407 } else {
4408 if (!ExistingDecl.getDecl())
4409 ExistingDecl = GD.getWithMultiVersionIndex(Index);
4410
4411 Func = GetOrCreateLLVMFunction(
4412 MangledName, DeclTy, ExistingDecl,
4413 /*ForVTable=*/false, /*DontDefer=*/true,
4414 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4415 }
4416 }
4417
4419 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4420 llvm::transform(Features, Features.begin(),
4421 [](StringRef Str) { return Str.substr(1); });
4422 llvm::erase_if(Features, [&Target](StringRef Feat) {
4423 return !Target.validateCpuSupports(Feat);
4424 });
4425 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
4426 ++Index;
4427 }
4428
4429 llvm::stable_sort(
4430 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
4431 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4432 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4433 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4434 });
4435
4436 // If the list contains multiple 'default' versions, such as when it contains
4437 // 'pentium' and 'generic', don't emit the call to the generic one (since we
4438 // always run on at least a 'pentium'). We do this by deleting the 'least
4439 // advanced' (read, lowest mangling letter).
4440 while (Options.size() > 1 &&
4441 llvm::all_of(llvm::X86::getCpuSupportsMask(
4442 (Options.end() - 2)->Conditions.Features),
4443 [](auto X) { return X == 0; })) {
4444 StringRef LHSName = (Options.end() - 2)->Function->getName();
4445 StringRef RHSName = (Options.end() - 1)->Function->getName();
4446 if (LHSName.compare(RHSName) < 0)
4447 Options.erase(Options.end() - 2);
4448 else
4449 Options.erase(Options.end() - 1);
4450 }
4451
4452 CodeGenFunction CGF(*this);
4453 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4454
4455 if (getTarget().supportsIFunc()) {
4456 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
4457 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4458
4459 // Fix up function declarations that were created for cpu_specific before
4460 // cpu_dispatch was known
4461 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4462 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
4463 &getModule());
4464 replaceDeclarationWith(IFunc, GI);
4465 IFunc = GI;
4466 }
4467
4468 std::string AliasName = getMangledNameImpl(
4469 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4470 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4471 if (!AliasFunc) {
4472 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
4473 &getModule());
4474 SetCommonAttributes(GD, GA);
4475 }
4476 }
4477}
4478
4479/// Adds a declaration to the list of multi version functions if not present.
4480void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4481 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4482 assert(FD && "Not a FunctionDecl?");
4483
4485 std::string MangledName =
4486 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4487 if (!DeferredResolversToEmit.insert(MangledName).second)
4488 return;
4489 }
4490 MultiVersionFuncs.push_back(GD);
4491}
4492
4493/// If a dispatcher for the specified mangled name is not in the module, create
4494/// and return it. The dispatcher is either an llvm Function with the specified
4495/// type, or a global ifunc.
4496llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4497 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4498 assert(FD && "Not a FunctionDecl?");
4499
4500 std::string MangledName =
4501 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4502
4503 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4504 // a separate resolver).
4505 std::string ResolverName = MangledName;
4506 if (getTarget().supportsIFunc()) {
4507 switch (FD->getMultiVersionKind()) {
4509 llvm_unreachable("unexpected MultiVersionKind::None for resolver");
4513 ResolverName += ".ifunc";
4514 break;
4517 break;
4518 }
4519 } else if (FD->isTargetMultiVersion()) {
4520 ResolverName += ".resolver";
4521 }
4522
4523 // If the resolver has already been created, just return it. This lookup may
4524 // yield a function declaration instead of a resolver on AArch64. That is
4525 // because we didn't know whether a resolver will be generated when we first
4526 // encountered a use of the symbol named after this resolver. Therefore,
4527 // targets which support ifuncs should not return here unless we actually
4528 // found an ifunc.
4529 llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName);
4530 if (ResolverGV &&
4531 (isa<llvm::GlobalIFunc>(ResolverGV) || !getTarget().supportsIFunc()))
4532 return ResolverGV;
4533
4535 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4536
4537 // The resolver needs to be created. For target and target_clones, defer
4538 // creation until the end of the TU.
4540 AddDeferredMultiVersionResolverToEmit(GD);
4541
4542 // For cpu_specific, don't create an ifunc yet because we don't know if the
4543 // cpu_dispatch will be emitted in this translation unit.
4544 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
4545 llvm::Type *ResolverType = llvm::FunctionType::get(
4546 llvm::PointerType::get(DeclTy,
4547 getTypes().getTargetAddressSpace(FD->getType())),
4548 false);
4549 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4550 MangledName + ".resolver", ResolverType, GlobalDecl{},
4551 /*ForVTable=*/false);
4552 llvm::GlobalIFunc *GIF =
4553 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
4554 "", Resolver, &getModule());
4555 GIF->setName(ResolverName);
4556 SetCommonAttributes(FD, GIF);
4557 if (ResolverGV)
4558 replaceDeclarationWith(ResolverGV, GIF);
4559 return GIF;
4560 }
4561
4562 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4563 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
4564 assert(isa<llvm::GlobalValue>(Resolver) &&
4565 "Resolver should be created for the first time");
4566 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
4567 if (ResolverGV)
4568 replaceDeclarationWith(ResolverGV, Resolver);
4569 return Resolver;
4570}
4571
4572bool CodeGenModule::shouldDropDLLAttribute(const Decl *D,
4573 const llvm::GlobalValue *GV) const {
4574 auto SC = GV->getDLLStorageClass();
4575 if (SC == llvm::GlobalValue::DefaultStorageClass)
4576 return false;
4577 const Decl *MRD = D->getMostRecentDecl();
4578 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4579 !MRD->hasAttr<DLLImportAttr>()) ||
4580 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4581 !MRD->hasAttr<DLLExportAttr>())) &&
4582 !shouldMapVisibilityToDLLExport(cast<NamedDecl>(MRD)));
4583}
4584
4585/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
4586/// module, create and return an llvm Function with the specified type. If there
4587/// is something in the module with the specified name, return it potentially
4588/// bitcasted to the right type.
4589///
4590/// If D is non-null, it specifies a decl that correspond to this. This is used
4591/// to set the attributes on the function when it is first created.
4592llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4593 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
4594 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
4595 ForDefinition_t IsForDefinition) {
4596 const Decl *D = GD.getDecl();
4597
4598 std::string NameWithoutMultiVersionMangling;
4599 // Any attempts to use a MultiVersion function should result in retrieving
4600 // the iFunc instead. Name Mangling will handle the rest of the changes.
4601 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4602 // For the device mark the function as one that should be emitted.
4603 if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4604 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
4605 !DontDefer && !IsForDefinition) {
4606 if (const FunctionDecl *FDDef = FD->getDefinition()) {
4607 GlobalDecl GDDef;
4608 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4609 GDDef = GlobalDecl(CD, GD.getCtorType());
4610 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4611 GDDef = GlobalDecl(DD, GD.getDtorType());
4612 else
4613 GDDef = GlobalDecl(FDDef);
4614 EmitGlobal(GDDef);
4615 }
4616 }
4617
4618 if (FD->isMultiVersion()) {
4619 UpdateMultiVersionNames(GD, FD, MangledName);
4620 if (!IsForDefinition) {
4621 // On AArch64 we do not immediatelly emit an ifunc resolver when a
4622 // function is used. Instead we defer the emission until we see a
4623 // default definition. In the meantime we just reference the symbol
4624 // without FMV mangling (it may or may not be replaced later).
4625 if (getTarget().getTriple().isAArch64()) {
4626 AddDeferredMultiVersionResolverToEmit(GD);
4627 NameWithoutMultiVersionMangling = getMangledNameImpl(
4628 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4629 } else
4630 return GetOrCreateMultiVersionResolver(GD);
4631 }
4632 }
4633 }
4634
4635 if (!NameWithoutMultiVersionMangling.empty())
4636 MangledName = NameWithoutMultiVersionMangling;
4637
4638 // Lookup the entry, lazily creating it if necessary.
4639 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4640 if (Entry) {
4641 if (WeakRefReferences.erase(Entry)) {
4642 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4643 if (FD && !FD->hasAttr<WeakAttr>())
4644 Entry->setLinkage(llvm::Function::ExternalLinkage);
4645 }
4646
4647 // Handle dropped DLL attributes.
4648 if (D && shouldDropDLLAttribute(D, Entry)) {
4649 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4650 setDSOLocal(Entry);
4651 }
4652
4653 // If there are two attempts to define the same mangled name, issue an
4654 // error.
4655 if (IsForDefinition && !Entry->isDeclaration()) {
4656 GlobalDecl OtherGD;
4657 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
4658 // to make sure that we issue an error only once.
4659 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4660 (GD.getCanonicalDecl().getDecl() !=
4661 OtherGD.getCanonicalDecl().getDecl()) &&
4662 DiagnosedConflictingDefinitions.insert(GD).second) {
4663 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4664 << MangledName;
4665 getDiags().Report(OtherGD.getDecl()->getLocation(),
4666 diag::note_previous_definition);
4667 }
4668 }
4669
4670 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4671 (Entry->getValueType() == Ty)) {
4672 return Entry;
4673 }
4674
4675 // Make sure the result is of the correct type.
4676 // (If function is requested for a definition, we always need to create a new
4677 // function, not just return a bitcast.)
4678 if (!IsForDefinition)
4679 return Entry;
4680 }
4681
4682 // This function doesn't have a complete type (for example, the return
4683 // type is an incomplete struct). Use a fake type instead, and make
4684 // sure not to try to set attributes.
4685 bool IsIncompleteFunction = false;
4686
4687 llvm::FunctionType *FTy;
4688 if (isa<llvm::FunctionType>(Ty)) {
4689 FTy = cast<llvm::FunctionType>(Ty);
4690 } else {
4691 FTy = llvm::FunctionType::get(VoidTy, false);
4692 IsIncompleteFunction = true;
4693 }
4694
4695 llvm::Function *F =
4696 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4697 Entry ? StringRef() : MangledName, &getModule());
4698
4699 // Store the declaration associated with this function so it is potentially
4700 // updated by further declarations or definitions and emitted at the end.
4701 if (D && D->hasAttr<AnnotateAttr>())
4702 DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
4703
4704 // If we already created a function with the same mangled name (but different
4705 // type) before, take its name and add it to the list of functions to be
4706 // replaced with F at the end of CodeGen.
4707 //
4708 // This happens if there is a prototype for a function (e.g. "int f()") and
4709 // then a definition of a different type (e.g. "int f(int x)").
4710 if (Entry) {
4711 F->takeName(Entry);
4712
4713 // This might be an implementation of a function without a prototype, in
4714 // which case, try to do special replacement of calls which match the new
4715 // prototype. The really key thing here is that we also potentially drop
4716 // arguments from the call site so as to make a direct call, which makes the
4717 // inliner happier and suppresses a number of optimizer warnings (!) about
4718 // dropping arguments.
4719 if (!Entry->use_empty()) {
4721 Entry->removeDeadConstantUsers();
4722 }
4723
4724 addGlobalValReplacement(Entry, F);
4725 }
4726
4727 assert(F->getName() == MangledName && "name was uniqued!");
4728 if (D)
4729 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4730 if (ExtraAttrs.hasFnAttrs()) {
4731 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4732 F->addFnAttrs(B);
4733 }
4734
4735 if (!DontDefer) {
4736 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4737 // each other bottoming out with the base dtor. Therefore we emit non-base
4738 // dtors on usage, even if there is no dtor definition in the TU.
4739 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
4740 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
4741 GD.getDtorType()))
4742 addDeferredDeclToEmit(GD);
4743
4744 // This is the first use or definition of a mangled name. If there is a
4745 // deferred decl with this name, remember that we need to emit it at the end
4746 // of the file.
4747 auto DDI = DeferredDecls.find(MangledName);
4748 if (DDI != DeferredDecls.end()) {
4749 // Move the potentially referenced deferred decl to the
4750 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4751 // don't need it anymore).
4752 addDeferredDeclToEmit(DDI->second);
4753 DeferredDecls.erase(DDI);
4754
4755 // Otherwise, there are cases we have to worry about where we're
4756 // using a declaration for which we must emit a definition but where
4757 // we might not find a top-level definition:
4758 // - member functions defined inline in their classes
4759 // - friend functions defined inline in some class
4760 // - special member functions with implicit definitions
4761 // If we ever change our AST traversal to walk into class methods,
4762 // this will be unnecessary.
4763 //
4764 // We also don't emit a definition for a function if it's going to be an
4765 // entry in a vtable, unless it's already marked as used.
4766 } else if (getLangOpts().CPlusPlus && D) {
4767 // Look for a declaration that's lexically in a record.
4768 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4769 FD = FD->getPreviousDecl()) {
4770 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
4771 if (FD->doesThisDeclarationHaveABody()) {
4772 addDeferredDeclToEmit(GD.getWithDecl(FD));
4773 break;
4774 }
4775 }
4776 }
4777 }
4778 }
4779
4780 // Make sure the result is of the requested type.
4781 if (!IsIncompleteFunction) {
4782 assert(F->getFunctionType() == Ty);
4783 return F;
4784 }
4785
4786 return F;
4787}
4788
4789/// GetAddrOfFunction - Return the address of the given function. If Ty is
4790/// non-null, then this function will use the specified type if it has to
4791/// create it (this occurs when we see a definition of the function).
4792llvm::Constant *
4793CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
4794 bool DontDefer,
4795 ForDefinition_t IsForDefinition) {
4796 // If there was no specific requested type, just convert it now.
4797 if (!Ty) {
4798 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4799 Ty = getTypes().ConvertType(FD->getType());
4800 }
4801
4802 // Devirtualized destructor calls may come through here instead of via
4803 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4804 // of the complete destructor when necessary.
4805 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
4806 if (getTarget().getCXXABI().isMicrosoft() &&
4807 GD.getDtorType() == Dtor_Complete &&
4808 DD->getParent()->getNumVBases() == 0)
4809 GD = GlobalDecl(DD, Dtor_Base);
4810 }
4811
4812 StringRef MangledName = getMangledName(GD);
4813 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4814 /*IsThunk=*/false, llvm::AttributeList(),
4815 IsForDefinition);
4816 // Returns kernel handle for HIP kernel stub function.
4817 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4818 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4819 auto *Handle = getCUDARuntime().getKernelHandle(
4820 cast<llvm::Function>(F->stripPointerCasts()), GD);
4821 if (IsForDefinition)
4822 return F;
4823 return Handle;
4824 }
4825 return F;
4826}
4827
4829 llvm::GlobalValue *F =
4830 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4831
4832 return llvm::NoCFIValue::get(F);
4833}
4834
4835static const FunctionDecl *
4837 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4839
4840 IdentifierInfo &CII = C.Idents.get(Name);
4841 for (const auto *Result : DC->lookup(&CII))
4842 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4843 return FD;
4844
4845 if (!C.getLangOpts().CPlusPlus)
4846 return nullptr;
4847
4848 // Demangle the premangled name from getTerminateFn()
4849 IdentifierInfo &CXXII =
4850 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4851 ? C.Idents.get("terminate")
4852 : C.Idents.get(Name);
4853
4854 for (const auto &N : {"__cxxabiv1", "std"}) {
4855 IdentifierInfo &NS = C.Idents.get(N);
4856 for (const auto *Result : DC->lookup(&NS)) {
4857 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4858 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4859 for (const auto *Result : LSD->lookup(&NS))
4860 if ((ND = dyn_cast<NamespaceDecl>(Result)))
4861 break;
4862
4863 if (ND)
4864 for (const auto *Result : ND->lookup(&CXXII))
4865 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4866 return FD;
4867 }
4868 }
4869
4870 return nullptr;
4871}
4872
4873/// CreateRuntimeFunction - Create a new runtime function with the specified
4874/// type and name.
4875llvm::FunctionCallee
4876CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4877 llvm::AttributeList ExtraAttrs, bool Local,
4878 bool AssumeConvergent) {
4879 if (AssumeConvergent) {
4880 ExtraAttrs =
4881 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4882 }
4883
4884 llvm::Constant *C =
4885 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4886 /*DontDefer=*/false, /*IsThunk=*/false,
4887 ExtraAttrs);
4888
4889 if (auto *F = dyn_cast<llvm::Function>(C)) {
4890 if (F->empty()) {
4891 F->setCallingConv(getRuntimeCC());
4892
4893 // In Windows Itanium environments, try to mark runtime functions
4894 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4895 // will link their standard library statically or dynamically. Marking
4896 // functions imported when they are not imported can cause linker errors
4897 // and warnings.
4898 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4899 !getCodeGenOpts().LTOVisibilityPublicStd) {
4900 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4901 if (!FD || FD->hasAttr<DLLImportAttr>()) {
4902 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4903 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4904 }
4905 }
4906 setDSOLocal(F);
4907 // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
4908 // of trying to approximate the attributes using the LLVM function
4909 // signature. This requires revising the API of CreateRuntimeFunction().
4910 markRegisterParameterAttributes(F);
4911 }
4912 }
4913
4914 return {FTy, C};
4915}
4916
4917/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4918/// create and return an llvm GlobalVariable with the specified type and address
4919/// space. If there is something in the module with the specified name, return
4920/// it potentially bitcasted to the right type.
4921///
4922/// If D is non-null, it specifies a decl that correspond to this. This is used
4923/// to set the attributes on the global when it is first created.
4924///
4925/// If IsForDefinition is true, it is guaranteed that an actual global with
4926/// type Ty will be returned, not conversion of a variable with the same
4927/// mangled name but some other type.
4928llvm::Constant *
4929CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4930 LangAS AddrSpace, const VarDecl *D,
4931 ForDefinition_t IsForDefinition) {
4932 // Lookup the entry, lazily creating it if necessary.
4933 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4934 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4935 if (Entry) {
4936 if (WeakRefReferences.erase(Entry)) {
4937 if (D && !D->hasAttr<WeakAttr>())
4938 Entry->setLinkage(llvm::Function::ExternalLinkage);
4939 }
4940
4941 // Handle dropped DLL attributes.
4942 if (D && shouldDropDLLAttribute(D, Entry))
4943 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4944
4945 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4947
4948 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4949 return Entry;
4950
4951 // If there are two attempts to define the same mangled name, issue an
4952 // error.
4953 if (IsForDefinition && !Entry->isDeclaration()) {
4954 GlobalDecl OtherGD;
4955 const VarDecl *OtherD;
4956
4957 // Check that D is not yet in DiagnosedConflictingDefinitions is required
4958 // to make sure that we issue an error only once.
4959 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4960 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4961 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4962 OtherD->hasInit() &&
4963 DiagnosedConflictingDefinitions.insert(D).second) {
4964 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4965 << MangledName;
4966 getDiags().Report(OtherGD.getDecl()->getLocation(),
4967 diag::note_previous_definition);
4968 }
4969 }
4970
4971 // Make sure the result is of the correct type.
4972 if (Entry->getType()->getAddressSpace() != TargetAS)
4973 return llvm::ConstantExpr::getAddrSpaceCast(
4974 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
4975
4976 // (If global is requested for a definition, we always need to create a new
4977 // global, not just return a bitcast.)
4978 if (!IsForDefinition)
4979 return Entry;
4980 }
4981
4982 auto DAddrSpace = GetGlobalVarAddressSpace(D);
4983
4984 auto *GV = new llvm::GlobalVariable(
4985 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4986 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4987 getContext().getTargetAddressSpace(DAddrSpace));
4988
4989 // If we already created a global with the same mangled name (but different
4990 // type) before, take its name and remove it from its parent.
4991 if (Entry) {
4992 GV->takeName(Entry);
4993
4994 if (!Entry->use_empty()) {
4995 Entry->replaceAllUsesWith(GV);
4996 }
4997
4998 Entry->eraseFromParent();
4999 }
5000
5001 // This is the first use or definition of a mangled name. If there is a
5002 // deferred decl with this name, remember that we need to emit it at the end
5003 // of the file.
5004 auto DDI = DeferredDecls.find(MangledName);
5005 if (DDI != DeferredDecls.end()) {
5006 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
5007 // list, and remove it from DeferredDecls (since we don't need it anymore).
5008 addDeferredDeclToEmit(DDI->second);
5009 DeferredDecls.erase(DDI);
5010 }
5011
5012 // Handle things which are present even on external declarations.
5013 if (D) {
5014 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5016
5017 // FIXME: This code is overly simple and should be merged with other global
5018 // handling.
5019 GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
5020
5021 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
5022
5023 setLinkageForGV(GV, D);
5024
5025 if (D->getTLSKind()) {
5026 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5027 CXXThreadLocals.push_back(D);
5028 setTLSMode(GV, *D);
5029 }
5030
5031 setGVProperties(GV, D);
5032
5033 // If required by the ABI, treat declarations of static data members with
5034 // inline initializers as definitions.
5035 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
5036 EmitGlobalVarDefinition(D);
5037 }
5038
5039 // Emit section information for extern variables.
5040 if (D->hasExternalStorage()) {
5041 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
5042 GV->setSection(SA->getName());
5043 }
5044
5045 // Handle XCore specific ABI requirements.
5046 if (getTriple().getArch() == llvm::Triple::xcore &&
5047 D->getLanguageLinkage() == CLanguageLinkage &&
5048 D->getType().isConstant(Context) &&
5049 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
5050 GV->setSection(".cp.rodata");
5051
5052 // Handle code model attribute
5053 if (const auto *CMA = D->getAttr<CodeModelAttr>())
5054 GV->setCodeModel(CMA->getModel());
5055
5056 // Check if we a have a const declaration with an initializer, we may be
5057 // able to emit it as available_externally to expose it's value to the
5058 // optimizer.
5059 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5060 D->getType().isConstQualified() && !GV->hasInitializer() &&
5061 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
5062 const auto *Record =
5063 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
5064 bool HasMutableFields = Record && Record->hasMutableFields();
5065 if (!HasMutableFields) {
5066 const VarDecl *InitDecl;
5067 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5068 if (InitExpr) {
5069 ConstantEmitter emitter(*this);
5070 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
5071 if (Init) {
5072 auto *InitType = Init->getType();
5073 if (GV->getValueType() != InitType) {
5074 // The type of the initializer does not match the definition.
5075 // This happens when an initializer has a different type from
5076 // the type of the global (because of padding at the end of a
5077 // structure for instance).
5078 GV->setName(StringRef());
5079 // Make a new global with the correct type, this is now guaranteed
5080 // to work.
5081 auto *NewGV = cast<llvm::GlobalVariable>(
5082 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
5083 ->stripPointerCasts());
5084
5085 // Erase the old global, since it is no longer used.
5086 GV->eraseFromParent();
5087 GV = NewGV;
5088 } else {
5089 GV->setInitializer(Init);
5090 GV->setConstant(true);
5091 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5092 }
5093 emitter.finalize(GV);
5094 }
5095 }
5096 }
5097 }
5098 }
5099
5100 if (D &&
5101 D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
5103 // External HIP managed variables needed to be recorded for transformation
5104 // in both device and host compilations.
5105 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
5106 D->hasExternalStorage())
5108 }
5109
5110 if (D)
5111 SanitizerMD->reportGlobal(GV, *D);
5112
5113 LangAS ExpectedAS =
5114 D ? D->getType().getAddressSpace()
5115 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
5116 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5117 if (DAddrSpace != ExpectedAS) {
5119 *this, GV, DAddrSpace, ExpectedAS,
5120 llvm::PointerType::get(getLLVMContext(), TargetAS));
5121 }
5122
5123 return GV;
5124}
5125
5126llvm::Constant *
5128 const Decl *D = GD.getDecl();
5129
5130 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
5131 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
5132 /*DontDefer=*/false, IsForDefinition);
5133
5134 if (isa<CXXMethodDecl>(D)) {
5135 auto FInfo =
5136 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
5137 auto Ty = getTypes().GetFunctionType(*FInfo);
5138 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5139 IsForDefinition);
5140 }
5141
5142 if (isa<FunctionDecl>(D)) {
5144 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5145 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5146 IsForDefinition);
5147 }
5148
5149 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
5150}
5151
5153 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes