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