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