[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / lib / CodeGen / CodeGenModule.cpp
blob71a2f61ea955f3bdaa085397d81b8e4d6c5c75c8
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.
11 //===----------------------------------------------------------------------===//
13 #include "CodeGenModule.h"
14 #include "ABIInfo.h"
15 #include "CGBlocks.h"
16 #include "CGCUDARuntime.h"
17 #include "CGCXXABI.h"
18 #include "CGCall.h"
19 #include "CGDebugInfo.h"
20 #include "CGHLSLRuntime.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "CGOpenMPRuntime.h"
24 #include "CGOpenMPRuntimeGPU.h"
25 #include "CodeGenFunction.h"
26 #include "CodeGenPGO.h"
27 #include "ConstantEmitter.h"
28 #include "CoverageMappingGen.h"
29 #include "TargetInfo.h"
30 #include "clang/AST/ASTContext.h"
31 #include "clang/AST/CharUnits.h"
32 #include "clang/AST/DeclCXX.h"
33 #include "clang/AST/DeclObjC.h"
34 #include "clang/AST/DeclTemplate.h"
35 #include "clang/AST/Mangle.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/AST/StmtVisitor.h"
38 #include "clang/Basic/Builtins.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/CodeGenOptions.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/FileManager.h"
43 #include "clang/Basic/Module.h"
44 #include "clang/Basic/SourceManager.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "clang/Basic/Version.h"
47 #include "clang/CodeGen/BackendUtil.h"
48 #include "clang/CodeGen/ConstantInitBuilder.h"
49 #include "clang/Frontend/FrontendDiagnostic.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSwitch.h"
53 #include "llvm/Analysis/TargetLibraryInfo.h"
54 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/Intrinsics.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/ProfileSummary.h"
61 #include "llvm/ProfileData/InstrProfReader.h"
62 #include "llvm/ProfileData/SampleProf.h"
63 #include "llvm/Support/CRC.h"
64 #include "llvm/Support/CodeGen.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/ConvertUTF.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/TimeProfiler.h"
69 #include "llvm/Support/xxhash.h"
70 #include "llvm/TargetParser/Triple.h"
71 #include "llvm/TargetParser/X86TargetParser.h"
72 #include <optional>
74 using namespace clang;
75 using namespace CodeGen;
77 static llvm::cl::opt<bool> LimitedCoverage(
78 "limited-coverage-experimental", llvm::cl::Hidden,
79 llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
81 static const char AnnotationSection[] = "llvm.metadata";
83 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
84 switch (CGM.getContext().getCXXABIKind()) {
85 case TargetCXXABI::AppleARM64:
86 case TargetCXXABI::Fuchsia:
87 case TargetCXXABI::GenericAArch64:
88 case TargetCXXABI::GenericARM:
89 case TargetCXXABI::iOS:
90 case TargetCXXABI::WatchOS:
91 case TargetCXXABI::GenericMIPS:
92 case TargetCXXABI::GenericItanium:
93 case TargetCXXABI::WebAssembly:
94 case TargetCXXABI::XL:
95 return CreateItaniumCXXABI(CGM);
96 case TargetCXXABI::Microsoft:
97 return CreateMicrosoftCXXABI(CGM);
100 llvm_unreachable("invalid C++ ABI kind");
103 CodeGenModule::CodeGenModule(ASTContext &C,
104 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
105 const HeaderSearchOptions &HSO,
106 const PreprocessorOptions &PPO,
107 const CodeGenOptions &CGO, llvm::Module &M,
108 DiagnosticsEngine &diags,
109 CoverageSourceInfo *CoverageInfo)
110 : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
111 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
112 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
113 VMContext(M.getContext()), Types(*this), VTables(*this),
114 SanitizerMD(new SanitizerMetadata(*this)) {
116 // Initialize the type cache.
117 llvm::LLVMContext &LLVMContext = M.getContext();
118 VoidTy = llvm::Type::getVoidTy(LLVMContext);
119 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
120 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
121 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
122 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
123 HalfTy = llvm::Type::getHalfTy(LLVMContext);
124 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
125 FloatTy = llvm::Type::getFloatTy(LLVMContext);
126 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
127 PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
128 PointerAlignInBytes =
129 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
130 .getQuantity();
131 SizeSizeInBytes =
132 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
133 IntAlignInBytes =
134 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
135 CharTy =
136 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
137 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
138 IntPtrTy = llvm::IntegerType::get(LLVMContext,
139 C.getTargetInfo().getMaxPointerWidth());
140 Int8PtrTy = Int8Ty->getPointerTo(0);
141 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
142 const llvm::DataLayout &DL = M.getDataLayout();
143 AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
144 GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
145 ConstGlobalsPtrTy = Int8Ty->getPointerTo(
146 C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
147 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
149 // Build C++20 Module initializers.
150 // TODO: Add Microsoft here once we know the mangling required for the
151 // initializers.
152 CXX20ModuleInits =
153 LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
154 ItaniumMangleContext::MK_Itanium;
156 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
158 if (LangOpts.ObjC)
159 createObjCRuntime();
160 if (LangOpts.OpenCL)
161 createOpenCLRuntime();
162 if (LangOpts.OpenMP)
163 createOpenMPRuntime();
164 if (LangOpts.CUDA)
165 createCUDARuntime();
166 if (LangOpts.HLSL)
167 createHLSLRuntime();
169 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
170 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
171 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
172 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
173 getCXXABI().getMangleContext()));
175 // If debug info or coverage generation is enabled, create the CGDebugInfo
176 // object.
177 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
178 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
179 DebugInfo.reset(new CGDebugInfo(*this));
181 Block.GlobalUniqueCount = 0;
183 if (C.getLangOpts().ObjC)
184 ObjCData.reset(new ObjCEntrypoints());
186 if (CodeGenOpts.hasProfileClangUse()) {
187 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
188 CodeGenOpts.ProfileInstrumentUsePath, *FS,
189 CodeGenOpts.ProfileRemappingFile);
190 // We're checking for profile read errors in CompilerInvocation, so if
191 // there was an error it should've already been caught. If it hasn't been
192 // somehow, trip an assertion.
193 assert(ReaderOrErr);
194 PGOReader = std::move(ReaderOrErr.get());
197 // If coverage mapping generation is enabled, create the
198 // CoverageMappingModuleGen object.
199 if (CodeGenOpts.CoverageMapping)
200 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
202 // Generate the module name hash here if needed.
203 if (CodeGenOpts.UniqueInternalLinkageNames &&
204 !getModule().getSourceFileName().empty()) {
205 std::string Path = getModule().getSourceFileName();
206 // Check if a path substitution is needed from the MacroPrefixMap.
207 for (const auto &Entry : LangOpts.MacroPrefixMap)
208 if (Path.rfind(Entry.first, 0) != std::string::npos) {
209 Path = Entry.second + Path.substr(Entry.first.size());
210 break;
212 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
216 CodeGenModule::~CodeGenModule() {}
218 void CodeGenModule::createObjCRuntime() {
219 // This is just isGNUFamily(), but we want to force implementors of
220 // new ABIs to decide how best to do this.
221 switch (LangOpts.ObjCRuntime.getKind()) {
222 case ObjCRuntime::GNUstep:
223 case ObjCRuntime::GCC:
224 case ObjCRuntime::ObjFW:
225 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
226 return;
228 case ObjCRuntime::FragileMacOSX:
229 case ObjCRuntime::MacOSX:
230 case ObjCRuntime::iOS:
231 case ObjCRuntime::WatchOS:
232 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
233 return;
235 llvm_unreachable("bad runtime kind");
238 void CodeGenModule::createOpenCLRuntime() {
239 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
242 void CodeGenModule::createOpenMPRuntime() {
243 // Select a specialized code generation class based on the target, if any.
244 // If it does not exist use the default implementation.
245 switch (getTriple().getArch()) {
246 case llvm::Triple::nvptx:
247 case llvm::Triple::nvptx64:
248 case llvm::Triple::amdgcn:
249 assert(getLangOpts().OpenMPIsDevice &&
250 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
251 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
252 break;
253 default:
254 if (LangOpts.OpenMPSimd)
255 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
256 else
257 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
258 break;
262 void CodeGenModule::createCUDARuntime() {
263 CUDARuntime.reset(CreateNVCUDARuntime(*this));
266 void CodeGenModule::createHLSLRuntime() {
267 HLSLRuntime.reset(new CGHLSLRuntime(*this));
270 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
271 Replacements[Name] = C;
274 void CodeGenModule::applyReplacements() {
275 for (auto &I : Replacements) {
276 StringRef MangledName = I.first();
277 llvm::Constant *Replacement = I.second;
278 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
279 if (!Entry)
280 continue;
281 auto *OldF = cast<llvm::Function>(Entry);
282 auto *NewF = dyn_cast<llvm::Function>(Replacement);
283 if (!NewF) {
284 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
285 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
286 } else {
287 auto *CE = cast<llvm::ConstantExpr>(Replacement);
288 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
289 CE->getOpcode() == llvm::Instruction::GetElementPtr);
290 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
294 // Replace old with new, but keep the old order.
295 OldF->replaceAllUsesWith(Replacement);
296 if (NewF) {
297 NewF->removeFromParent();
298 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
299 NewF);
301 OldF->eraseFromParent();
305 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
306 GlobalValReplacements.push_back(std::make_pair(GV, C));
309 void CodeGenModule::applyGlobalValReplacements() {
310 for (auto &I : GlobalValReplacements) {
311 llvm::GlobalValue *GV = I.first;
312 llvm::Constant *C = I.second;
314 GV->replaceAllUsesWith(C);
315 GV->eraseFromParent();
319 // This is only used in aliases that we created and we know they have a
320 // linear structure.
321 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
322 const llvm::Constant *C;
323 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
324 C = GA->getAliasee();
325 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
326 C = GI->getResolver();
327 else
328 return GV;
330 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
331 if (!AliaseeGV)
332 return nullptr;
334 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
335 if (FinalGV == GV)
336 return nullptr;
338 return FinalGV;
341 static bool checkAliasedGlobal(DiagnosticsEngine &Diags,
342 SourceLocation Location, bool IsIFunc,
343 const llvm::GlobalValue *Alias,
344 const llvm::GlobalValue *&GV) {
345 GV = getAliasedGlobal(Alias);
346 if (!GV) {
347 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
348 return false;
351 if (GV->isDeclaration()) {
352 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
353 return false;
356 if (IsIFunc) {
357 // Check resolver function type.
358 const auto *F = dyn_cast<llvm::Function>(GV);
359 if (!F) {
360 Diags.Report(Location, diag::err_alias_to_undefined)
361 << IsIFunc << IsIFunc;
362 return false;
365 llvm::FunctionType *FTy = F->getFunctionType();
366 if (!FTy->getReturnType()->isPointerTy()) {
367 Diags.Report(Location, diag::err_ifunc_resolver_return);
368 return false;
372 return true;
375 void CodeGenModule::checkAliases() {
376 // Check if the constructed aliases are well formed. It is really unfortunate
377 // that we have to do this in CodeGen, but we only construct mangled names
378 // and aliases during codegen.
379 bool Error = false;
380 DiagnosticsEngine &Diags = getDiags();
381 for (const GlobalDecl &GD : Aliases) {
382 const auto *D = cast<ValueDecl>(GD.getDecl());
383 SourceLocation Location;
384 bool IsIFunc = D->hasAttr<IFuncAttr>();
385 if (const Attr *A = D->getDefiningAttr())
386 Location = A->getLocation();
387 else
388 llvm_unreachable("Not an alias or ifunc?");
390 StringRef MangledName = getMangledName(GD);
391 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
392 const llvm::GlobalValue *GV = nullptr;
393 if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) {
394 Error = true;
395 continue;
398 llvm::Constant *Aliasee =
399 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
400 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
402 llvm::GlobalValue *AliaseeGV;
403 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
404 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
405 else
406 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
408 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
409 StringRef AliasSection = SA->getName();
410 if (AliasSection != AliaseeGV->getSection())
411 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
412 << AliasSection << IsIFunc << IsIFunc;
415 // We have to handle alias to weak aliases in here. LLVM itself disallows
416 // this since the object semantics would not match the IL one. For
417 // compatibility with gcc we implement it by just pointing the alias
418 // to its aliasee's aliasee. We also warn, since the user is probably
419 // expecting the link to be weak.
420 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
421 if (GA->isInterposable()) {
422 Diags.Report(Location, diag::warn_alias_to_weak_alias)
423 << GV->getName() << GA->getName() << IsIFunc;
424 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
425 GA->getAliasee(), Alias->getType());
427 if (IsIFunc)
428 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
429 else
430 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
434 if (!Error)
435 return;
437 for (const GlobalDecl &GD : Aliases) {
438 StringRef MangledName = getMangledName(GD);
439 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
440 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
441 Alias->eraseFromParent();
445 void CodeGenModule::clear() {
446 DeferredDeclsToEmit.clear();
447 EmittedDeferredDecls.clear();
448 if (OpenMPRuntime)
449 OpenMPRuntime->clear();
452 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
453 StringRef MainFile) {
454 if (!hasDiagnostics())
455 return;
456 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
457 if (MainFile.empty())
458 MainFile = "<stdin>";
459 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
460 } else {
461 if (Mismatched > 0)
462 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
464 if (Missing > 0)
465 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
469 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
470 llvm::Module &M) {
471 if (!LO.VisibilityFromDLLStorageClass)
472 return;
474 llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
475 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
476 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
477 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
478 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
479 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
480 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
481 CodeGenModule::GetLLVMVisibility(
482 LO.getExternDeclNoDLLStorageClassVisibility());
484 for (llvm::GlobalValue &GV : M.global_values()) {
485 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
486 continue;
488 // Reset DSO locality before setting the visibility. This removes
489 // any effects that visibility options and annotations may have
490 // had on the DSO locality. Setting the visibility will implicitly set
491 // appropriate globals to DSO Local; however, this will be pessimistic
492 // w.r.t. to the normal compiler IRGen.
493 GV.setDSOLocal(false);
495 if (GV.isDeclarationForLinker()) {
496 GV.setVisibility(GV.getDLLStorageClass() ==
497 llvm::GlobalValue::DLLImportStorageClass
498 ? ExternDeclDLLImportVisibility
499 : ExternDeclNoDLLStorageClassVisibility);
500 } else {
501 GV.setVisibility(GV.getDLLStorageClass() ==
502 llvm::GlobalValue::DLLExportStorageClass
503 ? DLLExportVisibility
504 : NoDLLStorageClassVisibility);
507 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
511 void CodeGenModule::Release() {
512 Module *Primary = getContext().getNamedModuleForCodeGen();
513 if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
514 EmitModuleInitializers(Primary);
515 EmitDeferred();
516 DeferredDecls.insert(EmittedDeferredDecls.begin(),
517 EmittedDeferredDecls.end());
518 EmittedDeferredDecls.clear();
519 EmitVTablesOpportunistically();
520 applyGlobalValReplacements();
521 applyReplacements();
522 emitMultiVersionFunctions();
524 if (Context.getLangOpts().IncrementalExtensions &&
525 GlobalTopLevelStmtBlockInFlight.first) {
526 const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
527 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
528 GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
531 if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
532 EmitCXXModuleInitFunc(Primary);
533 else
534 EmitCXXGlobalInitFunc();
535 EmitCXXGlobalCleanUpFunc();
536 registerGlobalDtorsWithAtExit();
537 EmitCXXThreadLocalInitFunc();
538 if (ObjCRuntime)
539 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
540 AddGlobalCtor(ObjCInitFunction);
541 if (Context.getLangOpts().CUDA && CUDARuntime) {
542 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
543 AddGlobalCtor(CudaCtorFunction);
545 if (OpenMPRuntime) {
546 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
547 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
548 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
550 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
551 OpenMPRuntime->clear();
553 if (PGOReader) {
554 getModule().setProfileSummary(
555 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
556 llvm::ProfileSummary::PSK_Instr);
557 if (PGOStats.hasDiagnostics())
558 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
560 llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
561 return L.LexOrder < R.LexOrder;
563 EmitCtorList(GlobalCtors, "llvm.global_ctors");
564 EmitCtorList(GlobalDtors, "llvm.global_dtors");
565 EmitGlobalAnnotations();
566 EmitStaticExternCAliases();
567 checkAliases();
568 EmitDeferredUnusedCoverageMappings();
569 CodeGenPGO(*this).setValueProfilingFlag(getModule());
570 if (CoverageMapping)
571 CoverageMapping->emit();
572 if (CodeGenOpts.SanitizeCfiCrossDso) {
573 CodeGenFunction(*this).EmitCfiCheckFail();
574 CodeGenFunction(*this).EmitCfiCheckStub();
576 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
577 finalizeKCFITypes();
578 emitAtAvailableLinkGuard();
579 if (Context.getTargetInfo().getTriple().isWasm())
580 EmitMainVoidAlias();
582 if (getTriple().isAMDGPU()) {
583 // Emit reference of __amdgpu_device_library_preserve_asan_functions to
584 // preserve ASAN functions in bitcode libraries.
585 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
586 auto *FT = llvm::FunctionType::get(VoidTy, {});
587 auto *F = llvm::Function::Create(
588 FT, llvm::GlobalValue::ExternalLinkage,
589 "__amdgpu_device_library_preserve_asan_functions", &getModule());
590 auto *Var = new llvm::GlobalVariable(
591 getModule(), FT->getPointerTo(),
592 /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F,
593 "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr,
594 llvm::GlobalVariable::NotThreadLocal);
595 addCompilerUsedGlobal(Var);
597 // Emit amdgpu_code_object_version module flag, which is code object version
598 // times 100.
599 if (getTarget().getTargetOpts().CodeObjectVersion !=
600 TargetOptions::COV_None) {
601 getModule().addModuleFlag(llvm::Module::Error,
602 "amdgpu_code_object_version",
603 getTarget().getTargetOpts().CodeObjectVersion);
607 // Emit a global array containing all external kernels or device variables
608 // used by host functions and mark it as used for CUDA/HIP. This is necessary
609 // to get kernels or device variables in archives linked in even if these
610 // kernels or device variables are only used in host functions.
611 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
612 SmallVector<llvm::Constant *, 8> UsedArray;
613 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
614 GlobalDecl GD;
615 if (auto *FD = dyn_cast<FunctionDecl>(D))
616 GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
617 else
618 GD = GlobalDecl(D);
619 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
620 GetAddrOfGlobal(GD), Int8PtrTy));
623 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
625 auto *GV = new llvm::GlobalVariable(
626 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
627 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
628 addCompilerUsedGlobal(GV);
631 emitLLVMUsed();
632 if (SanStats)
633 SanStats->finish();
635 if (CodeGenOpts.Autolink &&
636 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
637 EmitModuleLinkOptions();
640 // On ELF we pass the dependent library specifiers directly to the linker
641 // without manipulating them. This is in contrast to other platforms where
642 // they are mapped to a specific linker option by the compiler. This
643 // difference is a result of the greater variety of ELF linkers and the fact
644 // that ELF linkers tend to handle libraries in a more complicated fashion
645 // than on other platforms. This forces us to defer handling the dependent
646 // libs to the linker.
648 // CUDA/HIP device and host libraries are different. Currently there is no
649 // way to differentiate dependent libraries for host or device. Existing
650 // usage of #pragma comment(lib, *) is intended for host libraries on
651 // Windows. Therefore emit llvm.dependent-libraries only for host.
652 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
653 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
654 for (auto *MD : ELFDependentLibraries)
655 NMD->addOperand(MD);
658 // Record mregparm value now so it is visible through rest of codegen.
659 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
660 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
661 CodeGenOpts.NumRegisterParameters);
663 if (CodeGenOpts.DwarfVersion) {
664 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
665 CodeGenOpts.DwarfVersion);
668 if (CodeGenOpts.Dwarf64)
669 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
671 if (Context.getLangOpts().SemanticInterposition)
672 // Require various optimization to respect semantic interposition.
673 getModule().setSemanticInterposition(true);
675 if (CodeGenOpts.EmitCodeView) {
676 // Indicate that we want CodeView in the metadata.
677 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
679 if (CodeGenOpts.CodeViewGHash) {
680 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
682 if (CodeGenOpts.ControlFlowGuard) {
683 // Function ID tables and checks for Control Flow Guard (cfguard=2).
684 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
685 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
686 // Function ID tables for Control Flow Guard (cfguard=1).
687 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
689 if (CodeGenOpts.EHContGuard) {
690 // Function ID tables for EH Continuation Guard.
691 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
693 if (Context.getLangOpts().Kernel) {
694 // Note if we are compiling with /kernel.
695 getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
697 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
698 // We don't support LTO with 2 with different StrictVTablePointers
699 // FIXME: we could support it by stripping all the information introduced
700 // by StrictVTablePointers.
702 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
704 llvm::Metadata *Ops[2] = {
705 llvm::MDString::get(VMContext, "StrictVTablePointers"),
706 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
707 llvm::Type::getInt32Ty(VMContext), 1))};
709 getModule().addModuleFlag(llvm::Module::Require,
710 "StrictVTablePointersRequirement",
711 llvm::MDNode::get(VMContext, Ops));
713 if (getModuleDebugInfo())
714 // We support a single version in the linked module. The LLVM
715 // parser will drop debug info with a different version number
716 // (and warn about it, too).
717 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
718 llvm::DEBUG_METADATA_VERSION);
720 // We need to record the widths of enums and wchar_t, so that we can generate
721 // the correct build attributes in the ARM backend. wchar_size is also used by
722 // TargetLibraryInfo.
723 uint64_t WCharWidth =
724 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
725 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
727 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
728 if ( Arch == llvm::Triple::arm
729 || Arch == llvm::Triple::armeb
730 || Arch == llvm::Triple::thumb
731 || Arch == llvm::Triple::thumbeb) {
732 // The minimum width of an enum in bytes
733 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
734 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
737 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
738 StringRef ABIStr = Target.getABI();
739 llvm::LLVMContext &Ctx = TheModule.getContext();
740 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
741 llvm::MDString::get(Ctx, ABIStr));
744 if (CodeGenOpts.SanitizeCfiCrossDso) {
745 // Indicate that we want cross-DSO control flow integrity checks.
746 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
749 if (CodeGenOpts.WholeProgramVTables) {
750 // Indicate whether VFE was enabled for this module, so that the
751 // vcall_visibility metadata added under whole program vtables is handled
752 // appropriately in the optimizer.
753 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
754 CodeGenOpts.VirtualFunctionElimination);
757 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
758 getModule().addModuleFlag(llvm::Module::Override,
759 "CFI Canonical Jump Tables",
760 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
763 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
764 getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
765 // KCFI assumes patchable-function-prefix is the same for all indirectly
766 // called functions. Store the expected offset for code generation.
767 if (CodeGenOpts.PatchableFunctionEntryOffset)
768 getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
769 CodeGenOpts.PatchableFunctionEntryOffset);
772 if (CodeGenOpts.CFProtectionReturn &&
773 Target.checkCFProtectionReturnSupported(getDiags())) {
774 // Indicate that we want to instrument return control flow protection.
775 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
779 if (CodeGenOpts.CFProtectionBranch &&
780 Target.checkCFProtectionBranchSupported(getDiags())) {
781 // Indicate that we want to instrument branch control flow protection.
782 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
786 if (CodeGenOpts.FunctionReturnThunks)
787 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
789 if (CodeGenOpts.IndirectBranchCSPrefix)
790 getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
792 // Add module metadata for return address signing (ignoring
793 // non-leaf/all) and stack tagging. These are actually turned on by function
794 // attributes, but we use module metadata to emit build attributes. This is
795 // needed for LTO, where the function attributes are inside bitcode
796 // serialised into a global variable by the time build attributes are
797 // emitted, so we can't access them. LTO objects could be compiled with
798 // different flags therefore module flags are set to "Min" behavior to achieve
799 // the same end result of the normal build where e.g BTI is off if any object
800 // doesn't support it.
801 if (Context.getTargetInfo().hasFeature("ptrauth") &&
802 LangOpts.getSignReturnAddressScope() !=
803 LangOptions::SignReturnAddressScopeKind::None)
804 getModule().addModuleFlag(llvm::Module::Override,
805 "sign-return-address-buildattr", 1);
806 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
807 getModule().addModuleFlag(llvm::Module::Override,
808 "tag-stack-memory-buildattr", 1);
810 if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
811 Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
812 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
813 Arch == llvm::Triple::aarch64_be) {
814 if (LangOpts.BranchTargetEnforcement)
815 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
817 if (LangOpts.hasSignReturnAddress())
818 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
819 if (LangOpts.isSignReturnAddressScopeAll())
820 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
822 if (!LangOpts.isSignReturnAddressWithAKey())
823 getModule().addModuleFlag(llvm::Module::Min,
824 "sign-return-address-with-bkey", 1);
827 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
828 llvm::LLVMContext &Ctx = TheModule.getContext();
829 getModule().addModuleFlag(
830 llvm::Module::Error, "MemProfProfileFilename",
831 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
834 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
835 // Indicate whether __nvvm_reflect should be configured to flush denormal
836 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
837 // property.)
838 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
839 CodeGenOpts.FP32DenormalMode.Output !=
840 llvm::DenormalMode::IEEE);
843 if (LangOpts.EHAsynch)
844 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
846 // Indicate whether this Module was compiled with -fopenmp
847 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
848 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
849 if (getLangOpts().OpenMPIsDevice)
850 getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
851 LangOpts.OpenMP);
853 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
854 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
855 EmitOpenCLMetadata();
856 // Emit SPIR version.
857 if (getTriple().isSPIR()) {
858 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
859 // opencl.spir.version named metadata.
860 // C++ for OpenCL has a distinct mapping for version compatibility with
861 // OpenCL.
862 auto Version = LangOpts.getOpenCLCompatibleVersion();
863 llvm::Metadata *SPIRVerElts[] = {
864 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
865 Int32Ty, Version / 100)),
866 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
867 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
868 llvm::NamedMDNode *SPIRVerMD =
869 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
870 llvm::LLVMContext &Ctx = TheModule.getContext();
871 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
875 // HLSL related end of code gen work items.
876 if (LangOpts.HLSL)
877 getHLSLRuntime().finishCodeGen();
879 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
880 assert(PLevel < 3 && "Invalid PIC Level");
881 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
882 if (Context.getLangOpts().PIE)
883 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
886 if (getCodeGenOpts().CodeModel.size() > 0) {
887 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
888 .Case("tiny", llvm::CodeModel::Tiny)
889 .Case("small", llvm::CodeModel::Small)
890 .Case("kernel", llvm::CodeModel::Kernel)
891 .Case("medium", llvm::CodeModel::Medium)
892 .Case("large", llvm::CodeModel::Large)
893 .Default(~0u);
894 if (CM != ~0u) {
895 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
896 getModule().setCodeModel(codeModel);
900 if (CodeGenOpts.NoPLT)
901 getModule().setRtLibUseGOT();
902 if (CodeGenOpts.UnwindTables)
903 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
905 switch (CodeGenOpts.getFramePointer()) {
906 case CodeGenOptions::FramePointerKind::None:
907 // 0 ("none") is the default.
908 break;
909 case CodeGenOptions::FramePointerKind::NonLeaf:
910 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
911 break;
912 case CodeGenOptions::FramePointerKind::All:
913 getModule().setFramePointer(llvm::FramePointerKind::All);
914 break;
917 SimplifyPersonality();
919 if (getCodeGenOpts().EmitDeclMetadata)
920 EmitDeclMetadata();
922 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
923 EmitCoverageFile();
925 if (CGDebugInfo *DI = getModuleDebugInfo())
926 DI->finalize();
928 if (getCodeGenOpts().EmitVersionIdentMetadata)
929 EmitVersionIdentMetadata();
931 if (!getCodeGenOpts().RecordCommandLine.empty())
932 EmitCommandLineMetadata();
934 if (!getCodeGenOpts().StackProtectorGuard.empty())
935 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
936 if (!getCodeGenOpts().StackProtectorGuardReg.empty())
937 getModule().setStackProtectorGuardReg(
938 getCodeGenOpts().StackProtectorGuardReg);
939 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
940 getModule().setStackProtectorGuardSymbol(
941 getCodeGenOpts().StackProtectorGuardSymbol);
942 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
943 getModule().setStackProtectorGuardOffset(
944 getCodeGenOpts().StackProtectorGuardOffset);
945 if (getCodeGenOpts().StackAlignment)
946 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
947 if (getCodeGenOpts().SkipRaxSetup)
948 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
950 if (getContext().getTargetInfo().getMaxTLSAlign())
951 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
952 getContext().getTargetInfo().getMaxTLSAlign());
954 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
956 EmitBackendOptionsMetadata(getCodeGenOpts());
958 // If there is device offloading code embed it in the host now.
959 EmbedObject(&getModule(), CodeGenOpts, getDiags());
961 // Set visibility from DLL storage class
962 // We do this at the end of LLVM IR generation; after any operation
963 // that might affect the DLL storage class or the visibility, and
964 // before anything that might act on these.
965 setVisibilityFromDLLStorageClass(LangOpts, getModule());
968 void CodeGenModule::EmitOpenCLMetadata() {
969 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
970 // opencl.ocl.version named metadata node.
971 // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
972 auto Version = LangOpts.getOpenCLCompatibleVersion();
973 llvm::Metadata *OCLVerElts[] = {
974 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
975 Int32Ty, Version / 100)),
976 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
977 Int32Ty, (Version % 100) / 10))};
978 llvm::NamedMDNode *OCLVerMD =
979 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
980 llvm::LLVMContext &Ctx = TheModule.getContext();
981 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
984 void CodeGenModule::EmitBackendOptionsMetadata(
985 const CodeGenOptions CodeGenOpts) {
986 if (getTriple().isRISCV()) {
987 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
988 CodeGenOpts.SmallDataLimit);
992 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
993 // Make sure that this type is translated.
994 Types.UpdateCompletedType(TD);
997 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
998 // Make sure that this type is translated.
999 Types.RefreshTypeCacheForClass(RD);
1002 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
1003 if (!TBAA)
1004 return nullptr;
1005 return TBAA->getTypeInfo(QTy);
1008 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
1009 if (!TBAA)
1010 return TBAAAccessInfo();
1011 if (getLangOpts().CUDAIsDevice) {
1012 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1013 // access info.
1014 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1015 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1016 nullptr)
1017 return TBAAAccessInfo();
1018 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1019 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1020 nullptr)
1021 return TBAAAccessInfo();
1024 return TBAA->getAccessInfo(AccessType);
1027 TBAAAccessInfo
1028 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
1029 if (!TBAA)
1030 return TBAAAccessInfo();
1031 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1034 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
1035 if (!TBAA)
1036 return nullptr;
1037 return TBAA->getTBAAStructInfo(QTy);
1040 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
1041 if (!TBAA)
1042 return nullptr;
1043 return TBAA->getBaseTypeInfo(QTy);
1046 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
1047 if (!TBAA)
1048 return nullptr;
1049 return TBAA->getAccessTagInfo(Info);
1052 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
1053 TBAAAccessInfo TargetInfo) {
1054 if (!TBAA)
1055 return TBAAAccessInfo();
1056 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1059 TBAAAccessInfo
1060 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
1061 TBAAAccessInfo InfoB) {
1062 if (!TBAA)
1063 return TBAAAccessInfo();
1064 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1067 TBAAAccessInfo
1068 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
1069 TBAAAccessInfo SrcInfo) {
1070 if (!TBAA)
1071 return TBAAAccessInfo();
1072 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1075 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
1076 TBAAAccessInfo TBAAInfo) {
1077 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1078 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1081 void CodeGenModule::DecorateInstructionWithInvariantGroup(
1082 llvm::Instruction *I, const CXXRecordDecl *RD) {
1083 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1084 llvm::MDNode::get(getLLVMContext(), {}));
1087 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1088 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1089 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1092 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1093 /// specified stmt yet.
1094 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1095 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1096 "cannot compile this %0 yet");
1097 std::string Msg = Type;
1098 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
1099 << Msg << S->getSourceRange();
1102 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1103 /// specified decl yet.
1104 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1105 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1106 "cannot compile this %0 yet");
1107 std::string Msg = Type;
1108 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
1111 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1112 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1115 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1116 const NamedDecl *D) const {
1117 // Internal definitions always have default visibility.
1118 if (GV->hasLocalLinkage()) {
1119 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1120 return;
1122 if (!D)
1123 return;
1124 // Set visibility for definitions, and for declarations if requested globally
1125 // or set explicitly.
1126 LinkageInfo LV = D->getLinkageAndVisibility();
1127 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1128 // Reject incompatible dlllstorage and visibility annotations.
1129 if (!LV.isVisibilityExplicit())
1130 return;
1131 if (GV->hasDLLExportStorageClass()) {
1132 if (LV.getVisibility() == HiddenVisibility)
1133 getDiags().Report(D->getLocation(),
1134 diag::err_hidden_visibility_dllexport);
1135 } else if (LV.getVisibility() != DefaultVisibility) {
1136 getDiags().Report(D->getLocation(),
1137 diag::err_non_default_visibility_dllimport);
1139 return;
1142 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1143 !GV->isDeclarationForLinker())
1144 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1147 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
1148 llvm::GlobalValue *GV) {
1149 if (GV->hasLocalLinkage())
1150 return true;
1152 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1153 return true;
1155 // DLLImport explicitly marks the GV as external.
1156 if (GV->hasDLLImportStorageClass())
1157 return false;
1159 const llvm::Triple &TT = CGM.getTriple();
1160 if (TT.isWindowsGNUEnvironment()) {
1161 // In MinGW, variables without DLLImport can still be automatically
1162 // imported from a DLL by the linker; don't mark variables that
1163 // potentially could come from another DLL as DSO local.
1165 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1166 // (and this actually happens in the public interface of libstdc++), so
1167 // such variables can't be marked as DSO local. (Native TLS variables
1168 // can't be dllimported at all, though.)
1169 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1170 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
1171 return false;
1174 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1175 // remain unresolved in the link, they can be resolved to zero, which is
1176 // outside the current DSO.
1177 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1178 return false;
1180 // Every other GV is local on COFF.
1181 // Make an exception for windows OS in the triple: Some firmware builds use
1182 // *-win32-macho triples. This (accidentally?) produced windows relocations
1183 // without GOT tables in older clang versions; Keep this behaviour.
1184 // FIXME: even thread local variables?
1185 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1186 return true;
1188 // Only handle COFF and ELF for now.
1189 if (!TT.isOSBinFormatELF())
1190 return false;
1192 // If this is not an executable, don't assume anything is local.
1193 const auto &CGOpts = CGM.getCodeGenOpts();
1194 llvm::Reloc::Model RM = CGOpts.RelocationModel;
1195 const auto &LOpts = CGM.getLangOpts();
1196 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1197 // On ELF, if -fno-semantic-interposition is specified and the target
1198 // supports local aliases, there will be neither CC1
1199 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1200 // dso_local on the function if using a local alias is preferable (can avoid
1201 // PLT indirection).
1202 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1203 return false;
1204 return !(CGM.getLangOpts().SemanticInterposition ||
1205 CGM.getLangOpts().HalfNoSemanticInterposition);
1208 // A definition cannot be preempted from an executable.
1209 if (!GV->isDeclarationForLinker())
1210 return true;
1212 // Most PIC code sequences that assume that a symbol is local cannot produce a
1213 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1214 // depended, it seems worth it to handle it here.
1215 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1216 return false;
1218 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1219 if (TT.isPPC64())
1220 return false;
1222 if (CGOpts.DirectAccessExternalData) {
1223 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1224 // for non-thread-local variables. If the symbol is not defined in the
1225 // executable, a copy relocation will be needed at link time. dso_local is
1226 // excluded for thread-local variables because they generally don't support
1227 // copy relocations.
1228 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1229 if (!Var->isThreadLocal())
1230 return true;
1232 // -fno-pic sets dso_local on a function declaration to allow direct
1233 // accesses when taking its address (similar to a data symbol). If the
1234 // function is not defined in the executable, a canonical PLT entry will be
1235 // needed at link time. -fno-direct-access-external-data can avoid the
1236 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1237 // it could just cause trouble without providing perceptible benefits.
1238 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1239 return true;
1242 // If we can use copy relocations we can assume it is local.
1244 // Otherwise don't assume it is local.
1245 return false;
1248 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1249 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1252 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1253 GlobalDecl GD) const {
1254 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1255 // C++ destructors have a few C++ ABI specific special cases.
1256 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1257 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1258 return;
1260 setDLLImportDLLExport(GV, D);
1263 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1264 const NamedDecl *D) const {
1265 if (D && D->isExternallyVisible()) {
1266 if (D->hasAttr<DLLImportAttr>())
1267 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1268 else if ((D->hasAttr<DLLExportAttr>() ||
1269 shouldMapVisibilityToDLLExport(D)) &&
1270 !GV->isDeclarationForLinker())
1271 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1275 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1276 GlobalDecl GD) const {
1277 setDLLImportDLLExport(GV, GD);
1278 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1281 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1282 const NamedDecl *D) const {
1283 setDLLImportDLLExport(GV, D);
1284 setGVPropertiesAux(GV, D);
1287 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1288 const NamedDecl *D) const {
1289 setGlobalVisibility(GV, D);
1290 setDSOLocal(GV);
1291 GV->setPartition(CodeGenOpts.SymbolPartition);
1294 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1295 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1296 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1297 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1298 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1299 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1302 llvm::GlobalVariable::ThreadLocalMode
1303 CodeGenModule::GetDefaultLLVMTLSModel() const {
1304 switch (CodeGenOpts.getDefaultTLSModel()) {
1305 case CodeGenOptions::GeneralDynamicTLSModel:
1306 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1307 case CodeGenOptions::LocalDynamicTLSModel:
1308 return llvm::GlobalVariable::LocalDynamicTLSModel;
1309 case CodeGenOptions::InitialExecTLSModel:
1310 return llvm::GlobalVariable::InitialExecTLSModel;
1311 case CodeGenOptions::LocalExecTLSModel:
1312 return llvm::GlobalVariable::LocalExecTLSModel;
1314 llvm_unreachable("Invalid TLS model!");
1317 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1318 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1320 llvm::GlobalValue::ThreadLocalMode TLM;
1321 TLM = GetDefaultLLVMTLSModel();
1323 // Override the TLS model if it is explicitly specified.
1324 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1325 TLM = GetLLVMTLSModel(Attr->getModel());
1328 GV->setThreadLocalMode(TLM);
1331 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1332 StringRef Name) {
1333 const TargetInfo &Target = CGM.getTarget();
1334 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1337 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1338 const CPUSpecificAttr *Attr,
1339 unsigned CPUIndex,
1340 raw_ostream &Out) {
1341 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1342 // supported.
1343 if (Attr)
1344 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1345 else if (CGM.getTarget().supportsIFunc())
1346 Out << ".resolver";
1349 static void AppendTargetVersionMangling(const CodeGenModule &CGM,
1350 const TargetVersionAttr *Attr,
1351 raw_ostream &Out) {
1352 if (Attr->isDefaultVersion())
1353 return;
1354 Out << "._";
1355 llvm::SmallVector<StringRef, 8> Feats;
1356 Attr->getFeatures(Feats);
1357 for (const auto &Feat : Feats) {
1358 Out << 'M';
1359 Out << Feat;
1363 static void AppendTargetMangling(const CodeGenModule &CGM,
1364 const TargetAttr *Attr, raw_ostream &Out) {
1365 if (Attr->isDefaultVersion())
1366 return;
1368 Out << '.';
1369 const TargetInfo &Target = CGM.getTarget();
1370 ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr());
1371 llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) {
1372 // Multiversioning doesn't allow "no-${feature}", so we can
1373 // only have "+" prefixes here.
1374 assert(LHS.startswith("+") && RHS.startswith("+") &&
1375 "Features should always have a prefix.");
1376 return Target.multiVersionSortPriority(LHS.substr(1)) >
1377 Target.multiVersionSortPriority(RHS.substr(1));
1380 bool IsFirst = true;
1382 if (!Info.CPU.empty()) {
1383 IsFirst = false;
1384 Out << "arch_" << Info.CPU;
1387 for (StringRef Feat : Info.Features) {
1388 if (!IsFirst)
1389 Out << '_';
1390 IsFirst = false;
1391 Out << Feat.substr(1);
1395 // Returns true if GD is a function decl with internal linkage and
1396 // needs a unique suffix after the mangled name.
1397 static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1398 CodeGenModule &CGM) {
1399 const Decl *D = GD.getDecl();
1400 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1401 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1404 static void AppendTargetClonesMangling(const CodeGenModule &CGM,
1405 const TargetClonesAttr *Attr,
1406 unsigned VersionIndex,
1407 raw_ostream &Out) {
1408 if (CGM.getTarget().getTriple().isAArch64()) {
1409 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1410 if (FeatureStr == "default")
1411 return;
1412 Out << "._";
1413 SmallVector<StringRef, 8> Features;
1414 FeatureStr.split(Features, "+");
1415 for (auto &Feat : Features) {
1416 Out << 'M';
1417 Out << Feat;
1419 } else {
1420 Out << '.';
1421 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1422 if (FeatureStr.startswith("arch="))
1423 Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
1424 else
1425 Out << FeatureStr;
1427 Out << '.' << Attr->getMangledIndex(VersionIndex);
1431 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1432 const NamedDecl *ND,
1433 bool OmitMultiVersionMangling = false) {
1434 SmallString<256> Buffer;
1435 llvm::raw_svector_ostream Out(Buffer);
1436 MangleContext &MC = CGM.getCXXABI().getMangleContext();
1437 if (!CGM.getModuleNameHash().empty())
1438 MC.needsUniqueInternalLinkageNames();
1439 bool ShouldMangle = MC.shouldMangleDeclName(ND);
1440 if (ShouldMangle)
1441 MC.mangleName(GD.getWithDecl(ND), Out);
1442 else {
1443 IdentifierInfo *II = ND->getIdentifier();
1444 assert(II && "Attempt to mangle unnamed decl.");
1445 const auto *FD = dyn_cast<FunctionDecl>(ND);
1447 if (FD &&
1448 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1449 Out << "__regcall3__" << II->getName();
1450 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1451 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1452 Out << "__device_stub__" << II->getName();
1453 } else {
1454 Out << II->getName();
1458 // Check if the module name hash should be appended for internal linkage
1459 // symbols. This should come before multi-version target suffixes are
1460 // appended. This is to keep the name and module hash suffix of the
1461 // internal linkage function together. The unique suffix should only be
1462 // added when name mangling is done to make sure that the final name can
1463 // be properly demangled. For example, for C functions without prototypes,
1464 // name mangling is not done and the unique suffix should not be appeneded
1465 // then.
1466 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1467 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1468 "Hash computed when not explicitly requested");
1469 Out << CGM.getModuleNameHash();
1472 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1473 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1474 switch (FD->getMultiVersionKind()) {
1475 case MultiVersionKind::CPUDispatch:
1476 case MultiVersionKind::CPUSpecific:
1477 AppendCPUSpecificCPUDispatchMangling(CGM,
1478 FD->getAttr<CPUSpecificAttr>(),
1479 GD.getMultiVersionIndex(), Out);
1480 break;
1481 case MultiVersionKind::Target:
1482 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1483 break;
1484 case MultiVersionKind::TargetVersion:
1485 AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out);
1486 break;
1487 case MultiVersionKind::TargetClones:
1488 AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
1489 GD.getMultiVersionIndex(), Out);
1490 break;
1491 case MultiVersionKind::None:
1492 llvm_unreachable("None multiversion type isn't valid here");
1496 // Make unique name for device side static file-scope variable for HIP.
1497 if (CGM.getContext().shouldExternalize(ND) &&
1498 CGM.getLangOpts().GPURelocatableDeviceCode &&
1499 CGM.getLangOpts().CUDAIsDevice)
1500 CGM.printPostfixForExternalizedDecl(Out, ND);
1502 return std::string(Out.str());
1505 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1506 const FunctionDecl *FD,
1507 StringRef &CurName) {
1508 if (!FD->isMultiVersion())
1509 return;
1511 // Get the name of what this would be without the 'target' attribute. This
1512 // allows us to lookup the version that was emitted when this wasn't a
1513 // multiversion function.
1514 std::string NonTargetName =
1515 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1516 GlobalDecl OtherGD;
1517 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1518 assert(OtherGD.getCanonicalDecl()
1519 .getDecl()
1520 ->getAsFunction()
1521 ->isMultiVersion() &&
1522 "Other GD should now be a multiversioned function");
1523 // OtherFD is the version of this function that was mangled BEFORE
1524 // becoming a MultiVersion function. It potentially needs to be updated.
1525 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1526 .getDecl()
1527 ->getAsFunction()
1528 ->getMostRecentDecl();
1529 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1530 // This is so that if the initial version was already the 'default'
1531 // version, we don't try to update it.
1532 if (OtherName != NonTargetName) {
1533 // Remove instead of erase, since others may have stored the StringRef
1534 // to this.
1535 const auto ExistingRecord = Manglings.find(NonTargetName);
1536 if (ExistingRecord != std::end(Manglings))
1537 Manglings.remove(&(*ExistingRecord));
1538 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1539 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
1540 Result.first->first();
1541 // If this is the current decl is being created, make sure we update the name.
1542 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
1543 CurName = OtherNameRef;
1544 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1545 Entry->setName(OtherName);
1550 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1551 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1553 // Some ABIs don't have constructor variants. Make sure that base and
1554 // complete constructors get mangled the same.
1555 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1556 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1557 CXXCtorType OrigCtorType = GD.getCtorType();
1558 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1559 if (OrigCtorType == Ctor_Base)
1560 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1564 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1565 // static device variable depends on whether the variable is referenced by
1566 // a host or device host function. Therefore the mangled name cannot be
1567 // cached.
1568 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
1569 auto FoundName = MangledDeclNames.find(CanonicalGD);
1570 if (FoundName != MangledDeclNames.end())
1571 return FoundName->second;
1574 // Keep the first result in the case of a mangling collision.
1575 const auto *ND = cast<NamedDecl>(GD.getDecl());
1576 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1578 // Ensure either we have different ABIs between host and device compilations,
1579 // says host compilation following MSVC ABI but device compilation follows
1580 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1581 // mangling should be the same after name stubbing. The later checking is
1582 // very important as the device kernel name being mangled in host-compilation
1583 // is used to resolve the device binaries to be executed. Inconsistent naming
1584 // result in undefined behavior. Even though we cannot check that naming
1585 // directly between host- and device-compilations, the host- and
1586 // device-mangling in host compilation could help catching certain ones.
1587 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1588 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
1589 (getContext().getAuxTargetInfo() &&
1590 (getContext().getAuxTargetInfo()->getCXXABI() !=
1591 getContext().getTargetInfo().getCXXABI())) ||
1592 getCUDARuntime().getDeviceSideName(ND) ==
1593 getMangledNameImpl(
1594 *this,
1595 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1596 ND));
1598 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1599 return MangledDeclNames[CanonicalGD] = Result.first->first();
1602 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1603 const BlockDecl *BD) {
1604 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1605 const Decl *D = GD.getDecl();
1607 SmallString<256> Buffer;
1608 llvm::raw_svector_ostream Out(Buffer);
1609 if (!D)
1610 MangleCtx.mangleGlobalBlock(BD,
1611 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1612 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1613 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1614 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1615 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1616 else
1617 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1619 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1620 return Result.first->first();
1623 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
1624 auto it = MangledDeclNames.begin();
1625 while (it != MangledDeclNames.end()) {
1626 if (it->second == Name)
1627 return it->first;
1628 it++;
1630 return GlobalDecl();
1633 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1634 return getModule().getNamedValue(Name);
1637 /// AddGlobalCtor - Add a function to the list that will be called before
1638 /// main() runs.
1639 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1640 unsigned LexOrder,
1641 llvm::Constant *AssociatedData) {
1642 // FIXME: Type coercion of void()* types.
1643 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
1646 /// AddGlobalDtor - Add a function to the list that will be called
1647 /// when the module is unloaded.
1648 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1649 bool IsDtorAttrFunc) {
1650 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1651 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
1652 DtorsUsingAtExit[Priority].push_back(Dtor);
1653 return;
1656 // FIXME: Type coercion of void()* types.
1657 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
1660 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1661 if (Fns.empty()) return;
1663 // Ctor function type is void()*.
1664 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1665 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1666 TheModule.getDataLayout().getProgramAddressSpace());
1668 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1669 llvm::StructType *CtorStructTy = llvm::StructType::get(
1670 Int32Ty, CtorPFTy, VoidPtrTy);
1672 // Construct the constructor and destructor arrays.
1673 ConstantInitBuilder builder(*this);
1674 auto ctors = builder.beginArray(CtorStructTy);
1675 for (const auto &I : Fns) {
1676 auto ctor = ctors.beginStruct(CtorStructTy);
1677 ctor.addInt(Int32Ty, I.Priority);
1678 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1679 if (I.AssociatedData)
1680 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1681 else
1682 ctor.addNullPointer(VoidPtrTy);
1683 ctor.finishAndAddTo(ctors);
1686 auto list =
1687 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1688 /*constant*/ false,
1689 llvm::GlobalValue::AppendingLinkage);
1691 // The LTO linker doesn't seem to like it when we set an alignment
1692 // on appending variables. Take it off as a workaround.
1693 list->setAlignment(std::nullopt);
1695 Fns.clear();
1698 llvm::GlobalValue::LinkageTypes
1699 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1700 const auto *D = cast<FunctionDecl>(GD.getDecl());
1702 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1704 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1705 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1707 if (isa<CXXConstructorDecl>(D) &&
1708 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1709 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1710 // Our approach to inheriting constructors is fundamentally different from
1711 // that used by the MS ABI, so keep our inheriting constructor thunks
1712 // internal rather than trying to pick an unambiguous mangling for them.
1713 return llvm::GlobalValue::InternalLinkage;
1716 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1719 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1720 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1721 if (!MDS) return nullptr;
1723 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1726 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
1727 if (auto *FnType = T->getAs<FunctionProtoType>())
1728 T = getContext().getFunctionType(
1729 FnType->getReturnType(), FnType->getParamTypes(),
1730 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
1732 std::string OutName;
1733 llvm::raw_string_ostream Out(OutName);
1734 getCXXABI().getMangleContext().mangleTypeName(
1735 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
1737 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
1738 Out << ".normalized";
1740 return llvm::ConstantInt::get(Int32Ty,
1741 static_cast<uint32_t>(llvm::xxHash64(OutName)));
1744 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1745 const CGFunctionInfo &Info,
1746 llvm::Function *F, bool IsThunk) {
1747 unsigned CallingConv;
1748 llvm::AttributeList PAL;
1749 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
1750 /*AttrOnCallSite=*/false, IsThunk);
1751 F->setAttributes(PAL);
1752 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1755 static void removeImageAccessQualifier(std::string& TyName) {
1756 std::string ReadOnlyQual("__read_only");
1757 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1758 if (ReadOnlyPos != std::string::npos)
1759 // "+ 1" for the space after access qualifier.
1760 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1761 else {
1762 std::string WriteOnlyQual("__write_only");
1763 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1764 if (WriteOnlyPos != std::string::npos)
1765 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1766 else {
1767 std::string ReadWriteQual("__read_write");
1768 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1769 if (ReadWritePos != std::string::npos)
1770 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1775 // Returns the address space id that should be produced to the
1776 // kernel_arg_addr_space metadata. This is always fixed to the ids
1777 // as specified in the SPIR 2.0 specification in order to differentiate
1778 // for example in clGetKernelArgInfo() implementation between the address
1779 // spaces with targets without unique mapping to the OpenCL address spaces
1780 // (basically all single AS CPUs).
1781 static unsigned ArgInfoAddressSpace(LangAS AS) {
1782 switch (AS) {
1783 case LangAS::opencl_global:
1784 return 1;
1785 case LangAS::opencl_constant:
1786 return 2;
1787 case LangAS::opencl_local:
1788 return 3;
1789 case LangAS::opencl_generic:
1790 return 4; // Not in SPIR 2.0 specs.
1791 case LangAS::opencl_global_device:
1792 return 5;
1793 case LangAS::opencl_global_host:
1794 return 6;
1795 default:
1796 return 0; // Assume private.
1800 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
1801 const FunctionDecl *FD,
1802 CodeGenFunction *CGF) {
1803 assert(((FD && CGF) || (!FD && !CGF)) &&
1804 "Incorrect use - FD and CGF should either be both null or not!");
1805 // Create MDNodes that represent the kernel arg metadata.
1806 // Each MDNode is a list in the form of "key", N number of values which is
1807 // the same number of values as their are kernel arguments.
1809 const PrintingPolicy &Policy = Context.getPrintingPolicy();
1811 // MDNode for the kernel argument address space qualifiers.
1812 SmallVector<llvm::Metadata *, 8> addressQuals;
1814 // MDNode for the kernel argument access qualifiers (images only).
1815 SmallVector<llvm::Metadata *, 8> accessQuals;
1817 // MDNode for the kernel argument type names.
1818 SmallVector<llvm::Metadata *, 8> argTypeNames;
1820 // MDNode for the kernel argument base type names.
1821 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1823 // MDNode for the kernel argument type qualifiers.
1824 SmallVector<llvm::Metadata *, 8> argTypeQuals;
1826 // MDNode for the kernel argument names.
1827 SmallVector<llvm::Metadata *, 8> argNames;
1829 if (FD && CGF)
1830 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1831 const ParmVarDecl *parm = FD->getParamDecl(i);
1832 // Get argument name.
1833 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1835 if (!getLangOpts().OpenCL)
1836 continue;
1837 QualType ty = parm->getType();
1838 std::string typeQuals;
1840 // Get image and pipe access qualifier:
1841 if (ty->isImageType() || ty->isPipeType()) {
1842 const Decl *PDecl = parm;
1843 if (const auto *TD = ty->getAs<TypedefType>())
1844 PDecl = TD->getDecl();
1845 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1846 if (A && A->isWriteOnly())
1847 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1848 else if (A && A->isReadWrite())
1849 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1850 else
1851 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1852 } else
1853 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1855 auto getTypeSpelling = [&](QualType Ty) {
1856 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
1858 if (Ty.isCanonical()) {
1859 StringRef typeNameRef = typeName;
1860 // Turn "unsigned type" to "utype"
1861 if (typeNameRef.consume_front("unsigned "))
1862 return std::string("u") + typeNameRef.str();
1863 if (typeNameRef.consume_front("signed "))
1864 return typeNameRef.str();
1867 return typeName;
1870 if (ty->isPointerType()) {
1871 QualType pointeeTy = ty->getPointeeType();
1873 // Get address qualifier.
1874 addressQuals.push_back(
1875 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1876 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1878 // Get argument type name.
1879 std::string typeName = getTypeSpelling(pointeeTy) + "*";
1880 std::string baseTypeName =
1881 getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
1882 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1883 argBaseTypeNames.push_back(
1884 llvm::MDString::get(VMContext, baseTypeName));
1886 // Get argument type qualifiers:
1887 if (ty.isRestrictQualified())
1888 typeQuals = "restrict";
1889 if (pointeeTy.isConstQualified() ||
1890 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1891 typeQuals += typeQuals.empty() ? "const" : " const";
1892 if (pointeeTy.isVolatileQualified())
1893 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1894 } else {
1895 uint32_t AddrSpc = 0;
1896 bool isPipe = ty->isPipeType();
1897 if (ty->isImageType() || isPipe)
1898 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1900 addressQuals.push_back(
1901 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1903 // Get argument type name.
1904 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
1905 std::string typeName = getTypeSpelling(ty);
1906 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
1908 // Remove access qualifiers on images
1909 // (as they are inseparable from type in clang implementation,
1910 // but OpenCL spec provides a special query to get access qualifier
1911 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1912 if (ty->isImageType()) {
1913 removeImageAccessQualifier(typeName);
1914 removeImageAccessQualifier(baseTypeName);
1917 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1918 argBaseTypeNames.push_back(
1919 llvm::MDString::get(VMContext, baseTypeName));
1921 if (isPipe)
1922 typeQuals = "pipe";
1924 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1927 if (getLangOpts().OpenCL) {
1928 Fn->setMetadata("kernel_arg_addr_space",
1929 llvm::MDNode::get(VMContext, addressQuals));
1930 Fn->setMetadata("kernel_arg_access_qual",
1931 llvm::MDNode::get(VMContext, accessQuals));
1932 Fn->setMetadata("kernel_arg_type",
1933 llvm::MDNode::get(VMContext, argTypeNames));
1934 Fn->setMetadata("kernel_arg_base_type",
1935 llvm::MDNode::get(VMContext, argBaseTypeNames));
1936 Fn->setMetadata("kernel_arg_type_qual",
1937 llvm::MDNode::get(VMContext, argTypeQuals));
1939 if (getCodeGenOpts().EmitOpenCLArgMetadata ||
1940 getCodeGenOpts().HIPSaveKernelArgName)
1941 Fn->setMetadata("kernel_arg_name",
1942 llvm::MDNode::get(VMContext, argNames));
1945 /// Determines whether the language options require us to model
1946 /// unwind exceptions. We treat -fexceptions as mandating this
1947 /// except under the fragile ObjC ABI with only ObjC exceptions
1948 /// enabled. This means, for example, that C with -fexceptions
1949 /// enables this.
1950 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1951 // If exceptions are completely disabled, obviously this is false.
1952 if (!LangOpts.Exceptions) return false;
1954 // If C++ exceptions are enabled, this is true.
1955 if (LangOpts.CXXExceptions) return true;
1957 // If ObjC exceptions are enabled, this depends on the ABI.
1958 if (LangOpts.ObjCExceptions) {
1959 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1962 return true;
1965 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1966 const CXXMethodDecl *MD) {
1967 // Check that the type metadata can ever actually be used by a call.
1968 if (!CGM.getCodeGenOpts().LTOUnit ||
1969 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1970 return false;
1972 // Only functions whose address can be taken with a member function pointer
1973 // need this sort of type metadata.
1974 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1975 !isa<CXXDestructorDecl>(MD);
1978 std::vector<const CXXRecordDecl *>
1979 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1980 llvm::SetVector<const CXXRecordDecl *> MostBases;
1982 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1983 CollectMostBases = [&](const CXXRecordDecl *RD) {
1984 if (RD->getNumBases() == 0)
1985 MostBases.insert(RD);
1986 for (const CXXBaseSpecifier &B : RD->bases())
1987 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1989 CollectMostBases(RD);
1990 return MostBases.takeVector();
1993 llvm::GlobalVariable *
1994 CodeGenModule::GetOrCreateRTTIProxyGlobalVariable(llvm::Constant *Addr) {
1995 auto It = RTTIProxyMap.find(Addr);
1996 if (It != RTTIProxyMap.end())
1997 return It->second;
1999 auto *FTRTTIProxy = new llvm::GlobalVariable(
2000 TheModule, Addr->getType(),
2001 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Addr,
2002 "__llvm_rtti_proxy");
2003 FTRTTIProxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2005 RTTIProxyMap[Addr] = FTRTTIProxy;
2006 return FTRTTIProxy;
2009 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2010 llvm::Function *F) {
2011 llvm::AttrBuilder B(F->getContext());
2013 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2014 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2016 if (CodeGenOpts.StackClashProtector)
2017 B.addAttribute("probe-stack", "inline-asm");
2019 if (!hasUnwindExceptions(LangOpts))
2020 B.addAttribute(llvm::Attribute::NoUnwind);
2022 if (D && D->hasAttr<NoStackProtectorAttr>())
2023 ; // Do nothing.
2024 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2025 LangOpts.getStackProtector() == LangOptions::SSPOn)
2026 B.addAttribute(llvm::Attribute::StackProtectStrong);
2027 else if (LangOpts.getStackProtector() == LangOptions::SSPOn)
2028 B.addAttribute(llvm::Attribute::StackProtect);
2029 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
2030 B.addAttribute(llvm::Attribute::StackProtectStrong);
2031 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
2032 B.addAttribute(llvm::Attribute::StackProtectReq);
2034 if (!D) {
2035 // If we don't have a declaration to control inlining, the function isn't
2036 // explicitly marked as alwaysinline for semantic reasons, and inlining is
2037 // disabled, mark the function as noinline.
2038 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2039 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2040 B.addAttribute(llvm::Attribute::NoInline);
2042 F->addFnAttrs(B);
2043 return;
2046 // Track whether we need to add the optnone LLVM attribute,
2047 // starting with the default for this optimization level.
2048 bool ShouldAddOptNone =
2049 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2050 // We can't add optnone in the following cases, it won't pass the verifier.
2051 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2052 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2054 // Add optnone, but do so only if the function isn't always_inline.
2055 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2056 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2057 B.addAttribute(llvm::Attribute::OptimizeNone);
2059 // OptimizeNone implies noinline; we should not be inlining such functions.
2060 B.addAttribute(llvm::Attribute::NoInline);
2062 // We still need to handle naked functions even though optnone subsumes
2063 // much of their semantics.
2064 if (D->hasAttr<NakedAttr>())
2065 B.addAttribute(llvm::Attribute::Naked);
2067 // OptimizeNone wins over OptimizeForSize and MinSize.
2068 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2069 F->removeFnAttr(llvm::Attribute::MinSize);
2070 } else if (D->hasAttr<NakedAttr>()) {
2071 // Naked implies noinline: we should not be inlining such functions.
2072 B.addAttribute(llvm::Attribute::Naked);
2073 B.addAttribute(llvm::Attribute::NoInline);
2074 } else if (D->hasAttr<NoDuplicateAttr>()) {
2075 B.addAttribute(llvm::Attribute::NoDuplicate);
2076 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2077 // Add noinline if the function isn't always_inline.
2078 B.addAttribute(llvm::Attribute::NoInline);
2079 } else if (D->hasAttr<AlwaysInlineAttr>() &&
2080 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2081 // (noinline wins over always_inline, and we can't specify both in IR)
2082 B.addAttribute(llvm::Attribute::AlwaysInline);
2083 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2084 // If we're not inlining, then force everything that isn't always_inline to
2085 // carry an explicit noinline attribute.
2086 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2087 B.addAttribute(llvm::Attribute::NoInline);
2088 } else {
2089 // Otherwise, propagate the inline hint attribute and potentially use its
2090 // absence to mark things as noinline.
2091 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2092 // Search function and template pattern redeclarations for inline.
2093 auto CheckForInline = [](const FunctionDecl *FD) {
2094 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2095 return Redecl->isInlineSpecified();
2097 if (any_of(FD->redecls(), CheckRedeclForInline))
2098 return true;
2099 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2100 if (!Pattern)
2101 return false;
2102 return any_of(Pattern->redecls(), CheckRedeclForInline);
2104 if (CheckForInline(FD)) {
2105 B.addAttribute(llvm::Attribute::InlineHint);
2106 } else if (CodeGenOpts.getInlining() ==
2107 CodeGenOptions::OnlyHintInlining &&
2108 !FD->isInlined() &&
2109 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2110 B.addAttribute(llvm::Attribute::NoInline);
2115 // Add other optimization related attributes if we are optimizing this
2116 // function.
2117 if (!D->hasAttr<OptimizeNoneAttr>()) {
2118 if (D->hasAttr<ColdAttr>()) {
2119 if (!ShouldAddOptNone)
2120 B.addAttribute(llvm::Attribute::OptimizeForSize);
2121 B.addAttribute(llvm::Attribute::Cold);
2123 if (D->hasAttr<HotAttr>())
2124 B.addAttribute(llvm::Attribute::Hot);
2125 if (D->hasAttr<MinSizeAttr>())
2126 B.addAttribute(llvm::Attribute::MinSize);
2129 F->addFnAttrs(B);
2131 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2132 if (alignment)
2133 F->setAlignment(llvm::Align(alignment));
2135 if (!D->hasAttr<AlignedAttr>())
2136 if (LangOpts.FunctionAlignment)
2137 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2139 // Some C++ ABIs require 2-byte alignment for member functions, in order to
2140 // reserve a bit for differentiating between virtual and non-virtual member
2141 // functions. If the current target's C++ ABI requires this and this is a
2142 // member function, set its alignment accordingly.
2143 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2144 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
2145 F->setAlignment(llvm::Align(2));
2148 // In the cross-dso CFI mode with canonical jump tables, we want !type
2149 // attributes on definitions only.
2150 if (CodeGenOpts.SanitizeCfiCrossDso &&
2151 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2152 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2153 // Skip available_externally functions. They won't be codegen'ed in the
2154 // current module anyway.
2155 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2156 CreateFunctionTypeMetadataForIcall(FD, F);
2160 // Emit type metadata on member functions for member function pointer checks.
2161 // These are only ever necessary on definitions; we're guaranteed that the
2162 // definition will be present in the LTO unit as a result of LTO visibility.
2163 auto *MD = dyn_cast<CXXMethodDecl>(D);
2164 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2165 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2166 llvm::Metadata *Id =
2167 CreateMetadataIdentifierForType(Context.getMemberPointerType(
2168 MD->getType(), Context.getRecordType(Base).getTypePtr()));
2169 F->addTypeMetadata(0, Id);
2174 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
2175 llvm::Function *F) {
2176 if (D->hasAttr<StrictFPAttr>()) {
2177 llvm::AttrBuilder FuncAttrs(F->getContext());
2178 FuncAttrs.addAttribute("strictfp");
2179 F->addFnAttrs(FuncAttrs);
2183 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2184 const Decl *D = GD.getDecl();
2185 if (isa_and_nonnull<NamedDecl>(D))
2186 setGVProperties(GV, GD);
2187 else
2188 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2190 if (D && D->hasAttr<UsedAttr>())
2191 addUsedOrCompilerUsedGlobal(GV);
2193 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
2194 const auto *VD = cast<VarDecl>(D);
2195 if (VD->getType().isConstQualified() &&
2196 VD->getStorageDuration() == SD_Static)
2197 addUsedOrCompilerUsedGlobal(GV);
2201 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2202 llvm::AttrBuilder &Attrs) {
2203 // Add target-cpu and target-features attributes to functions. If
2204 // we have a decl for the function and it has a target attribute then
2205 // parse that and add it to the feature set.
2206 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2207 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2208 std::vector<std::string> Features;
2209 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2210 FD = FD ? FD->getMostRecentDecl() : FD;
2211 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2212 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2213 assert((!TD || !TV) && "both target_version and target specified");
2214 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2215 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2216 bool AddedAttr = false;
2217 if (TD || TV || SD || TC) {
2218 llvm::StringMap<bool> FeatureMap;
2219 getContext().getFunctionFeatureMap(FeatureMap, GD);
2221 // Produce the canonical string for this set of features.
2222 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2223 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2225 // Now add the target-cpu and target-features to the function.
2226 // While we populated the feature map above, we still need to
2227 // get and parse the target attribute so we can get the cpu for
2228 // the function.
2229 if (TD) {
2230 ParsedTargetAttr ParsedAttr =
2231 Target.parseTargetAttr(TD->getFeaturesStr());
2232 if (!ParsedAttr.CPU.empty() &&
2233 getTarget().isValidCPUName(ParsedAttr.CPU)) {
2234 TargetCPU = ParsedAttr.CPU;
2235 TuneCPU = ""; // Clear the tune CPU.
2237 if (!ParsedAttr.Tune.empty() &&
2238 getTarget().isValidCPUName(ParsedAttr.Tune))
2239 TuneCPU = ParsedAttr.Tune;
2242 if (SD) {
2243 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2244 // favor this processor.
2245 TuneCPU = getTarget().getCPUSpecificTuneName(
2246 SD->getCPUName(GD.getMultiVersionIndex())->getName());
2248 } else {
2249 // Otherwise just add the existing target cpu and target features to the
2250 // function.
2251 Features = getTarget().getTargetOpts().Features;
2254 if (!TargetCPU.empty()) {
2255 Attrs.addAttribute("target-cpu", TargetCPU);
2256 AddedAttr = true;
2258 if (!TuneCPU.empty()) {
2259 Attrs.addAttribute("tune-cpu", TuneCPU);
2260 AddedAttr = true;
2262 if (!Features.empty()) {
2263 llvm::sort(Features);
2264 Attrs.addAttribute("target-features", llvm::join(Features, ","));
2265 AddedAttr = true;
2268 return AddedAttr;
2271 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2272 llvm::GlobalObject *GO) {
2273 const Decl *D = GD.getDecl();
2274 SetCommonAttributes(GD, GO);
2276 if (D) {
2277 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2278 if (D->hasAttr<RetainAttr>())
2279 addUsedGlobal(GV);
2280 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2281 GV->addAttribute("bss-section", SA->getName());
2282 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2283 GV->addAttribute("data-section", SA->getName());
2284 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2285 GV->addAttribute("rodata-section", SA->getName());
2286 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2287 GV->addAttribute("relro-section", SA->getName());
2290 if (auto *F = dyn_cast<llvm::Function>(GO)) {
2291 if (D->hasAttr<RetainAttr>())
2292 addUsedGlobal(F);
2293 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2294 if (!D->getAttr<SectionAttr>())
2295 F->addFnAttr("implicit-section-name", SA->getName());
2297 llvm::AttrBuilder Attrs(F->getContext());
2298 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2299 // We know that GetCPUAndFeaturesAttributes will always have the
2300 // newest set, since it has the newest possible FunctionDecl, so the
2301 // new ones should replace the old.
2302 llvm::AttributeMask RemoveAttrs;
2303 RemoveAttrs.addAttribute("target-cpu");
2304 RemoveAttrs.addAttribute("target-features");
2305 RemoveAttrs.addAttribute("tune-cpu");
2306 F->removeFnAttrs(RemoveAttrs);
2307 F->addFnAttrs(Attrs);
2311 if (const auto *CSA = D->getAttr<CodeSegAttr>())
2312 GO->setSection(CSA->getName());
2313 else if (const auto *SA = D->getAttr<SectionAttr>())
2314 GO->setSection(SA->getName());
2317 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2320 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2321 llvm::Function *F,
2322 const CGFunctionInfo &FI) {
2323 const Decl *D = GD.getDecl();
2324 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2325 SetLLVMFunctionAttributesForDefinition(D, F);
2327 F->setLinkage(llvm::Function::InternalLinkage);
2329 setNonAliasAttributes(GD, F);
2332 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2333 // Set linkage and visibility in case we never see a definition.
2334 LinkageInfo LV = ND->getLinkageAndVisibility();
2335 // Don't set internal linkage on declarations.
2336 // "extern_weak" is overloaded in LLVM; we probably should have
2337 // separate linkage types for this.
2338 if (isExternallyVisible(LV.getLinkage()) &&
2339 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2340 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2343 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2344 llvm::Function *F) {
2345 // Only if we are checking indirect calls.
2346 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2347 return;
2349 // Non-static class methods are handled via vtable or member function pointer
2350 // checks elsewhere.
2351 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2352 return;
2354 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2355 F->addTypeMetadata(0, MD);
2356 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2358 // Emit a hash-based bit set entry for cross-DSO calls.
2359 if (CodeGenOpts.SanitizeCfiCrossDso)
2360 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2361 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2364 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2365 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2366 return;
2368 llvm::LLVMContext &Ctx = F->getContext();
2369 llvm::MDBuilder MDB(Ctx);
2370 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2371 llvm::MDNode::get(
2372 Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2375 static bool allowKCFIIdentifier(StringRef Name) {
2376 // KCFI type identifier constants are only necessary for external assembly
2377 // functions, which means it's safe to skip unusual names. Subset of
2378 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2379 return llvm::all_of(Name, [](const char &C) {
2380 return llvm::isAlnum(C) || C == '_' || C == '.';
2384 void CodeGenModule::finalizeKCFITypes() {
2385 llvm::Module &M = getModule();
2386 for (auto &F : M.functions()) {
2387 // Remove KCFI type metadata from non-address-taken local functions.
2388 bool AddressTaken = F.hasAddressTaken();
2389 if (!AddressTaken && F.hasLocalLinkage())
2390 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2392 // Generate a constant with the expected KCFI type identifier for all
2393 // address-taken function declarations to support annotating indirectly
2394 // called assembly functions.
2395 if (!AddressTaken || !F.isDeclaration())
2396 continue;
2398 const llvm::ConstantInt *Type;
2399 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2400 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2401 else
2402 continue;
2404 StringRef Name = F.getName();
2405 if (!allowKCFIIdentifier(Name))
2406 continue;
2408 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2409 Name + ", " + Twine(Type->getZExtValue()) + "\n")
2410 .str();
2411 M.appendModuleInlineAsm(Asm);
2415 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2416 bool IsIncompleteFunction,
2417 bool IsThunk) {
2419 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2420 // If this is an intrinsic function, set the function's attributes
2421 // to the intrinsic's attributes.
2422 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2423 return;
2426 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2428 if (!IsIncompleteFunction)
2429 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2430 IsThunk);
2432 // Add the Returned attribute for "this", except for iOS 5 and earlier
2433 // where substantial code, including the libstdc++ dylib, was compiled with
2434 // GCC and does not actually return "this".
2435 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2436 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2437 assert(!F->arg_empty() &&
2438 F->arg_begin()->getType()
2439 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2440 "unexpected this return");
2441 F->addParamAttr(0, llvm::Attribute::Returned);
2444 // Only a few attributes are set on declarations; these may later be
2445 // overridden by a definition.
2447 setLinkageForGV(F, FD);
2448 setGVProperties(F, FD);
2450 // Setup target-specific attributes.
2451 if (!IsIncompleteFunction && F->isDeclaration())
2452 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2454 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2455 F->setSection(CSA->getName());
2456 else if (const auto *SA = FD->getAttr<SectionAttr>())
2457 F->setSection(SA->getName());
2459 if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2460 if (EA->isError())
2461 F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2462 else if (EA->isWarning())
2463 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2466 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2467 if (FD->isInlineBuiltinDeclaration()) {
2468 const FunctionDecl *FDBody;
2469 bool HasBody = FD->hasBody(FDBody);
2470 (void)HasBody;
2471 assert(HasBody && "Inline builtin declarations should always have an "
2472 "available body!");
2473 if (shouldEmitFunction(FDBody))
2474 F->addFnAttr(llvm::Attribute::NoBuiltin);
2477 if (FD->isReplaceableGlobalAllocationFunction()) {
2478 // A replaceable global allocation function does not act like a builtin by
2479 // default, only if it is invoked by a new-expression or delete-expression.
2480 F->addFnAttr(llvm::Attribute::NoBuiltin);
2483 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2484 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2485 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2486 if (MD->isVirtual())
2487 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2489 // Don't emit entries for function declarations in the cross-DSO mode. This
2490 // is handled with better precision by the receiving DSO. But if jump tables
2491 // are non-canonical then we need type metadata in order to produce the local
2492 // jump table.
2493 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2494 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2495 CreateFunctionTypeMetadataForIcall(FD, F);
2497 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2498 setKCFIType(FD, F);
2500 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2501 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2503 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2504 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2506 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2507 // Annotate the callback behavior as metadata:
2508 // - The callback callee (as argument number).
2509 // - The callback payloads (as argument numbers).
2510 llvm::LLVMContext &Ctx = F->getContext();
2511 llvm::MDBuilder MDB(Ctx);
2513 // The payload indices are all but the first one in the encoding. The first
2514 // identifies the callback callee.
2515 int CalleeIdx = *CB->encoding_begin();
2516 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2517 F->addMetadata(llvm::LLVMContext::MD_callback,
2518 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2519 CalleeIdx, PayloadIndices,
2520 /* VarArgsArePassed */ false)}));
2524 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2525 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2526 "Only globals with definition can force usage.");
2527 LLVMUsed.emplace_back(GV);
2530 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2531 assert(!GV->isDeclaration() &&
2532 "Only globals with definition can force usage.");
2533 LLVMCompilerUsed.emplace_back(GV);
2536 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2537 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2538 "Only globals with definition can force usage.");
2539 if (getTriple().isOSBinFormatELF())
2540 LLVMCompilerUsed.emplace_back(GV);
2541 else
2542 LLVMUsed.emplace_back(GV);
2545 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2546 std::vector<llvm::WeakTrackingVH> &List) {
2547 // Don't create llvm.used if there is no need.
2548 if (List.empty())
2549 return;
2551 // Convert List to what ConstantArray needs.
2552 SmallVector<llvm::Constant*, 8> UsedArray;
2553 UsedArray.resize(List.size());
2554 for (unsigned i = 0, e = List.size(); i != e; ++i) {
2555 UsedArray[i] =
2556 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2557 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2560 if (UsedArray.empty())
2561 return;
2562 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2564 auto *GV = new llvm::GlobalVariable(
2565 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2566 llvm::ConstantArray::get(ATy, UsedArray), Name);
2568 GV->setSection("llvm.metadata");
2571 void CodeGenModule::emitLLVMUsed() {
2572 emitUsed(*this, "llvm.used", LLVMUsed);
2573 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2576 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2577 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2578 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2581 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2582 llvm::SmallString<32> Opt;
2583 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2584 if (Opt.empty())
2585 return;
2586 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2587 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2590 void CodeGenModule::AddDependentLib(StringRef Lib) {
2591 auto &C = getLLVMContext();
2592 if (getTarget().getTriple().isOSBinFormatELF()) {
2593 ELFDependentLibraries.push_back(
2594 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2595 return;
2598 llvm::SmallString<24> Opt;
2599 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2600 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2601 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2604 /// Add link options implied by the given module, including modules
2605 /// it depends on, using a postorder walk.
2606 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2607 SmallVectorImpl<llvm::MDNode *> &Metadata,
2608 llvm::SmallPtrSet<Module *, 16> &Visited) {
2609 // Import this module's parent.
2610 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2611 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2614 // Import this module's dependencies.
2615 for (Module *Import : llvm::reverse(Mod->Imports)) {
2616 if (Visited.insert(Import).second)
2617 addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
2620 // Add linker options to link against the libraries/frameworks
2621 // described by this module.
2622 llvm::LLVMContext &Context = CGM.getLLVMContext();
2623 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2625 // For modules that use export_as for linking, use that module
2626 // name instead.
2627 if (Mod->UseExportAsModuleLinkName)
2628 return;
2630 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
2631 // Link against a framework. Frameworks are currently Darwin only, so we
2632 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2633 if (LL.IsFramework) {
2634 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
2635 llvm::MDString::get(Context, LL.Library)};
2637 Metadata.push_back(llvm::MDNode::get(Context, Args));
2638 continue;
2641 // Link against a library.
2642 if (IsELF) {
2643 llvm::Metadata *Args[2] = {
2644 llvm::MDString::get(Context, "lib"),
2645 llvm::MDString::get(Context, LL.Library),
2647 Metadata.push_back(llvm::MDNode::get(Context, Args));
2648 } else {
2649 llvm::SmallString<24> Opt;
2650 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
2651 auto *OptString = llvm::MDString::get(Context, Opt);
2652 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2657 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
2658 // Emit the initializers in the order that sub-modules appear in the
2659 // source, first Global Module Fragments, if present.
2660 if (auto GMF = Primary->getGlobalModuleFragment()) {
2661 for (Decl *D : getContext().getModuleInitializers(GMF)) {
2662 if (isa<ImportDecl>(D))
2663 continue;
2664 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
2665 EmitTopLevelDecl(D);
2668 // Second any associated with the module, itself.
2669 for (Decl *D : getContext().getModuleInitializers(Primary)) {
2670 // Skip import decls, the inits for those are called explicitly.
2671 if (isa<ImportDecl>(D))
2672 continue;
2673 EmitTopLevelDecl(D);
2675 // Third any associated with the Privat eMOdule Fragment, if present.
2676 if (auto PMF = Primary->getPrivateModuleFragment()) {
2677 for (Decl *D : getContext().getModuleInitializers(PMF)) {
2678 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
2679 EmitTopLevelDecl(D);
2684 void CodeGenModule::EmitModuleLinkOptions() {
2685 // Collect the set of all of the modules we want to visit to emit link
2686 // options, which is essentially the imported modules and all of their
2687 // non-explicit child modules.
2688 llvm::SetVector<clang::Module *> LinkModules;
2689 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2690 SmallVector<clang::Module *, 16> Stack;
2692 // Seed the stack with imported modules.
2693 for (Module *M : ImportedModules) {
2694 // Do not add any link flags when an implementation TU of a module imports
2695 // a header of that same module.
2696 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2697 !getLangOpts().isCompilingModule())
2698 continue;
2699 if (Visited.insert(M).second)
2700 Stack.push_back(M);
2703 // Find all of the modules to import, making a little effort to prune
2704 // non-leaf modules.
2705 while (!Stack.empty()) {
2706 clang::Module *Mod = Stack.pop_back_val();
2708 bool AnyChildren = false;
2710 // Visit the submodules of this module.
2711 for (const auto &SM : Mod->submodules()) {
2712 // Skip explicit children; they need to be explicitly imported to be
2713 // linked against.
2714 if (SM->IsExplicit)
2715 continue;
2717 if (Visited.insert(SM).second) {
2718 Stack.push_back(SM);
2719 AnyChildren = true;
2723 // We didn't find any children, so add this module to the list of
2724 // modules to link against.
2725 if (!AnyChildren) {
2726 LinkModules.insert(Mod);
2730 // Add link options for all of the imported modules in reverse topological
2731 // order. We don't do anything to try to order import link flags with respect
2732 // to linker options inserted by things like #pragma comment().
2733 SmallVector<llvm::MDNode *, 16> MetadataArgs;
2734 Visited.clear();
2735 for (Module *M : LinkModules)
2736 if (Visited.insert(M).second)
2737 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2738 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2739 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2741 // Add the linker options metadata flag.
2742 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2743 for (auto *MD : LinkerOptionsMetadata)
2744 NMD->addOperand(MD);
2747 void CodeGenModule::EmitDeferred() {
2748 // Emit deferred declare target declarations.
2749 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2750 getOpenMPRuntime().emitDeferredTargetDecls();
2752 // Emit code for any potentially referenced deferred decls. Since a
2753 // previously unused static decl may become used during the generation of code
2754 // for a static function, iterate until no changes are made.
2756 if (!DeferredVTables.empty()) {
2757 EmitDeferredVTables();
2759 // Emitting a vtable doesn't directly cause more vtables to
2760 // become deferred, although it can cause functions to be
2761 // emitted that then need those vtables.
2762 assert(DeferredVTables.empty());
2765 // Emit CUDA/HIP static device variables referenced by host code only.
2766 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
2767 // needed for further handling.
2768 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2769 llvm::append_range(DeferredDeclsToEmit,
2770 getContext().CUDADeviceVarODRUsedByHost);
2772 // Stop if we're out of both deferred vtables and deferred declarations.
2773 if (DeferredDeclsToEmit.empty())
2774 return;
2776 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2777 // work, it will not interfere with this.
2778 std::vector<GlobalDecl> CurDeclsToEmit;
2779 CurDeclsToEmit.swap(DeferredDeclsToEmit);
2781 for (GlobalDecl &D : CurDeclsToEmit) {
2782 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2783 // to get GlobalValue with exactly the type we need, not something that
2784 // might had been created for another decl with the same mangled name but
2785 // different type.
2786 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2787 GetAddrOfGlobal(D, ForDefinition));
2789 // In case of different address spaces, we may still get a cast, even with
2790 // IsForDefinition equal to true. Query mangled names table to get
2791 // GlobalValue.
2792 if (!GV)
2793 GV = GetGlobalValue(getMangledName(D));
2795 // Make sure GetGlobalValue returned non-null.
2796 assert(GV);
2798 // Check to see if we've already emitted this. This is necessary
2799 // for a couple of reasons: first, decls can end up in the
2800 // deferred-decls queue multiple times, and second, decls can end
2801 // up with definitions in unusual ways (e.g. by an extern inline
2802 // function acquiring a strong function redefinition). Just
2803 // ignore these cases.
2804 if (!GV->isDeclaration())
2805 continue;
2807 // If this is OpenMP, check if it is legal to emit this global normally.
2808 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2809 continue;
2811 // Otherwise, emit the definition and move on to the next one.
2812 EmitGlobalDefinition(D, GV);
2814 // If we found out that we need to emit more decls, do that recursively.
2815 // This has the advantage that the decls are emitted in a DFS and related
2816 // ones are close together, which is convenient for testing.
2817 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2818 EmitDeferred();
2819 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2824 void CodeGenModule::EmitVTablesOpportunistically() {
2825 // Try to emit external vtables as available_externally if they have emitted
2826 // all inlined virtual functions. It runs after EmitDeferred() and therefore
2827 // is not allowed to create new references to things that need to be emitted
2828 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2830 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2831 && "Only emit opportunistic vtables with optimizations");
2833 for (const CXXRecordDecl *RD : OpportunisticVTables) {
2834 assert(getVTables().isVTableExternal(RD) &&
2835 "This queue should only contain external vtables");
2836 if (getCXXABI().canSpeculativelyEmitVTable(RD))
2837 VTables.GenerateClassData(RD);
2839 OpportunisticVTables.clear();
2842 void CodeGenModule::EmitGlobalAnnotations() {
2843 if (Annotations.empty())
2844 return;
2846 // Create a new global variable for the ConstantStruct in the Module.
2847 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2848 Annotations[0]->getType(), Annotations.size()), Annotations);
2849 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2850 llvm::GlobalValue::AppendingLinkage,
2851 Array, "llvm.global.annotations");
2852 gv->setSection(AnnotationSection);
2855 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2856 llvm::Constant *&AStr = AnnotationStrings[Str];
2857 if (AStr)
2858 return AStr;
2860 // Not found yet, create a new global.
2861 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2862 auto *gv = new llvm::GlobalVariable(
2863 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
2864 ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
2865 ConstGlobalsPtrTy->getAddressSpace());
2866 gv->setSection(AnnotationSection);
2867 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2868 AStr = gv;
2869 return gv;
2872 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2873 SourceManager &SM = getContext().getSourceManager();
2874 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2875 if (PLoc.isValid())
2876 return EmitAnnotationString(PLoc.getFilename());
2877 return EmitAnnotationString(SM.getBufferName(Loc));
2880 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2881 SourceManager &SM = getContext().getSourceManager();
2882 PresumedLoc PLoc = SM.getPresumedLoc(L);
2883 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2884 SM.getExpansionLineNumber(L);
2885 return llvm::ConstantInt::get(Int32Ty, LineNo);
2888 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2889 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2890 if (Exprs.empty())
2891 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
2893 llvm::FoldingSetNodeID ID;
2894 for (Expr *E : Exprs) {
2895 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2897 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2898 if (Lookup)
2899 return Lookup;
2901 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2902 LLVMArgs.reserve(Exprs.size());
2903 ConstantEmitter ConstEmiter(*this);
2904 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2905 const auto *CE = cast<clang::ConstantExpr>(E);
2906 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2907 CE->getType());
2909 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2910 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2911 llvm::GlobalValue::PrivateLinkage, Struct,
2912 ".args");
2913 GV->setSection(AnnotationSection);
2914 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2915 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
2917 Lookup = Bitcasted;
2918 return Bitcasted;
2921 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2922 const AnnotateAttr *AA,
2923 SourceLocation L) {
2924 // Get the globals for file name, annotation, and the line number.
2925 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2926 *UnitGV = EmitAnnotationUnit(L),
2927 *LineNoCst = EmitAnnotationLineNo(L),
2928 *Args = EmitAnnotationArgs(AA);
2930 llvm::Constant *GVInGlobalsAS = GV;
2931 if (GV->getAddressSpace() !=
2932 getDataLayout().getDefaultGlobalsAddressSpace()) {
2933 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
2934 GV, GV->getValueType()->getPointerTo(
2935 getDataLayout().getDefaultGlobalsAddressSpace()));
2938 // Create the ConstantStruct for the global annotation.
2939 llvm::Constant *Fields[] = {
2940 llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
2941 llvm::ConstantExpr::getBitCast(AnnoGV, ConstGlobalsPtrTy),
2942 llvm::ConstantExpr::getBitCast(UnitGV, ConstGlobalsPtrTy),
2943 LineNoCst,
2944 Args,
2946 return llvm::ConstantStruct::getAnon(Fields);
2949 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2950 llvm::GlobalValue *GV) {
2951 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2952 // Get the struct elements for these annotations.
2953 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2954 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2957 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
2958 SourceLocation Loc) const {
2959 const auto &NoSanitizeL = getContext().getNoSanitizeList();
2960 // NoSanitize by function name.
2961 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
2962 return true;
2963 // NoSanitize by location. Check "mainfile" prefix.
2964 auto &SM = Context.getSourceManager();
2965 const FileEntry &MainFile = *SM.getFileEntryForID(SM.getMainFileID());
2966 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
2967 return true;
2969 // Check "src" prefix.
2970 if (Loc.isValid())
2971 return NoSanitizeL.containsLocation(Kind, Loc);
2972 // If location is unknown, this may be a compiler-generated function. Assume
2973 // it's located in the main file.
2974 return NoSanitizeL.containsFile(Kind, MainFile.getName());
2977 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
2978 llvm::GlobalVariable *GV,
2979 SourceLocation Loc, QualType Ty,
2980 StringRef Category) const {
2981 const auto &NoSanitizeL = getContext().getNoSanitizeList();
2982 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
2983 return true;
2984 auto &SM = Context.getSourceManager();
2985 if (NoSanitizeL.containsMainFile(
2986 Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category))
2987 return true;
2988 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
2989 return true;
2991 // Check global type.
2992 if (!Ty.isNull()) {
2993 // Drill down the array types: if global variable of a fixed type is
2994 // not sanitized, we also don't instrument arrays of them.
2995 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2996 Ty = AT->getElementType();
2997 Ty = Ty.getCanonicalType().getUnqualifiedType();
2998 // Only record types (classes, structs etc.) are ignored.
2999 if (Ty->isRecordType()) {
3000 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3001 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3002 return true;
3005 return false;
3008 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3009 StringRef Category) const {
3010 const auto &XRayFilter = getContext().getXRayFilter();
3011 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3012 auto Attr = ImbueAttr::NONE;
3013 if (Loc.isValid())
3014 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3015 if (Attr == ImbueAttr::NONE)
3016 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3017 switch (Attr) {
3018 case ImbueAttr::NONE:
3019 return false;
3020 case ImbueAttr::ALWAYS:
3021 Fn->addFnAttr("function-instrument", "xray-always");
3022 break;
3023 case ImbueAttr::ALWAYS_ARG1:
3024 Fn->addFnAttr("function-instrument", "xray-always");
3025 Fn->addFnAttr("xray-log-args", "1");
3026 break;
3027 case ImbueAttr::NEVER:
3028 Fn->addFnAttr("function-instrument", "xray-never");
3029 break;
3031 return true;
3034 ProfileList::ExclusionType
3035 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3036 SourceLocation Loc) const {
3037 const auto &ProfileList = getContext().getProfileList();
3038 // If the profile list is empty, then instrument everything.
3039 if (ProfileList.isEmpty())
3040 return ProfileList::Allow;
3041 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3042 // First, check the function name.
3043 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3044 return *V;
3045 // Next, check the source location.
3046 if (Loc.isValid())
3047 if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3048 return *V;
3049 // If location is unknown, this may be a compiler-generated function. Assume
3050 // it's located in the main file.
3051 auto &SM = Context.getSourceManager();
3052 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
3053 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3054 return *V;
3055 return ProfileList.getDefault(Kind);
3058 ProfileList::ExclusionType
3059 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3060 SourceLocation Loc) const {
3061 auto V = isFunctionBlockedByProfileList(Fn, Loc);
3062 if (V != ProfileList::Allow)
3063 return V;
3065 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3066 if (NumGroups > 1) {
3067 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3068 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3069 return ProfileList::Skip;
3071 return ProfileList::Allow;
3074 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3075 // Never defer when EmitAllDecls is specified.
3076 if (LangOpts.EmitAllDecls)
3077 return true;
3079 if (CodeGenOpts.KeepStaticConsts) {
3080 const auto *VD = dyn_cast<VarDecl>(Global);
3081 if (VD && VD->getType().isConstQualified() &&
3082 VD->getStorageDuration() == SD_Static)
3083 return true;
3086 return getContext().DeclMustBeEmitted(Global);
3089 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3090 // In OpenMP 5.0 variables and function may be marked as
3091 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3092 // that they must be emitted on the host/device. To be sure we need to have
3093 // seen a declare target with an explicit mentioning of the function, we know
3094 // we have if the level of the declare target attribute is -1. Note that we
3095 // check somewhere else if we should emit this at all.
3096 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3097 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3098 OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3099 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3100 return false;
3103 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3104 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3105 // Implicit template instantiations may change linkage if they are later
3106 // explicitly instantiated, so they should not be emitted eagerly.
3107 return false;
3109 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3110 if (Context.getInlineVariableDefinitionKind(VD) ==
3111 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3112 // A definition of an inline constexpr static data member may change
3113 // linkage later if it's redeclared outside the class.
3114 return false;
3115 if (CXX20ModuleInits && VD->getOwningModule() &&
3116 !VD->getOwningModule()->isModuleMapModule()) {
3117 // For CXX20, module-owned initializers need to be deferred, since it is
3118 // not known at this point if they will be run for the current module or
3119 // as part of the initializer for an imported one.
3120 return false;
3123 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3124 // codegen for global variables, because they may be marked as threadprivate.
3125 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3126 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3127 !isTypeConstant(Global->getType(), false) &&
3128 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3129 return false;
3131 return true;
3134 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3135 StringRef Name = getMangledName(GD);
3137 // The UUID descriptor should be pointer aligned.
3138 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3140 // Look for an existing global.
3141 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3142 return ConstantAddress(GV, GV->getValueType(), Alignment);
3144 ConstantEmitter Emitter(*this);
3145 llvm::Constant *Init;
3147 APValue &V = GD->getAsAPValue();
3148 if (!V.isAbsent()) {
3149 // If possible, emit the APValue version of the initializer. In particular,
3150 // this gets the type of the constant right.
3151 Init = Emitter.emitForInitializer(
3152 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3153 } else {
3154 // As a fallback, directly construct the constant.
3155 // FIXME: This may get padding wrong under esoteric struct layout rules.
3156 // MSVC appears to create a complete type 'struct __s_GUID' that it
3157 // presumably uses to represent these constants.
3158 MSGuidDecl::Parts Parts = GD->getParts();
3159 llvm::Constant *Fields[4] = {
3160 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3161 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3162 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3163 llvm::ConstantDataArray::getRaw(
3164 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3165 Int8Ty)};
3166 Init = llvm::ConstantStruct::getAnon(Fields);
3169 auto *GV = new llvm::GlobalVariable(
3170 getModule(), Init->getType(),
3171 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3172 if (supportsCOMDAT())
3173 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3174 setDSOLocal(GV);
3176 if (!V.isAbsent()) {
3177 Emitter.finalize(GV);
3178 return ConstantAddress(GV, GV->getValueType(), Alignment);
3181 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3182 llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
3183 GV, Ty->getPointerTo(GV->getAddressSpace()));
3184 return ConstantAddress(Addr, Ty, Alignment);
3187 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3188 const UnnamedGlobalConstantDecl *GCD) {
3189 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3191 llvm::GlobalVariable **Entry = nullptr;
3192 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3193 if (*Entry)
3194 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3196 ConstantEmitter Emitter(*this);
3197 llvm::Constant *Init;
3199 const APValue &V = GCD->getValue();
3201 assert(!V.isAbsent());
3202 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3203 GCD->getType());
3205 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3206 /*isConstant=*/true,
3207 llvm::GlobalValue::PrivateLinkage, Init,
3208 ".constant");
3209 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3210 GV->setAlignment(Alignment.getAsAlign());
3212 Emitter.finalize(GV);
3214 *Entry = GV;
3215 return ConstantAddress(GV, GV->getValueType(), Alignment);
3218 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3219 const TemplateParamObjectDecl *TPO) {
3220 StringRef Name = getMangledName(TPO);
3221 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3223 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3224 return ConstantAddress(GV, GV->getValueType(), Alignment);
3226 ConstantEmitter Emitter(*this);
3227 llvm::Constant *Init = Emitter.emitForInitializer(
3228 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3230 if (!Init) {
3231 ErrorUnsupported(TPO, "template parameter object");
3232 return ConstantAddress::invalid();
3235 auto *GV = new llvm::GlobalVariable(
3236 getModule(), Init->getType(),
3237 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3238 if (supportsCOMDAT())
3239 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3240 Emitter.finalize(GV);
3242 return ConstantAddress(GV, GV->getValueType(), Alignment);
3245 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3246 const AliasAttr *AA = VD->getAttr<AliasAttr>();
3247 assert(AA && "No alias?");
3249 CharUnits Alignment = getContext().getDeclAlign(VD);
3250 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3252 // See if there is already something with the target's name in the module.
3253 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3254 if (Entry) {
3255 unsigned AS = getTypes().getTargetAddressSpace(VD->getType());
3256 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
3257 return ConstantAddress(Ptr, DeclTy, Alignment);
3260 llvm::Constant *Aliasee;
3261 if (isa<llvm::FunctionType>(DeclTy))
3262 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3263 GlobalDecl(cast<FunctionDecl>(VD)),
3264 /*ForVTable=*/false);
3265 else
3266 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3267 nullptr);
3269 auto *F = cast<llvm::GlobalValue>(Aliasee);
3270 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3271 WeakRefReferences.insert(F);
3273 return ConstantAddress(Aliasee, DeclTy, Alignment);
3276 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3277 const auto *Global = cast<ValueDecl>(GD.getDecl());
3279 // Weak references don't produce any output by themselves.
3280 if (Global->hasAttr<WeakRefAttr>())
3281 return;
3283 // If this is an alias definition (which otherwise looks like a declaration)
3284 // emit it now.
3285 if (Global->hasAttr<AliasAttr>())
3286 return EmitAliasDefinition(GD);
3288 // IFunc like an alias whose value is resolved at runtime by calling resolver.
3289 if (Global->hasAttr<IFuncAttr>())
3290 return emitIFuncDefinition(GD);
3292 // If this is a cpu_dispatch multiversion function, emit the resolver.
3293 if (Global->hasAttr<CPUDispatchAttr>())
3294 return emitCPUDispatchDefinition(GD);
3296 // If this is CUDA, be selective about which declarations we emit.
3297 if (LangOpts.CUDA) {
3298 if (LangOpts.CUDAIsDevice) {
3299 if (!Global->hasAttr<CUDADeviceAttr>() &&
3300 !Global->hasAttr<CUDAGlobalAttr>() &&
3301 !Global->hasAttr<CUDAConstantAttr>() &&
3302 !Global->hasAttr<CUDASharedAttr>() &&
3303 !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3304 !Global->getType()->isCUDADeviceBuiltinTextureType())
3305 return;
3306 } else {
3307 // We need to emit host-side 'shadows' for all global
3308 // device-side variables because the CUDA runtime needs their
3309 // size and host-side address in order to provide access to
3310 // their device-side incarnations.
3312 // So device-only functions are the only things we skip.
3313 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3314 Global->hasAttr<CUDADeviceAttr>())
3315 return;
3317 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3318 "Expected Variable or Function");
3322 if (LangOpts.OpenMP) {
3323 // If this is OpenMP, check if it is legal to emit this global normally.
3324 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3325 return;
3326 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3327 if (MustBeEmitted(Global))
3328 EmitOMPDeclareReduction(DRD);
3329 return;
3331 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3332 if (MustBeEmitted(Global))
3333 EmitOMPDeclareMapper(DMD);
3334 return;
3338 // Ignore declarations, they will be emitted on their first use.
3339 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3340 // Forward declarations are emitted lazily on first use.
3341 if (!FD->doesThisDeclarationHaveABody()) {
3342 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
3343 return;
3345 StringRef MangledName = getMangledName(GD);
3347 // Compute the function info and LLVM type.
3348 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3349 llvm::Type *Ty = getTypes().GetFunctionType(FI);
3351 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3352 /*DontDefer=*/false);
3353 return;
3355 } else {
3356 const auto *VD = cast<VarDecl>(Global);
3357 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3358 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3359 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3360 if (LangOpts.OpenMP) {
3361 // Emit declaration of the must-be-emitted declare target variable.
3362 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3363 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3364 bool UnifiedMemoryEnabled =
3365 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3366 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3367 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3368 !UnifiedMemoryEnabled) {
3369 (void)GetAddrOfGlobalVar(VD);
3370 } else {
3371 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3372 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3373 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3374 UnifiedMemoryEnabled)) &&
3375 "Link clause or to clause with unified memory expected.");
3376 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3379 return;
3382 // If this declaration may have caused an inline variable definition to
3383 // change linkage, make sure that it's emitted.
3384 if (Context.getInlineVariableDefinitionKind(VD) ==
3385 ASTContext::InlineVariableDefinitionKind::Strong)
3386 GetAddrOfGlobalVar(VD);
3387 return;
3391 // Defer code generation to first use when possible, e.g. if this is an inline
3392 // function. If the global must always be emitted, do it eagerly if possible
3393 // to benefit from cache locality.
3394 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3395 // Emit the definition if it can't be deferred.
3396 EmitGlobalDefinition(GD);
3397 return;
3400 // If we're deferring emission of a C++ variable with an
3401 // initializer, remember the order in which it appeared in the file.
3402 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3403 cast<VarDecl>(Global)->hasInit()) {
3404 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3405 CXXGlobalInits.push_back(nullptr);
3408 StringRef MangledName = getMangledName(GD);
3409 if (GetGlobalValue(MangledName) != nullptr) {
3410 // The value has already been used and should therefore be emitted.
3411 addDeferredDeclToEmit(GD);
3412 } else if (MustBeEmitted(Global)) {
3413 // The value must be emitted, but cannot be emitted eagerly.
3414 assert(!MayBeEmittedEagerly(Global));
3415 addDeferredDeclToEmit(GD);
3416 EmittedDeferredDecls[MangledName] = GD;
3417 } else {
3418 // Otherwise, remember that we saw a deferred decl with this name. The
3419 // first use of the mangled name will cause it to move into
3420 // DeferredDeclsToEmit.
3421 DeferredDecls[MangledName] = GD;
3425 // Check if T is a class type with a destructor that's not dllimport.
3426 static bool HasNonDllImportDtor(QualType T) {
3427 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3428 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3429 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3430 return true;
3432 return false;
3435 namespace {
3436 struct FunctionIsDirectlyRecursive
3437 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3438 const StringRef Name;
3439 const Builtin::Context &BI;
3440 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3441 : Name(N), BI(C) {}
3443 bool VisitCallExpr(const CallExpr *E) {
3444 const FunctionDecl *FD = E->getDirectCallee();
3445 if (!FD)
3446 return false;
3447 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3448 if (Attr && Name == Attr->getLabel())
3449 return true;
3450 unsigned BuiltinID = FD->getBuiltinID();
3451 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3452 return false;
3453 StringRef BuiltinName = BI.getName(BuiltinID);
3454 if (BuiltinName.startswith("__builtin_") &&
3455 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3456 return true;
3458 return false;
3461 bool VisitStmt(const Stmt *S) {
3462 for (const Stmt *Child : S->children())
3463 if (Child && this->Visit(Child))
3464 return true;
3465 return false;
3469 // Make sure we're not referencing non-imported vars or functions.
3470 struct DLLImportFunctionVisitor
3471 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3472 bool SafeToInline = true;
3474 bool shouldVisitImplicitCode() const { return true; }
3476 bool VisitVarDecl(VarDecl *VD) {
3477 if (VD->getTLSKind()) {
3478 // A thread-local variable cannot be imported.
3479 SafeToInline = false;
3480 return SafeToInline;
3483 // A variable definition might imply a destructor call.
3484 if (VD->isThisDeclarationADefinition())
3485 SafeToInline = !HasNonDllImportDtor(VD->getType());
3487 return SafeToInline;
3490 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3491 if (const auto *D = E->getTemporary()->getDestructor())
3492 SafeToInline = D->hasAttr<DLLImportAttr>();
3493 return SafeToInline;
3496 bool VisitDeclRefExpr(DeclRefExpr *E) {
3497 ValueDecl *VD = E->getDecl();
3498 if (isa<FunctionDecl>(VD))
3499 SafeToInline = VD->hasAttr<DLLImportAttr>();
3500 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3501 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3502 return SafeToInline;
3505 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3506 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3507 return SafeToInline;
3510 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3511 CXXMethodDecl *M = E->getMethodDecl();
3512 if (!M) {
3513 // Call through a pointer to member function. This is safe to inline.
3514 SafeToInline = true;
3515 } else {
3516 SafeToInline = M->hasAttr<DLLImportAttr>();
3518 return SafeToInline;
3521 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3522 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3523 return SafeToInline;
3526 bool VisitCXXNewExpr(CXXNewExpr *E) {
3527 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3528 return SafeToInline;
3533 // isTriviallyRecursive - Check if this function calls another
3534 // decl that, because of the asm attribute or the other decl being a builtin,
3535 // ends up pointing to itself.
3536 bool
3537 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3538 StringRef Name;
3539 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3540 // asm labels are a special kind of mangling we have to support.
3541 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3542 if (!Attr)
3543 return false;
3544 Name = Attr->getLabel();
3545 } else {
3546 Name = FD->getName();
3549 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3550 const Stmt *Body = FD->getBody();
3551 return Body ? Walker.Visit(Body) : false;
3554 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3555 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3556 return true;
3557 const auto *F = cast<FunctionDecl>(GD.getDecl());
3558 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3559 return false;
3561 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3562 // Check whether it would be safe to inline this dllimport function.
3563 DLLImportFunctionVisitor Visitor;
3564 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3565 if (!Visitor.SafeToInline)
3566 return false;
3568 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3569 // Implicit destructor invocations aren't captured in the AST, so the
3570 // check above can't see them. Check for them manually here.
3571 for (const Decl *Member : Dtor->getParent()->decls())
3572 if (isa<FieldDecl>(Member))
3573 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3574 return false;
3575 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3576 if (HasNonDllImportDtor(B.getType()))
3577 return false;
3581 // Inline builtins declaration must be emitted. They often are fortified
3582 // functions.
3583 if (F->isInlineBuiltinDeclaration())
3584 return true;
3586 // PR9614. Avoid cases where the source code is lying to us. An available
3587 // externally function should have an equivalent function somewhere else,
3588 // but a function that calls itself through asm label/`__builtin_` trickery is
3589 // clearly not equivalent to the real implementation.
3590 // This happens in glibc's btowc and in some configure checks.
3591 return !isTriviallyRecursive(F);
3594 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3595 return CodeGenOpts.OptimizationLevel > 0;
3598 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3599 llvm::GlobalValue *GV) {
3600 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3602 if (FD->isCPUSpecificMultiVersion()) {
3603 auto *Spec = FD->getAttr<CPUSpecificAttr>();
3604 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3605 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3606 } else if (FD->isTargetClonesMultiVersion()) {
3607 auto *Clone = FD->getAttr<TargetClonesAttr>();
3608 for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
3609 if (Clone->isFirstOfVersion(I))
3610 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3611 // Ensure that the resolver function is also emitted.
3612 GetOrCreateMultiVersionResolver(GD);
3613 } else
3614 EmitGlobalFunctionDefinition(GD, GV);
3617 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3618 const auto *D = cast<ValueDecl>(GD.getDecl());
3620 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3621 Context.getSourceManager(),
3622 "Generating code for declaration");
3624 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3625 // At -O0, don't generate IR for functions with available_externally
3626 // linkage.
3627 if (!shouldEmitFunction(GD))
3628 return;
3630 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3631 std::string Name;
3632 llvm::raw_string_ostream OS(Name);
3633 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3634 /*Qualified=*/true);
3635 return Name;
3638 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3639 // Make sure to emit the definition(s) before we emit the thunks.
3640 // This is necessary for the generation of certain thunks.
3641 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3642 ABI->emitCXXStructor(GD);
3643 else if (FD->isMultiVersion())
3644 EmitMultiVersionFunctionDefinition(GD, GV);
3645 else
3646 EmitGlobalFunctionDefinition(GD, GV);
3648 if (Method->isVirtual())
3649 getVTables().EmitThunks(GD);
3651 return;
3654 if (FD->isMultiVersion())
3655 return EmitMultiVersionFunctionDefinition(GD, GV);
3656 return EmitGlobalFunctionDefinition(GD, GV);
3659 if (const auto *VD = dyn_cast<VarDecl>(D))
3660 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3662 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3665 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3666 llvm::Function *NewFn);
3668 static unsigned
3669 TargetMVPriority(const TargetInfo &TI,
3670 const CodeGenFunction::MultiVersionResolverOption &RO) {
3671 unsigned Priority = 0;
3672 unsigned NumFeatures = 0;
3673 for (StringRef Feat : RO.Conditions.Features) {
3674 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3675 NumFeatures++;
3678 if (!RO.Conditions.Architecture.empty())
3679 Priority = std::max(
3680 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3682 Priority += TI.multiVersionFeatureCost() * NumFeatures;
3684 return Priority;
3687 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
3688 // TU can forward declare the function without causing problems. Particularly
3689 // in the cases of CPUDispatch, this causes issues. This also makes sure we
3690 // work with internal linkage functions, so that the same function name can be
3691 // used with internal linkage in multiple TUs.
3692 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
3693 GlobalDecl GD) {
3694 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3695 if (FD->getFormalLinkage() == InternalLinkage)
3696 return llvm::GlobalValue::InternalLinkage;
3697 return llvm::GlobalValue::WeakODRLinkage;
3700 void CodeGenModule::emitMultiVersionFunctions() {
3701 std::vector<GlobalDecl> MVFuncsToEmit;
3702 MultiVersionFuncs.swap(MVFuncsToEmit);
3703 for (GlobalDecl GD : MVFuncsToEmit) {
3704 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3705 assert(FD && "Expected a FunctionDecl");
3707 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3708 if (FD->isTargetMultiVersion()) {
3709 getContext().forEachMultiversionedFunctionVersion(
3710 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3711 GlobalDecl CurGD{
3712 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3713 StringRef MangledName = getMangledName(CurGD);
3714 llvm::Constant *Func = GetGlobalValue(MangledName);
3715 if (!Func) {
3716 if (CurFD->isDefined()) {
3717 EmitGlobalFunctionDefinition(CurGD, nullptr);
3718 Func = GetGlobalValue(MangledName);
3719 } else {
3720 const CGFunctionInfo &FI =
3721 getTypes().arrangeGlobalDeclaration(GD);
3722 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3723 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3724 /*DontDefer=*/false, ForDefinition);
3726 assert(Func && "This should have just been created");
3728 if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) {
3729 const auto *TA = CurFD->getAttr<TargetAttr>();
3730 llvm::SmallVector<StringRef, 8> Feats;
3731 TA->getAddedFeatures(Feats);
3732 Options.emplace_back(cast<llvm::Function>(Func),
3733 TA->getArchitecture(), Feats);
3734 } else {
3735 const auto *TVA = CurFD->getAttr<TargetVersionAttr>();
3736 llvm::SmallVector<StringRef, 8> Feats;
3737 TVA->getFeatures(Feats);
3738 Options.emplace_back(cast<llvm::Function>(Func),
3739 /*Architecture*/ "", Feats);
3742 } else if (FD->isTargetClonesMultiVersion()) {
3743 const auto *TC = FD->getAttr<TargetClonesAttr>();
3744 for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
3745 ++VersionIndex) {
3746 if (!TC->isFirstOfVersion(VersionIndex))
3747 continue;
3748 GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
3749 VersionIndex};
3750 StringRef Version = TC->getFeatureStr(VersionIndex);
3751 StringRef MangledName = getMangledName(CurGD);
3752 llvm::Constant *Func = GetGlobalValue(MangledName);
3753 if (!Func) {
3754 if (FD->isDefined()) {
3755 EmitGlobalFunctionDefinition(CurGD, nullptr);
3756 Func = GetGlobalValue(MangledName);
3757 } else {
3758 const CGFunctionInfo &FI =
3759 getTypes().arrangeGlobalDeclaration(CurGD);
3760 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3761 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3762 /*DontDefer=*/false, ForDefinition);
3764 assert(Func && "This should have just been created");
3767 StringRef Architecture;
3768 llvm::SmallVector<StringRef, 1> Feature;
3770 if (getTarget().getTriple().isAArch64()) {
3771 if (Version != "default") {
3772 llvm::SmallVector<StringRef, 8> VerFeats;
3773 Version.split(VerFeats, "+");
3774 for (auto &CurFeat : VerFeats)
3775 Feature.push_back(CurFeat.trim());
3777 } else {
3778 if (Version.startswith("arch="))
3779 Architecture = Version.drop_front(sizeof("arch=") - 1);
3780 else if (Version != "default")
3781 Feature.push_back(Version);
3784 Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
3786 } else {
3787 assert(0 && "Expected a target or target_clones multiversion function");
3788 continue;
3791 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
3792 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant))
3793 ResolverConstant = IFunc->getResolver();
3794 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
3796 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3798 if (supportsCOMDAT())
3799 ResolverFunc->setComdat(
3800 getModule().getOrInsertComdat(ResolverFunc->getName()));
3802 const TargetInfo &TI = getTarget();
3803 llvm::stable_sort(
3804 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3805 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3806 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3808 CodeGenFunction CGF(*this);
3809 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3812 // Ensure that any additions to the deferred decls list caused by emitting a
3813 // variant are emitted. This can happen when the variant itself is inline and
3814 // calls a function without linkage.
3815 if (!MVFuncsToEmit.empty())
3816 EmitDeferred();
3818 // Ensure that any additions to the multiversion funcs list from either the
3819 // deferred decls or the multiversion functions themselves are emitted.
3820 if (!MultiVersionFuncs.empty())
3821 emitMultiVersionFunctions();
3824 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3825 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3826 assert(FD && "Not a FunctionDecl?");
3827 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
3828 const auto *DD = FD->getAttr<CPUDispatchAttr>();
3829 assert(DD && "Not a cpu_dispatch Function?");
3831 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3832 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3834 StringRef ResolverName = getMangledName(GD);
3835 UpdateMultiVersionNames(GD, FD, ResolverName);
3837 llvm::Type *ResolverType;
3838 GlobalDecl ResolverGD;
3839 if (getTarget().supportsIFunc()) {
3840 ResolverType = llvm::FunctionType::get(
3841 llvm::PointerType::get(DeclTy,
3842 getTypes().getTargetAddressSpace(FD->getType())),
3843 false);
3845 else {
3846 ResolverType = DeclTy;
3847 ResolverGD = GD;
3850 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3851 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3852 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3853 if (supportsCOMDAT())
3854 ResolverFunc->setComdat(
3855 getModule().getOrInsertComdat(ResolverFunc->getName()));
3857 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3858 const TargetInfo &Target = getTarget();
3859 unsigned Index = 0;
3860 for (const IdentifierInfo *II : DD->cpus()) {
3861 // Get the name of the target function so we can look it up/create it.
3862 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3863 getCPUSpecificMangling(*this, II->getName());
3865 llvm::Constant *Func = GetGlobalValue(MangledName);
3867 if (!Func) {
3868 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3869 if (ExistingDecl.getDecl() &&
3870 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3871 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3872 Func = GetGlobalValue(MangledName);
3873 } else {
3874 if (!ExistingDecl.getDecl())
3875 ExistingDecl = GD.getWithMultiVersionIndex(Index);
3877 Func = GetOrCreateLLVMFunction(
3878 MangledName, DeclTy, ExistingDecl,
3879 /*ForVTable=*/false, /*DontDefer=*/true,
3880 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3884 llvm::SmallVector<StringRef, 32> Features;
3885 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3886 llvm::transform(Features, Features.begin(),
3887 [](StringRef Str) { return Str.substr(1); });
3888 llvm::erase_if(Features, [&Target](StringRef Feat) {
3889 return !Target.validateCpuSupports(Feat);
3891 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3892 ++Index;
3895 llvm::stable_sort(
3896 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3897 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3898 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
3899 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
3902 // If the list contains multiple 'default' versions, such as when it contains
3903 // 'pentium' and 'generic', don't emit the call to the generic one (since we
3904 // always run on at least a 'pentium'). We do this by deleting the 'least
3905 // advanced' (read, lowest mangling letter).
3906 while (Options.size() > 1 &&
3907 llvm::X86::getCpuSupportsMask(
3908 (Options.end() - 2)->Conditions.Features) == 0) {
3909 StringRef LHSName = (Options.end() - 2)->Function->getName();
3910 StringRef RHSName = (Options.end() - 1)->Function->getName();
3911 if (LHSName.compare(RHSName) < 0)
3912 Options.erase(Options.end() - 2);
3913 else
3914 Options.erase(Options.end() - 1);
3917 CodeGenFunction CGF(*this);
3918 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3920 if (getTarget().supportsIFunc()) {
3921 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
3922 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
3924 // Fix up function declarations that were created for cpu_specific before
3925 // cpu_dispatch was known
3926 if (!isa<llvm::GlobalIFunc>(IFunc)) {
3927 assert(cast<llvm::Function>(IFunc)->isDeclaration());
3928 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
3929 &getModule());
3930 GI->takeName(IFunc);
3931 IFunc->replaceAllUsesWith(GI);
3932 IFunc->eraseFromParent();
3933 IFunc = GI;
3936 std::string AliasName = getMangledNameImpl(
3937 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3938 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3939 if (!AliasFunc) {
3940 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
3941 &getModule());
3942 SetCommonAttributes(GD, GA);
3947 /// If a dispatcher for the specified mangled name is not in the module, create
3948 /// and return an llvm Function with the specified type.
3949 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
3950 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3951 assert(FD && "Not a FunctionDecl?");
3953 std::string MangledName =
3954 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3956 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3957 // a separate resolver).
3958 std::string ResolverName = MangledName;
3959 if (getTarget().supportsIFunc())
3960 ResolverName += ".ifunc";
3961 else if (FD->isTargetMultiVersion())
3962 ResolverName += ".resolver";
3964 // If the resolver has already been created, just return it.
3965 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3966 return ResolverGV;
3968 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3969 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3971 // The resolver needs to be created. For target and target_clones, defer
3972 // creation until the end of the TU.
3973 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
3974 MultiVersionFuncs.push_back(GD);
3976 // For cpu_specific, don't create an ifunc yet because we don't know if the
3977 // cpu_dispatch will be emitted in this translation unit.
3978 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
3979 llvm::Type *ResolverType = llvm::FunctionType::get(
3980 llvm::PointerType::get(DeclTy,
3981 getTypes().getTargetAddressSpace(FD->getType())),
3982 false);
3983 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3984 MangledName + ".resolver", ResolverType, GlobalDecl{},
3985 /*ForVTable=*/false);
3986 llvm::GlobalIFunc *GIF =
3987 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
3988 "", Resolver, &getModule());
3989 GIF->setName(ResolverName);
3990 SetCommonAttributes(FD, GIF);
3992 return GIF;
3995 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3996 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3997 assert(isa<llvm::GlobalValue>(Resolver) &&
3998 "Resolver should be created for the first time");
3999 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
4000 return Resolver;
4003 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
4004 /// module, create and return an llvm Function with the specified type. If there
4005 /// is something in the module with the specified name, return it potentially
4006 /// bitcasted to the right type.
4008 /// If D is non-null, it specifies a decl that correspond to this. This is used
4009 /// to set the attributes on the function when it is first created.
4010 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4011 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
4012 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
4013 ForDefinition_t IsForDefinition) {
4014 const Decl *D = GD.getDecl();
4016 // Any attempts to use a MultiVersion function should result in retrieving
4017 // the iFunc instead. Name Mangling will handle the rest of the changes.
4018 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4019 // For the device mark the function as one that should be emitted.
4020 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
4021 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
4022 !DontDefer && !IsForDefinition) {
4023 if (const FunctionDecl *FDDef = FD->getDefinition()) {
4024 GlobalDecl GDDef;
4025 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4026 GDDef = GlobalDecl(CD, GD.getCtorType());
4027 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4028 GDDef = GlobalDecl(DD, GD.getDtorType());
4029 else
4030 GDDef = GlobalDecl(FDDef);
4031 EmitGlobal(GDDef);
4035 if (FD->isMultiVersion()) {
4036 UpdateMultiVersionNames(GD, FD, MangledName);
4037 if (!IsForDefinition)
4038 return GetOrCreateMultiVersionResolver(GD);
4042 // Lookup the entry, lazily creating it if necessary.
4043 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4044 if (Entry) {
4045 if (WeakRefReferences.erase(Entry)) {
4046 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4047 if (FD && !FD->hasAttr<WeakAttr>())
4048 Entry->setLinkage(llvm::Function::ExternalLinkage);
4051 // Handle dropped DLL attributes.
4052 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4053 !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) {
4054 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4055 setDSOLocal(Entry);
4058 // If there are two attempts to define the same mangled name, issue an
4059 // error.
4060 if (IsForDefinition && !Entry->isDeclaration()) {
4061 GlobalDecl OtherGD;
4062 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
4063 // to make sure that we issue an error only once.
4064 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4065 (GD.getCanonicalDecl().getDecl() !=
4066 OtherGD.getCanonicalDecl().getDecl()) &&
4067 DiagnosedConflictingDefinitions.insert(GD).second) {
4068 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4069 << MangledName;
4070 getDiags().Report(OtherGD.getDecl()->getLocation(),
4071 diag::note_previous_definition);
4075 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4076 (Entry->getValueType() == Ty)) {
4077 return Entry;
4080 // Make sure the result is of the correct type.
4081 // (If function is requested for a definition, we always need to create a new
4082 // function, not just return a bitcast.)
4083 if (!IsForDefinition)
4084 return llvm::ConstantExpr::getBitCast(
4085 Entry, Ty->getPointerTo(Entry->getAddressSpace()));
4088 // This function doesn't have a complete type (for example, the return
4089 // type is an incomplete struct). Use a fake type instead, and make
4090 // sure not to try to set attributes.
4091 bool IsIncompleteFunction = false;
4093 llvm::FunctionType *FTy;
4094 if (isa<llvm::FunctionType>(Ty)) {
4095 FTy = cast<llvm::FunctionType>(Ty);
4096 } else {
4097 FTy = llvm::FunctionType::get(VoidTy, false);
4098 IsIncompleteFunction = true;
4101 llvm::Function *F =
4102 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4103 Entry ? StringRef() : MangledName, &getModule());
4105 // If we already created a function with the same mangled name (but different
4106 // type) before, take its name and add it to the list of functions to be
4107 // replaced with F at the end of CodeGen.
4109 // This happens if there is a prototype for a function (e.g. "int f()") and
4110 // then a definition of a different type (e.g. "int f(int x)").
4111 if (Entry) {
4112 F->takeName(Entry);
4114 // This might be an implementation of a function without a prototype, in
4115 // which case, try to do special replacement of calls which match the new
4116 // prototype. The really key thing here is that we also potentially drop
4117 // arguments from the call site so as to make a direct call, which makes the
4118 // inliner happier and suppresses a number of optimizer warnings (!) about
4119 // dropping arguments.
4120 if (!Entry->use_empty()) {
4121 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
4122 Entry->removeDeadConstantUsers();
4125 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
4126 F, Entry->getValueType()->getPointerTo(Entry->getAddressSpace()));
4127 addGlobalValReplacement(Entry, BC);
4130 assert(F->getName() == MangledName && "name was uniqued!");
4131 if (D)
4132 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4133 if (ExtraAttrs.hasFnAttrs()) {
4134 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4135 F->addFnAttrs(B);
4138 if (!DontDefer) {
4139 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4140 // each other bottoming out with the base dtor. Therefore we emit non-base
4141 // dtors on usage, even if there is no dtor definition in the TU.
4142 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
4143 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
4144 GD.getDtorType()))
4145 addDeferredDeclToEmit(GD);
4147 // This is the first use or definition of a mangled name. If there is a
4148 // deferred decl with this name, remember that we need to emit it at the end
4149 // of the file.
4150 auto DDI = DeferredDecls.find(MangledName);
4151 if (DDI != DeferredDecls.end()) {
4152 // Move the potentially referenced deferred decl to the
4153 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4154 // don't need it anymore).
4155 addDeferredDeclToEmit(DDI->second);
4156 EmittedDeferredDecls[DDI->first] = DDI->second;
4157 DeferredDecls.erase(DDI);
4159 // Otherwise, there are cases we have to worry about where we're
4160 // using a declaration for which we must emit a definition but where
4161 // we might not find a top-level definition:
4162 // - member functions defined inline in their classes
4163 // - friend functions defined inline in some class
4164 // - special member functions with implicit definitions
4165 // If we ever change our AST traversal to walk into class methods,
4166 // this will be unnecessary.
4168 // We also don't emit a definition for a function if it's going to be an
4169 // entry in a vtable, unless it's already marked as used.
4170 } else if (getLangOpts().CPlusPlus && D) {
4171 // Look for a declaration that's lexically in a record.
4172 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4173 FD = FD->getPreviousDecl()) {
4174 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
4175 if (FD->doesThisDeclarationHaveABody()) {
4176 addDeferredDeclToEmit(GD.getWithDecl(FD));
4177 break;
4184 // Make sure the result is of the requested type.
4185 if (!IsIncompleteFunction) {
4186 assert(F->getFunctionType() == Ty);
4187 return F;
4190 return llvm::ConstantExpr::getBitCast(F,
4191 Ty->getPointerTo(F->getAddressSpace()));
4194 /// GetAddrOfFunction - Return the address of the given function. If Ty is
4195 /// non-null, then this function will use the specified type if it has to
4196 /// create it (this occurs when we see a definition of the function).
4197 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
4198 llvm::Type *Ty,
4199 bool ForVTable,
4200 bool DontDefer,
4201 ForDefinition_t IsForDefinition) {
4202 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
4203 "consteval function should never be emitted");
4204 // If there was no specific requested type, just convert it now.
4205 if (!Ty) {
4206 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4207 Ty = getTypes().ConvertType(FD->getType());
4210 // Devirtualized destructor calls may come through here instead of via
4211 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4212 // of the complete destructor when necessary.
4213 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
4214 if (getTarget().getCXXABI().isMicrosoft() &&
4215 GD.getDtorType() == Dtor_Complete &&
4216 DD->getParent()->getNumVBases() == 0)
4217 GD = GlobalDecl(DD, Dtor_Base);
4220 StringRef MangledName = getMangledName(GD);
4221 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4222 /*IsThunk=*/false, llvm::AttributeList(),
4223 IsForDefinition);
4224 // Returns kernel handle for HIP kernel stub function.
4225 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4226 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4227 auto *Handle = getCUDARuntime().getKernelHandle(
4228 cast<llvm::Function>(F->stripPointerCasts()), GD);
4229 if (IsForDefinition)
4230 return F;
4231 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
4233 return F;
4236 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
4237 llvm::GlobalValue *F =
4238 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4240 return llvm::ConstantExpr::getBitCast(
4241 llvm::NoCFIValue::get(F),
4242 llvm::Type::getInt8PtrTy(VMContext, F->getAddressSpace()));
4245 static const FunctionDecl *
4246 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
4247 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4248 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4250 IdentifierInfo &CII = C.Idents.get(Name);
4251 for (const auto *Result : DC->lookup(&CII))
4252 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4253 return FD;
4255 if (!C.getLangOpts().CPlusPlus)
4256 return nullptr;
4258 // Demangle the premangled name from getTerminateFn()
4259 IdentifierInfo &CXXII =
4260 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4261 ? C.Idents.get("terminate")
4262 : C.Idents.get(Name);
4264 for (const auto &N : {"__cxxabiv1", "std"}) {
4265 IdentifierInfo &NS = C.Idents.get(N);
4266 for (const auto *Result : DC->lookup(&NS)) {
4267 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4268 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4269 for (const auto *Result : LSD->lookup(&NS))
4270 if ((ND = dyn_cast<NamespaceDecl>(Result)))
4271 break;
4273 if (ND)
4274 for (const auto *Result : ND->lookup(&CXXII))
4275 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4276 return FD;
4280 return nullptr;
4283 /// CreateRuntimeFunction - Create a new runtime function with the specified
4284 /// type and name.
4285 llvm::FunctionCallee
4286 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4287 llvm::AttributeList ExtraAttrs, bool Local,
4288 bool AssumeConvergent) {
4289 if (AssumeConvergent) {
4290 ExtraAttrs =
4291 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4294 llvm::Constant *C =
4295 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4296 /*DontDefer=*/false, /*IsThunk=*/false,
4297 ExtraAttrs);
4299 if (auto *F = dyn_cast<llvm::Function>(C)) {
4300 if (F->empty()) {
4301 F->setCallingConv(getRuntimeCC());
4303 // In Windows Itanium environments, try to mark runtime functions
4304 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4305 // will link their standard library statically or dynamically. Marking
4306 // functions imported when they are not imported can cause linker errors
4307 // and warnings.
4308 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4309 !getCodeGenOpts().LTOVisibilityPublicStd) {
4310 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4311 if (!FD || FD->hasAttr<DLLImportAttr>()) {
4312 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4313 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4316 setDSOLocal(F);
4320 return {FTy, C};
4323 /// isTypeConstant - Determine whether an object of this type can be emitted
4324 /// as a constant.
4326 /// If ExcludeCtor is true, the duration when the object's constructor runs
4327 /// will not be considered. The caller will need to verify that the object is
4328 /// not written to during its construction.
4329 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
4330 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
4331 return false;
4333 if (Context.getLangOpts().CPlusPlus) {
4334 if (const CXXRecordDecl *Record
4335 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
4336 return ExcludeCtor && !Record->hasMutableFields() &&
4337 Record->hasTrivialDestructor();
4340 return true;
4343 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4344 /// create and return an llvm GlobalVariable with the specified type and address
4345 /// space. If there is something in the module with the specified name, return
4346 /// it potentially bitcasted to the right type.
4348 /// If D is non-null, it specifies a decl that correspond to this. This is used
4349 /// to set the attributes on the global when it is first created.
4351 /// If IsForDefinition is true, it is guaranteed that an actual global with
4352 /// type Ty will be returned, not conversion of a variable with the same
4353 /// mangled name but some other type.
4354 llvm::Constant *
4355 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4356 LangAS AddrSpace, const VarDecl *D,
4357 ForDefinition_t IsForDefinition) {
4358 // Lookup the entry, lazily creating it if necessary.
4359 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4360 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4361 if (Entry) {
4362 if (WeakRefReferences.erase(Entry)) {
4363 if (D && !D->hasAttr<WeakAttr>())
4364 Entry->setLinkage(llvm::Function::ExternalLinkage);
4367 // Handle dropped DLL attributes.
4368 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4369 !shouldMapVisibilityToDLLExport(D))
4370 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4372 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4373 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4375 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4376 return Entry;
4378 // If there are two attempts to define the same mangled name, issue an
4379 // error.
4380 if (IsForDefinition && !Entry->isDeclaration()) {
4381 GlobalDecl OtherGD;
4382 const VarDecl *OtherD;
4384 // Check that D is not yet in DiagnosedConflictingDefinitions is required
4385 // to make sure that we issue an error only once.
4386 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4387 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4388 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4389 OtherD->hasInit() &&
4390 DiagnosedConflictingDefinitions.insert(D).second) {
4391 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4392 << MangledName;
4393 getDiags().Report(OtherGD.getDecl()->getLocation(),
4394 diag::note_previous_definition);
4398 // Make sure the result is of the correct type.
4399 if (Entry->getType()->getAddressSpace() != TargetAS) {
4400 return llvm::ConstantExpr::getAddrSpaceCast(Entry,
4401 Ty->getPointerTo(TargetAS));
4404 // (If global is requested for a definition, we always need to create a new
4405 // global, not just return a bitcast.)
4406 if (!IsForDefinition)
4407 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
4410 auto DAddrSpace = GetGlobalVarAddressSpace(D);
4412 auto *GV = new llvm::GlobalVariable(
4413 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4414 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4415 getContext().getTargetAddressSpace(DAddrSpace));
4417 // If we already created a global with the same mangled name (but different
4418 // type) before, take its name and remove it from its parent.
4419 if (Entry) {
4420 GV->takeName(Entry);
4422 if (!Entry->use_empty()) {
4423 llvm::Constant *NewPtrForOldDecl =
4424 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4425 Entry->replaceAllUsesWith(NewPtrForOldDecl);
4428 Entry->eraseFromParent();
4431 // This is the first use or definition of a mangled name. If there is a
4432 // deferred decl with this name, remember that we need to emit it at the end
4433 // of the file.
4434 auto DDI = DeferredDecls.find(MangledName);
4435 if (DDI != DeferredDecls.end()) {
4436 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4437 // list, and remove it from DeferredDecls (since we don't need it anymore).
4438 addDeferredDeclToEmit(DDI->second);
4439 EmittedDeferredDecls[DDI->first] = DDI->second;
4440 DeferredDecls.erase(DDI);
4443 // Handle things which are present even on external declarations.
4444 if (D) {
4445 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4446 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4448 // FIXME: This code is overly simple and should be merged with other global
4449 // handling.
4450 GV->setConstant(isTypeConstant(D->getType(), false));
4452 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4454 setLinkageForGV(GV, D);
4456 if (D->getTLSKind()) {
4457 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4458 CXXThreadLocals.push_back(D);
4459 setTLSMode(GV, *D);
4462 setGVProperties(GV, D);
4464 // If required by the ABI, treat declarations of static data members with
4465 // inline initializers as definitions.
4466 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
4467 EmitGlobalVarDefinition(D);
4470 // Emit section information for extern variables.
4471 if (D->hasExternalStorage()) {
4472 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4473 GV->setSection(SA->getName());
4476 // Handle XCore specific ABI requirements.
4477 if (getTriple().getArch() == llvm::Triple::xcore &&
4478 D->getLanguageLinkage() == CLanguageLinkage &&
4479 D->getType().isConstant(Context) &&
4480 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
4481 GV->setSection(".cp.rodata");
4483 // Check if we a have a const declaration with an initializer, we may be
4484 // able to emit it as available_externally to expose it's value to the
4485 // optimizer.
4486 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4487 D->getType().isConstQualified() && !GV->hasInitializer() &&
4488 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
4489 const auto *Record =
4490 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
4491 bool HasMutableFields = Record && Record->hasMutableFields();
4492 if (!HasMutableFields) {
4493 const VarDecl *InitDecl;
4494 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4495 if (InitExpr) {
4496 ConstantEmitter emitter(*this);
4497 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
4498 if (Init) {
4499 auto *InitType = Init->getType();
4500 if (GV->getValueType() != InitType) {
4501 // The type of the initializer does not match the definition.
4502 // This happens when an initializer has a different type from
4503 // the type of the global (because of padding at the end of a
4504 // structure for instance).
4505 GV->setName(StringRef());
4506 // Make a new global with the correct type, this is now guaranteed
4507 // to work.
4508 auto *NewGV = cast<llvm::GlobalVariable>(
4509 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4510 ->stripPointerCasts());
4512 // Erase the old global, since it is no longer used.
4513 GV->eraseFromParent();
4514 GV = NewGV;
4515 } else {
4516 GV->setInitializer(Init);
4517 GV->setConstant(true);
4518 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
4520 emitter.finalize(GV);
4527 if (GV->isDeclaration()) {
4528 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4529 // External HIP managed variables needed to be recorded for transformation
4530 // in both device and host compilations.
4531 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4532 D->hasExternalStorage())
4533 getCUDARuntime().handleVarRegistration(D, *GV);
4536 if (D)
4537 SanitizerMD->reportGlobal(GV, *D);
4539 LangAS ExpectedAS =
4540 D ? D->getType().getAddressSpace()
4541 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4542 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4543 if (DAddrSpace != ExpectedAS) {
4544 return getTargetCodeGenInfo().performAddrSpaceCast(
4545 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4548 return GV;
4551 llvm::Constant *
4552 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4553 const Decl *D = GD.getDecl();
4555 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4556 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4557 /*DontDefer=*/false, IsForDefinition);
4559 if (isa<CXXMethodDecl>(D)) {
4560 auto FInfo =
4561 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4562 auto Ty = getTypes().GetFunctionType(*FInfo);
4563 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4564 IsForDefinition);
4567 if (isa<FunctionDecl>(D)) {
4568 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4569 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4570 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4571 IsForDefinition);
4574 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4577 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4578 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4579 llvm::Align Alignment) {
4580 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4581 llvm::GlobalVariable *OldGV = nullptr;
4583 if (GV) {
4584 // Check if the variable has the right type.
4585 if (GV->getValueType() == Ty)
4586 return GV;
4588 // Because C++ name mangling, the only way we can end up with an already
4589 // existing global with the same name is if it has been declared extern "C".
4590 assert(GV->isDeclaration() && "Declaration has wrong type!");
4591 OldGV = GV;
4594 // Create a new variable.
4595 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4596 Linkage, nullptr, Name);
4598 if (OldGV) {
4599 // Replace occurrences of the old variable if needed.
4600 GV->takeName(OldGV);
4602 if (!OldGV->use_empty()) {
4603 llvm::Constant *NewPtrForOldDecl =
4604 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4605 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4608 OldGV->eraseFromParent();
4611 if (supportsCOMDAT() && GV->isWeakForLinker() &&
4612 !GV->hasAvailableExternallyLinkage())
4613 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4615 GV->setAlignment(Alignment);
4617 return GV;
4620 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4621 /// given global variable. If Ty is non-null and if the global doesn't exist,
4622 /// then it will be created with the specified type instead of whatever the
4623 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4624 /// that an actual global with type Ty will be returned, not conversion of a
4625 /// variable with the same mangled name but some other type.
4626 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4627 llvm::Type *Ty,
4628 ForDefinition_t IsForDefinition) {
4629 assert(D->hasGlobalStorage() && "Not a global variable");
4630 QualType ASTTy = D->getType();
4631 if (!Ty)
4632 Ty = getTypes().ConvertTypeForMem(ASTTy);
4634 StringRef MangledName = getMangledName(D);
4635 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4636 IsForDefinition);
4639 /// CreateRuntimeVariable - Create a new runtime global variable with the
4640 /// specified type and name.
4641 llvm::Constant *
4642 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4643 StringRef Name) {
4644 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4645 : LangAS::Default;
4646 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4647 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4648 return Ret;
4651 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4652 assert(!D->getInit() && "Cannot emit definite definitions here!");
4654 StringRef MangledName = getMangledName(D);
4655 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4657 // We already have a definition, not declaration, with the same mangled name.
4658 // Emitting of declaration is not required (and actually overwrites emitted
4659 // definition).
4660 if (GV && !GV->isDeclaration())
4661 return;
4663 // If we have not seen a reference to this variable yet, place it into the
4664 // deferred declarations table to be emitted if needed later.
4665 if (!MustBeEmitted(D) && !GV) {
4666 DeferredDecls[MangledName] = D;
4667 return;
4670 // The tentative definition is the only definition.
4671 EmitGlobalVarDefinition(D);
4674 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4675 EmitExternalVarDeclaration(D);
4678 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4679 return Context.toCharUnitsFromBits(
4680 getDataLayout().getTypeStoreSizeInBits(Ty));
4683 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4684 if (LangOpts.OpenCL) {
4685 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4686 assert(AS == LangAS::opencl_global ||
4687 AS == LangAS::opencl_global_device ||
4688 AS == LangAS::opencl_global_host ||
4689 AS == LangAS::opencl_constant ||
4690 AS == LangAS::opencl_local ||
4691 AS >= LangAS::FirstTargetAddressSpace);
4692 return AS;
4695 if (LangOpts.SYCLIsDevice &&
4696 (!D || D->getType().getAddressSpace() == LangAS::Default))
4697 return LangAS::sycl_global;
4699 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4700 if (D) {
4701 if (D->hasAttr<CUDAConstantAttr>())
4702 return LangAS::cuda_constant;
4703 if (D->hasAttr<CUDASharedAttr>())
4704 return LangAS::cuda_shared;
4705 if (D->hasAttr<CUDADeviceAttr>())
4706 return LangAS::cuda_device;
4707 if (D->getType().isConstQualified())
4708 return LangAS::cuda_constant;
4710 return LangAS::cuda_device;
4713 if (LangOpts.OpenMP) {
4714 LangAS AS;
4715 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4716 return AS;
4718 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4721 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4722 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4723 if (LangOpts.OpenCL)
4724 return LangAS::opencl_constant;
4725 if (LangOpts.SYCLIsDevice)
4726 return LangAS::sycl_global;
4727 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
4728 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
4729 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
4730 // with OpVariable instructions with Generic storage class which is not
4731 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
4732 // UniformConstant storage class is not viable as pointers to it may not be
4733 // casted to Generic pointers which are used to model HIP's "flat" pointers.
4734 return LangAS::cuda_device;
4735 if (auto AS = getTarget().getConstantAddressSpace())
4736 return *AS;
4737 return LangAS::Default;
4740 // In address space agnostic languages, string literals are in default address
4741 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4742 // emitted in constant address space in LLVM IR. To be consistent with other
4743 // parts of AST, string literal global variables in constant address space
4744 // need to be casted to default address space before being put into address
4745 // map and referenced by other part of CodeGen.
4746 // In OpenCL, string literals are in constant address space in AST, therefore
4747 // they should not be casted to default address space.
4748 static llvm::Constant *
4749 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4750 llvm::GlobalVariable *GV) {
4751 llvm::Constant *Cast = GV;
4752 if (!CGM.getLangOpts().OpenCL) {
4753 auto AS = CGM.GetGlobalConstantAddressSpace();
4754 if (AS != LangAS::Default)
4755 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4756 CGM, GV, AS, LangAS::Default,
4757 GV->getValueType()->getPointerTo(
4758 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4760 return Cast;
4763 template<typename SomeDecl>
4764 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4765 llvm::GlobalValue *GV) {
4766 if (!getLangOpts().CPlusPlus)
4767 return;
4769 // Must have 'used' attribute, or else inline assembly can't rely on
4770 // the name existing.
4771 if (!D->template hasAttr<UsedAttr>())
4772 return;
4774 // Must have internal linkage and an ordinary name.
4775 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4776 return;
4778 // Must be in an extern "C" context. Entities declared directly within
4779 // a record are not extern "C" even if the record is in such a context.
4780 const SomeDecl *First = D->getFirstDecl();
4781 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4782 return;
4784 // OK, this is an internal linkage entity inside an extern "C" linkage
4785 // specification. Make a note of that so we can give it the "expected"
4786 // mangled name if nothing else is using that name.
4787 std::pair<StaticExternCMap::iterator, bool> R =
4788 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4790 // If we have multiple internal linkage entities with the same name
4791 // in extern "C" regions, none of them gets that name.
4792 if (!R.second)
4793 R.first->second = nullptr;
4796 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4797 if (!CGM.supportsCOMDAT())
4798 return false;
4800 if (D.hasAttr<SelectAnyAttr>())
4801 return true;
4803 GVALinkage Linkage;
4804 if (auto *VD = dyn_cast<VarDecl>(&D))
4805 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4806 else
4807 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4809 switch (Linkage) {
4810 case GVA_Internal:
4811 case GVA_AvailableExternally:
4812 case GVA_StrongExternal:
4813 return false;
4814 case GVA_DiscardableODR:
4815 case GVA_StrongODR:
4816 return true;
4818 llvm_unreachable("No such linkage");
4821 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4822 llvm::GlobalObject &GO) {
4823 if (!shouldBeInCOMDAT(*this, D))
4824 return;
4825 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4828 /// Pass IsTentative as true if you want to create a tentative definition.
4829 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4830 bool IsTentative) {
4831 // OpenCL global variables of sampler type are translated to function calls,
4832 // therefore no need to be translated.
4833 QualType ASTTy = D->getType();
4834 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4835 return;
4837 // If this is OpenMP device, check if it is legal to emit this global
4838 // normally.
4839 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4840 OpenMPRuntime->emitTargetGlobalVariable(D))
4841 return;
4843 llvm::TrackingVH<llvm::Constant> Init;
4844 bool NeedsGlobalCtor = false;
4845 // Whether the definition of the variable is available externally.
4846 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
4847 // since this is the job for its original source.
4848 bool IsDefinitionAvailableExternally =
4849 getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
4850 bool NeedsGlobalDtor =
4851 !IsDefinitionAvailableExternally &&
4852 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4854 const VarDecl *InitDecl;
4855 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4857 std::optional<ConstantEmitter> emitter;
4859 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4860 // as part of their declaration." Sema has already checked for
4861 // error cases, so we just need to set Init to UndefValue.
4862 bool IsCUDASharedVar =
4863 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4864 // Shadows of initialized device-side global variables are also left
4865 // undefined.
4866 // Managed Variables should be initialized on both host side and device side.
4867 bool IsCUDAShadowVar =
4868 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4869 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4870 D->hasAttr<CUDASharedAttr>());
4871 bool IsCUDADeviceShadowVar =
4872 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4873 (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4874 D->getType()->isCUDADeviceBuiltinTextureType());
4875 if (getLangOpts().CUDA &&
4876 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4877 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4878 else if (D->hasAttr<LoaderUninitializedAttr>())
4879 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4880 else if (!InitExpr) {
4881 // This is a tentative definition; tentative definitions are
4882 // implicitly initialized with { 0 }.
4884 // Note that tentative definitions are only emitted at the end of
4885 // a translation unit, so they should never have incomplete
4886 // type. In addition, EmitTentativeDefinition makes sure that we
4887 // never attempt to emit a tentative definition if a real one
4888 // exists. A use may still exists, however, so we still may need
4889 // to do a RAUW.
4890 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4891 Init = EmitNullConstant(D->getType());
4892 } else {
4893 initializedGlobalDecl = GlobalDecl(D);
4894 emitter.emplace(*this);
4895 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
4896 if (!Initializer) {
4897 QualType T = InitExpr->getType();
4898 if (D->getType()->isReferenceType())
4899 T = D->getType();
4901 if (getLangOpts().CPlusPlus) {
4902 if (InitDecl->hasFlexibleArrayInit(getContext()))
4903 ErrorUnsupported(D, "flexible array initializer");
4904 Init = EmitNullConstant(T);
4906 if (!IsDefinitionAvailableExternally)
4907 NeedsGlobalCtor = true;
4908 } else {
4909 ErrorUnsupported(D, "static initializer");
4910 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4912 } else {
4913 Init = Initializer;
4914 // We don't need an initializer, so remove the entry for the delayed
4915 // initializer position (just in case this entry was delayed) if we
4916 // also don't need to register a destructor.
4917 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4918 DelayedCXXInitPosition.erase(D);
4920 #ifndef NDEBUG
4921 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
4922 InitDecl->getFlexibleArrayInitChars(getContext());
4923 CharUnits CstSize = CharUnits::fromQuantity(
4924 getDataLayout().getTypeAllocSize(Init->getType()));
4925 assert(VarSize == CstSize && "Emitted constant has unexpected size");
4926 #endif
4930 llvm::Type* InitType = Init->getType();
4931 llvm::Constant *Entry =
4932 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4934 // Strip off pointer casts if we got them.
4935 Entry = Entry->stripPointerCasts();
4937 // Entry is now either a Function or GlobalVariable.
4938 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4940 // We have a definition after a declaration with the wrong type.
4941 // We must make a new GlobalVariable* and update everything that used OldGV
4942 // (a declaration or tentative definition) with the new GlobalVariable*
4943 // (which will be a definition).
4945 // This happens if there is a prototype for a global (e.g.
4946 // "extern int x[];") and then a definition of a different type (e.g.
4947 // "int x[10];"). This also happens when an initializer has a different type
4948 // from the type of the global (this happens with unions).
4949 if (!GV || GV->getValueType() != InitType ||
4950 GV->getType()->getAddressSpace() !=
4951 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4953 // Move the old entry aside so that we'll create a new one.
4954 Entry->setName(StringRef());
4956 // Make a new global with the correct type, this is now guaranteed to work.
4957 GV = cast<llvm::GlobalVariable>(
4958 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4959 ->stripPointerCasts());
4961 // Replace all uses of the old global with the new global
4962 llvm::Constant *NewPtrForOldDecl =
4963 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4964 Entry->getType());
4965 Entry->replaceAllUsesWith(NewPtrForOldDecl);
4967 // Erase the old global, since it is no longer used.
4968 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4971 MaybeHandleStaticInExternC(D, GV);
4973 if (D->hasAttr<AnnotateAttr>())
4974 AddGlobalAnnotations(D, GV);
4976 // Set the llvm linkage type as appropriate.
4977 llvm::GlobalValue::LinkageTypes Linkage =
4978 getLLVMLinkageVarDefinition(D, GV->isConstant());
4980 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4981 // the device. [...]"
4982 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4983 // __device__, declares a variable that: [...]
4984 // Is accessible from all the threads within the grid and from the host
4985 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4986 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4987 if (GV && LangOpts.CUDA) {
4988 if (LangOpts.CUDAIsDevice) {
4989 if (Linkage != llvm::GlobalValue::InternalLinkage &&
4990 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
4991 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4992 D->getType()->isCUDADeviceBuiltinTextureType()))
4993 GV->setExternallyInitialized(true);
4994 } else {
4995 getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4997 getCUDARuntime().handleVarRegistration(D, *GV);
5000 GV->setInitializer(Init);
5001 if (emitter)
5002 emitter->finalize(GV);
5004 // If it is safe to mark the global 'constant', do so now.
5005 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5006 isTypeConstant(D->getType(), true));
5008 // If it is in a read-only section, mark it 'constant'.
5009 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
5010 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
5011 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
5012 GV->setConstant(true);
5015 CharUnits AlignVal = getContext().getDeclAlign(D);
5016 // Check for alignment specifed in an 'omp allocate' directive.
5017 if (std::optional<CharUnits> AlignValFromAllocate =
5018 getOMPAllocateAlignment(D))
5019 AlignVal = *AlignValFromAllocate;
5020 GV->setAlignment(AlignVal.getAsAlign());
5022 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
5023 // function is only defined alongside the variable, not also alongside
5024 // callers. Normally, all accesses to a thread_local go through the
5025 // thread-wrapper in order to ensure initialization has occurred, underlying
5026 // variable will never be used other than the thread-wrapper, so it can be
5027 // converted to internal linkage.
5029 // However, if the variable has the 'constinit' attribute, it _can_ be
5030 // referenced directly, without calling the thread-wrapper, so the linkage
5031 // must not be changed.
5033 // Additionally, if the variable isn't plain external linkage, e.g. if it's
5034 // weak or linkonce, the de-duplication semantics are important to preserve,
5035 // so we don't change the linkage.
5036 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
5037 Linkage == llvm::GlobalValue::ExternalLinkage &&
5038 Context.getTargetInfo().getTriple().isOSDarwin() &&
5039 !D->hasAttr<ConstInitAttr>())
5040 Linkage = llvm::GlobalValue::InternalLinkage;
5042 GV->setLinkage(Linkage);
5043 if (D->hasAttr<DLLImportAttr>())
5044 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5045 else if (D->hasAttr<DLLExportAttr>())
5046 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5047 else
5048 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5050 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
5051 // common vars aren't constant even if declared const.
5052 GV->setConstant(false);
5053 // Tentative definition of global variables may be initialized with
5054 // non-zero null pointers. In this case they should have weak linkage
5055 // since common linkage must have zero initializer and must not have
5056 // explicit section therefore cannot have non-zero initial value.
5057 if (!GV->getInitializer()->isNullValue())
5058 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5061 setNonAliasAttributes(D, GV);
5063 if (D->getTLSKind() && !GV->isThreadLocal()) {
5064 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5065 CXXThreadLocals.push_back(D);
5066 setTLSMode(GV, *D);
5069 maybeSetTrivialComdat(*D, *GV);
5071 // Emit the initializer function if necessary.
5072 if (NeedsGlobalCtor || NeedsGlobalDtor)
5073 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
5075 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
5077 // Emit global variable debug information.
5078 if (CGDebugInfo *DI = getModuleDebugInfo())
5079 if (getCodeGenOpts().hasReducedDebugInfo())
5080 DI->EmitGlobalVariable(GV, D);
5083 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5084 if (CGDebugInfo *DI = getModuleDebugInfo())
5085 if (getCodeGenOpts().hasReducedDebugInfo()) {
5086 QualType ASTTy = D->getType();
5087 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5088 llvm::Constant *GV =
5089 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5090 DI->EmitExternalVariable(
5091 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5095 static bool isVarDeclStrongDefinition(const ASTContext &Context,
5096 CodeGenModule &CGM, const VarDecl *D,
5097 bool NoCommon) {
5098 // Don't give variables common linkage if -fno-common was specified unless it
5099 // was overridden by a NoCommon attribute.
5100 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
5101 return true;
5103 // C11 6.9.2/2:
5104 // A declaration of an identifier for an object that has file scope without
5105 // an initializer, and without a storage-class specifier or with the
5106 // storage-class specifier static, constitutes a tentative definition.
5107 if (D->getInit() || D->hasExternalStorage())
5108 return true;
5110 // A variable cannot be both common and exist in a section.
5111 if (D->hasAttr<SectionAttr>())
5112 return true;
5114 // A variable cannot be both common and exist in a section.
5115 // We don't try to determine which is the right section in the front-end.
5116 // If no specialized section name is applicable, it will resort to default.
5117 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
5118 D->hasAttr<PragmaClangDataSectionAttr>() ||
5119 D->hasAttr<PragmaClangRelroSectionAttr>() ||
5120 D->hasAttr<PragmaClangRodataSectionAttr>())
5121 return true;
5123 // Thread local vars aren't considered common linkage.
5124 if (D->getTLSKind())
5125 return true;
5127 // Tentative definitions marked with WeakImportAttr are true definitions.
5128 if (D->hasAttr<WeakImportAttr>())
5129 return true;
5131 // A variable cannot be both common and exist in a comdat.
5132 if (shouldBeInCOMDAT(CGM, *D))
5133 return true;
5135 // Declarations with a required alignment do not have common linkage in MSVC
5136 // mode.
5137 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5138 if (D->hasAttr<AlignedAttr>())
5139 return true;
5140 QualType VarType = D->getType();
5141 if (Context.isAlignmentRequired(VarType))
5142 return true;
5144 if (const auto *RT = VarType->getAs<RecordType>()) {
5145 const RecordDecl *RD = RT->getDecl();
5146 for (const FieldDecl *FD : RD->fields()) {
5147 if (FD->isBitField())
5148 continue;
5149 if (FD->hasAttr<AlignedAttr>())
5150 return true;
5151 if (Context.isAlignmentRequired(FD->getType()))
5152 return true;
5157 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
5158 // common symbols, so symbols with greater alignment requirements cannot be
5159 // common.
5160 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
5161 // alignments for common symbols via the aligncomm directive, so this
5162 // restriction only applies to MSVC environments.
5163 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
5164 Context.getTypeAlignIfKnown(D->getType()) >
5165 Context.toBits(CharUnits::fromQuantity(32)))
5166 return true;
5168 return false;
5171 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
5172 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
5173 if (Linkage == GVA_Internal)
5174 return llvm::Function::InternalLinkage;
5176 if (D->hasAttr<WeakAttr>())
5177 return llvm::GlobalVariable::WeakAnyLinkage;
5179 if (const auto *FD = D->getAsFunction())
5180 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
5181 return llvm::GlobalVariable::LinkOnceAnyLinkage;
5183 // We are guaranteed to have a strong definition somewhere else,
5184 // so we can use available_externally linkage.
5185 if (Linkage == GVA_AvailableExternally)
5186 return llvm::GlobalValue::AvailableExternallyLinkage;
5188 // Note that Apple's kernel linker doesn't support symbol
5189 // coalescing, so we need to avoid linkonce and weak linkages there.
5190 // Normally, this means we just map to internal, but for explicit
5191 // instantiations we'll map to external.
5193 // In C++, the compiler has to emit a definition in every translation unit
5194 // that references the function. We should use linkonce_odr because
5195 // a) if all references in this translation unit are optimized away, we
5196 // don't need to codegen it. b) if the function persists, it needs to be
5197 // merged with other definitions. c) C++ has the ODR, so we know the
5198 // definition is dependable.
5199 if (Linkage == GVA_DiscardableODR)
5200 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5201 : llvm::Function::InternalLinkage;
5203 // An explicit instantiation of a template has weak linkage, since
5204 // explicit instantiations can occur in multiple translation units
5205 // and must all be equivalent. However, we are not allowed to
5206 // throw away these explicit instantiations.
5208 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
5209 // so say that CUDA templates are either external (for kernels) or internal.
5210 // This lets llvm perform aggressive inter-procedural optimizations. For
5211 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5212 // therefore we need to follow the normal linkage paradigm.
5213 if (Linkage == GVA_StrongODR) {
5214 if (getLangOpts().AppleKext)
5215 return llvm::Function::ExternalLinkage;
5216 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5217 !getLangOpts().GPURelocatableDeviceCode)
5218 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5219 : llvm::Function::InternalLinkage;
5220 return llvm::Function::WeakODRLinkage;
5223 // C++ doesn't have tentative definitions and thus cannot have common
5224 // linkage.
5225 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
5226 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
5227 CodeGenOpts.NoCommon))
5228 return llvm::GlobalVariable::CommonLinkage;
5230 // selectany symbols are externally visible, so use weak instead of
5231 // linkonce. MSVC optimizes away references to const selectany globals, so
5232 // all definitions should be the same and ODR linkage should be used.
5233 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5234 if (D->hasAttr<SelectAnyAttr>())
5235 return llvm::GlobalVariable::WeakODRLinkage;
5237 // Otherwise, we have strong external linkage.
5238 assert(Linkage == GVA_StrongExternal);
5239 return llvm::GlobalVariable::ExternalLinkage;
5242 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
5243 const VarDecl *VD, bool IsConstant) {
5244 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5245 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
5248 /// Replace the uses of a function that was declared with a non-proto type.
5249 /// We want to silently drop extra arguments from call sites
5250 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
5251 llvm::Function *newFn) {
5252 // Fast path.
5253 if (old->use_empty()) return;
5255 llvm::Type *newRetTy = newFn->getReturnType();
5256 SmallVector<llvm::Value*, 4> newArgs;
5258 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5259 ui != ue; ) {
5260 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
5261 llvm::User *user = use->getUser();
5263 // Recognize and replace uses of bitcasts. Most calls to
5264 // unprototyped functions will use bitcasts.
5265 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5266 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5267 replaceUsesOfNonProtoConstant(bitcast, newFn);
5268 continue;
5271 // Recognize calls to the function.
5272 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5273 if (!callSite) continue;
5274 if (!callSite->isCallee(&*use))
5275 continue;
5277 // If the return types don't match exactly, then we can't
5278 // transform this call unless it's dead.
5279 if (callSite->getType() != newRetTy && !callSite->use_empty())
5280 continue;
5282 // Get the call site's attribute list.
5283 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
5284 llvm::AttributeList oldAttrs = callSite->getAttributes();
5286 // If the function was passed too few arguments, don't transform.
5287 unsigned newNumArgs = newFn->arg_size();
5288 if (callSite->arg_size() < newNumArgs)
5289 continue;
5291 // If extra arguments were passed, we silently drop them.
5292 // If any of the types mismatch, we don't transform.
5293 unsigned argNo = 0;
5294 bool dontTransform = false;
5295 for (llvm::Argument &A : newFn->args()) {
5296 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5297 dontTransform = true;
5298 break;
5301 // Add any parameter attributes.
5302 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5303 argNo++;
5305 if (dontTransform)
5306 continue;
5308 // Okay, we can transform this. Create the new call instruction and copy
5309 // over the required information.
5310 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5312 // Copy over any operand bundles.
5313 SmallVector<llvm::OperandBundleDef, 1> newBundles;
5314 callSite->getOperandBundlesAsDefs(newBundles);
5316 llvm::CallBase *newCall;
5317 if (isa<llvm::CallInst>(callSite)) {
5318 newCall =
5319 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
5320 } else {
5321 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5322 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5323 oldInvoke->getUnwindDest(), newArgs,
5324 newBundles, "", callSite);
5326 newArgs.clear(); // for the next iteration
5328 if (!newCall->getType()->isVoidTy())
5329 newCall->takeName(callSite);
5330 newCall->setAttributes(
5331 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5332 oldAttrs.getRetAttrs(), newArgAttrs));
5333 newCall->setCallingConv(callSite->getCallingConv());
5335 // Finally, remove the old call, replacing any uses with the new one.
5336 if (!callSite->use_empty())
5337 callSite->replaceAllUsesWith(newCall);
5339 // Copy debug location attached to CI.
5340 if (callSite->getDebugLoc())
5341 newCall->setDebugLoc(callSite->getDebugLoc());
5343 callSite->eraseFromParent();
5347 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5348 /// implement a function with no prototype, e.g. "int foo() {}". If there are
5349 /// existing call uses of the old function in the module, this adjusts them to
5350 /// call the new function directly.
5352 /// This is not just a cleanup: the always_inline pass requires direct calls to
5353 /// functions to be able to inline them. If there is a bitcast in the way, it
5354 /// won't inline them. Instcombine normally deletes these calls, but it isn't
5355 /// run at -O0.
5356 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5357 llvm::Function *NewFn) {
5358 // If we're redefining a global as a function, don't transform it.
5359 if (!isa<llvm::Function>(Old)) return;
5361 replaceUsesOfNonProtoConstant(Old, NewFn);
5364 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5365 auto DK = VD->isThisDeclarationADefinition();
5366 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
5367 return;
5369 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5370 // If we have a definition, this might be a deferred decl. If the
5371 // instantiation is explicit, make sure we emit it at the end.
5372 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5373 GetAddrOfGlobalVar(VD);
5375 EmitTopLevelDecl(VD);
5378 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5379 llvm::GlobalValue *GV) {
5380 const auto *D = cast<FunctionDecl>(GD.getDecl());
5382 // Compute the function info and LLVM type.
5383 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5384 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5386 // Get or create the prototype for the function.
5387 if (!GV || (GV->getValueType() != Ty))
5388 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5389 /*DontDefer=*/true,
5390 ForDefinition));
5392 // Already emitted.
5393 if (!GV->isDeclaration())
5394 return;
5396 // We need to set linkage and visibility on the function before
5397 // generating code for it because various parts of IR generation
5398 // want to propagate this information down (e.g. to local static
5399 // declarations).
5400 auto *Fn = cast<llvm::Function>(GV);
5401 setFunctionLinkage(GD, Fn);
5403 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5404 setGVProperties(Fn, GD);
5406 MaybeHandleStaticInExternC(D, Fn);
5408 maybeSetTrivialComdat(*D, *Fn);
5410 // Set CodeGen attributes that represent floating point environment.
5411 setLLVMFunctionFEnvAttributes(D, Fn);
5413 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
5415 setNonAliasAttributes(GD, Fn);
5416 SetLLVMFunctionAttributesForDefinition(D, Fn);
5418 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
5419 AddGlobalCtor(Fn, CA->getPriority());
5420 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5421 AddGlobalDtor(Fn, DA->getPriority(), true);
5422 if (D->hasAttr<AnnotateAttr>())
5423 AddGlobalAnnotations(D, Fn);
5426 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
5427 const auto *D = cast<ValueDecl>(GD.getDecl());
5428 const AliasAttr *AA = D->getAttr<AliasAttr>();
5429 assert(AA && "Not an alias?");
5431 StringRef MangledName = getMangledName(GD);
5433 if (AA->getAliasee() == MangledName) {
5434 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5435 return;
5438 // If there is a definition in the module, then it wins over the alias.
5439 // This is dubious, but allow it to be safe. Just ignore the alias.
5440 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5441 if (Entry && !Entry->isDeclaration())
5442 return;
5444 Aliases.push_back(GD);
5446 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5448 // Create a reference to the named value. This ensures that it is emitted
5449 // if a deferred decl.
5450 llvm::Constant *Aliasee;
5451 llvm::GlobalValue::LinkageTypes LT;
5452 if (isa<llvm::FunctionType>(DeclTy)) {
5453 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5454 /*ForVTable=*/false);
5455 LT = getFunctionLinkage(GD);
5456 } else {
5457 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
5458 /*D=*/nullptr);
5459 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5460 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
5461 else
5462 LT = getFunctionLinkage(GD);
5465 // Create the new alias itself, but don't set a name yet.
5466 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5467 auto *GA =
5468 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
5470 if (Entry) {
5471 if (GA->getAliasee() == Entry) {
5472 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5473 return;
5476 assert(Entry->isDeclaration());
5478 // If there is a declaration in the module, then we had an extern followed
5479 // by the alias, as in:
5480 // extern int test6();
5481 // ...
5482 // int test6() __attribute__((alias("test7")));
5484 // Remove it and replace uses of it with the alias.
5485 GA->takeName(Entry);
5487 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
5488 Entry->getType()));
5489 Entry->eraseFromParent();
5490 } else {
5491 GA->setName(MangledName);
5494 // Set attributes which are particular to an alias; this is a
5495 // specialization of the attributes which may be set on a global
5496 // variable/function.
5497 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
5498 D->isWeakImported()) {
5499 GA->setLinkage(llvm::Function::WeakAnyLinkage);
5502 if (const auto *VD = dyn_cast<VarDecl>(D))
5503 if (VD->getTLSKind())
5504 setTLSMode(GA, *VD);
5506 SetCommonAttributes(GD, GA);
5508 // Emit global alias debug information.
5509 if (isa<VarDecl>(D))
5510 if (CGDebugInfo *DI = getModuleDebugInfo())
5511 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
5514 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
5515 const auto *D = cast<ValueDecl>(GD.getDecl());
5516 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
5517 assert(IFA && "Not an ifunc?");
5519 StringRef MangledName = getMangledName(GD);
5521 if (IFA->getResolver() == MangledName) {
5522 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5523 return;
5526 // Report an error if some definition overrides ifunc.
5527 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5528 if (Entry && !Entry->isDeclaration()) {
5529 GlobalDecl OtherGD;
5530 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5531 DiagnosedConflictingDefinitions.insert(GD).second) {
5532 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
5533 << MangledName;
5534 Diags.Report(OtherGD.getDecl()->getLocation(),
5535 diag::note_previous_definition);
5537 return;
5540 Aliases.push_back(GD);
5542 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5543 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
5544 llvm::Constant *Resolver =
5545 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
5546 /*ForVTable=*/false);
5547 llvm::GlobalIFunc *GIF =
5548 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
5549 "", Resolver, &getModule());
5550 if (Entry) {
5551 if (GIF->getResolver() == Entry) {
5552 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5553 return;
5555 assert(Entry->isDeclaration());
5557 // If there is a declaration in the module, then we had an extern followed
5558 // by the ifunc, as in:
5559 // extern int test();
5560 // ...
5561 // int test() __attribute__((ifunc("resolver")));
5563 // Remove it and replace uses of it with the ifunc.
5564 GIF->takeName(Entry);
5566 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5567 Entry->getType()));
5568 Entry->eraseFromParent();
5569 } else
5570 GIF->setName(MangledName);
5572 SetCommonAttributes(GD, GIF);
5575 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5576 ArrayRef<llvm::Type*> Tys) {
5577 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5578 Tys);
5581 static llvm::StringMapEntry<llvm::GlobalVariable *> &
5582 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5583 const StringLiteral *Literal, bool TargetIsLSB,
5584 bool &IsUTF16, unsigned &StringLength) {
5585 StringRef String = Literal->getString();
5586 unsigned NumBytes = String.size();
5588 // Check for simple case.
5589 if (!Literal->containsNonAsciiOrNull()) {
5590 StringLength = NumBytes;
5591 return *Map.insert(std::make_pair(String, nullptr)).first;
5594 // Otherwise, convert the UTF8 literals into a string of shorts.
5595 IsUTF16 = true;
5597 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5598 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5599 llvm::UTF16 *ToPtr = &ToBuf[0];
5601 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5602 ToPtr + NumBytes, llvm::strictConversion);
5604 // ConvertUTF8toUTF16 returns the length in ToPtr.
5605 StringLength = ToPtr - &ToBuf[0];
5607 // Add an explicit null.
5608 *ToPtr = 0;
5609 return *Map.insert(std::make_pair(
5610 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5611 (StringLength + 1) * 2),
5612 nullptr)).first;
5615 ConstantAddress
5616 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5617 unsigned StringLength = 0;
5618 bool isUTF16 = false;
5619 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5620 GetConstantCFStringEntry(CFConstantStringMap, Literal,
5621 getDataLayout().isLittleEndian(), isUTF16,
5622 StringLength);
5624 if (auto *C = Entry.second)
5625 return ConstantAddress(
5626 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
5628 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5629 llvm::Constant *Zeros[] = { Zero, Zero };
5631 const ASTContext &Context = getContext();
5632 const llvm::Triple &Triple = getTriple();
5634 const auto CFRuntime = getLangOpts().CFRuntime;
5635 const bool IsSwiftABI =
5636 static_cast<unsigned>(CFRuntime) >=
5637 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5638 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5640 // If we don't already have it, get __CFConstantStringClassReference.
5641 if (!CFConstantStringClassRef) {
5642 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5643 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5644 Ty = llvm::ArrayType::get(Ty, 0);
5646 switch (CFRuntime) {
5647 default: break;
5648 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
5649 case LangOptions::CoreFoundationABI::Swift5_0:
5650 CFConstantStringClassName =
5651 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5652 : "$s10Foundation19_NSCFConstantStringCN";
5653 Ty = IntPtrTy;
5654 break;
5655 case LangOptions::CoreFoundationABI::Swift4_2:
5656 CFConstantStringClassName =
5657 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5658 : "$S10Foundation19_NSCFConstantStringCN";
5659 Ty = IntPtrTy;
5660 break;
5661 case LangOptions::CoreFoundationABI::Swift4_1:
5662 CFConstantStringClassName =
5663 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5664 : "__T010Foundation19_NSCFConstantStringCN";
5665 Ty = IntPtrTy;
5666 break;
5669 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5671 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5672 llvm::GlobalValue *GV = nullptr;
5674 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5675 IdentifierInfo &II = Context.Idents.get(GV->getName());
5676 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5677 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5679 const VarDecl *VD = nullptr;
5680 for (const auto *Result : DC->lookup(&II))
5681 if ((VD = dyn_cast<VarDecl>(Result)))
5682 break;
5684 if (Triple.isOSBinFormatELF()) {
5685 if (!VD)
5686 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5687 } else {
5688 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5689 if (!VD || !VD->hasAttr<DLLExportAttr>())
5690 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5691 else
5692 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5695 setDSOLocal(GV);
5699 // Decay array -> ptr
5700 CFConstantStringClassRef =
5701 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5702 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5705 QualType CFTy = Context.getCFConstantStringType();
5707 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5709 ConstantInitBuilder Builder(*this);
5710 auto Fields = Builder.beginStruct(STy);
5712 // Class pointer.
5713 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
5715 // Flags.
5716 if (IsSwiftABI) {
5717 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5718 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5719 } else {
5720 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5723 // String pointer.
5724 llvm::Constant *C = nullptr;
5725 if (isUTF16) {
5726 auto Arr = llvm::ArrayRef(
5727 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5728 Entry.first().size() / 2);
5729 C = llvm::ConstantDataArray::get(VMContext, Arr);
5730 } else {
5731 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5734 // Note: -fwritable-strings doesn't make the backing store strings of
5735 // CFStrings writable. (See <rdar://problem/10657500>)
5736 auto *GV =
5737 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5738 llvm::GlobalValue::PrivateLinkage, C, ".str");
5739 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5740 // Don't enforce the target's minimum global alignment, since the only use
5741 // of the string is via this class initializer.
5742 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5743 : Context.getTypeAlignInChars(Context.CharTy);
5744 GV->setAlignment(Align.getAsAlign());
5746 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5747 // Without it LLVM can merge the string with a non unnamed_addr one during
5748 // LTO. Doing that changes the section it ends in, which surprises ld64.
5749 if (Triple.isOSBinFormatMachO())
5750 GV->setSection(isUTF16 ? "__TEXT,__ustring"
5751 : "__TEXT,__cstring,cstring_literals");
5752 // Make sure the literal ends up in .rodata to allow for safe ICF and for
5753 // the static linker to adjust permissions to read-only later on.
5754 else if (Triple.isOSBinFormatELF())
5755 GV->setSection(".rodata");
5757 // String.
5758 llvm::Constant *Str =
5759 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5761 if (isUTF16)
5762 // Cast the UTF16 string to the correct type.
5763 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5764 Fields.add(Str);
5766 // String length.
5767 llvm::IntegerType *LengthTy =
5768 llvm::IntegerType::get(getModule().getContext(),
5769 Context.getTargetInfo().getLongWidth());
5770 if (IsSwiftABI) {
5771 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5772 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5773 LengthTy = Int32Ty;
5774 else
5775 LengthTy = IntPtrTy;
5777 Fields.addInt(LengthTy, StringLength);
5779 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5780 // properly aligned on 32-bit platforms.
5781 CharUnits Alignment =
5782 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5784 // The struct.
5785 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5786 /*isConstant=*/false,
5787 llvm::GlobalVariable::PrivateLinkage);
5788 GV->addAttribute("objc_arc_inert");
5789 switch (Triple.getObjectFormat()) {
5790 case llvm::Triple::UnknownObjectFormat:
5791 llvm_unreachable("unknown file format");
5792 case llvm::Triple::DXContainer:
5793 case llvm::Triple::GOFF:
5794 case llvm::Triple::SPIRV:
5795 case llvm::Triple::XCOFF:
5796 llvm_unreachable("unimplemented");
5797 case llvm::Triple::COFF:
5798 case llvm::Triple::ELF:
5799 case llvm::Triple::Wasm:
5800 GV->setSection("cfstring");
5801 break;
5802 case llvm::Triple::MachO:
5803 GV->setSection("__DATA,__cfstring");
5804 break;
5806 Entry.second = GV;
5808 return ConstantAddress(GV, GV->getValueType(), Alignment);
5811 bool CodeGenModule::getExpressionLocationsEnabled() const {
5812 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5815 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5816 if (ObjCFastEnumerationStateType.isNull()) {
5817 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5818 D->startDefinition();
5820 QualType FieldTypes[] = {
5821 Context.UnsignedLongTy,
5822 Context.getPointerType(Context.getObjCIdType()),
5823 Context.getPointerType(Context.UnsignedLongTy),
5824 Context.getConstantArrayType(Context.UnsignedLongTy,
5825 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5828 for (size_t i = 0; i < 4; ++i) {
5829 FieldDecl *Field = FieldDecl::Create(Context,
5831 SourceLocation(),
5832 SourceLocation(), nullptr,
5833 FieldTypes[i], /*TInfo=*/nullptr,
5834 /*BitWidth=*/nullptr,
5835 /*Mutable=*/false,
5836 ICIS_NoInit);
5837 Field->setAccess(AS_public);
5838 D->addDecl(Field);
5841 D->completeDefinition();
5842 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5845 return ObjCFastEnumerationStateType;
5848 llvm::Constant *
5849 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5850 assert(!E->getType()->isPointerType() && "Strings are always arrays");
5852 // Don't emit it as the address of the string, emit the string data itself
5853 // as an inline array.
5854 if (E->getCharByteWidth() == 1) {
5855 SmallString<64> Str(E->getString());
5857 // Resize the string to the right size, which is indicated by its type.
5858 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5859 Str.resize(CAT->getSize().getZExtValue());
5860 return llvm::ConstantDataArray::getString(VMContext, Str, false);
5863 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5864 llvm::Type *ElemTy = AType->getElementType();
5865 unsigned NumElements = AType->getNumElements();
5867 // Wide strings have either 2-byte or 4-byte elements.
5868 if (ElemTy->getPrimitiveSizeInBits() == 16) {
5869 SmallVector<uint16_t, 32> Elements;
5870 Elements.reserve(NumElements);
5872 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5873 Elements.push_back(E->getCodeUnit(i));
5874 Elements.resize(NumElements);
5875 return llvm::ConstantDataArray::get(VMContext, Elements);
5878 assert(ElemTy->getPrimitiveSizeInBits() == 32);
5879 SmallVector<uint32_t, 32> Elements;
5880 Elements.reserve(NumElements);
5882 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5883 Elements.push_back(E->getCodeUnit(i));
5884 Elements.resize(NumElements);
5885 return llvm::ConstantDataArray::get(VMContext, Elements);
5888 static llvm::GlobalVariable *
5889 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5890 CodeGenModule &CGM, StringRef GlobalName,
5891 CharUnits Alignment) {
5892 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5893 CGM.GetGlobalConstantAddressSpace());
5895 llvm::Module &M = CGM.getModule();
5896 // Create a global variable for this string
5897 auto *GV = new llvm::GlobalVariable(
5898 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5899 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5900 GV->setAlignment(Alignment.getAsAlign());
5901 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5902 if (GV->isWeakForLinker()) {
5903 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5904 GV->setComdat(M.getOrInsertComdat(GV->getName()));
5906 CGM.setDSOLocal(GV);
5908 return GV;
5911 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5912 /// constant array for the given string literal.
5913 ConstantAddress
5914 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5915 StringRef Name) {
5916 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5918 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5919 llvm::GlobalVariable **Entry = nullptr;
5920 if (!LangOpts.WritableStrings) {
5921 Entry = &ConstantStringMap[C];
5922 if (auto GV = *Entry) {
5923 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5924 GV->setAlignment(Alignment.getAsAlign());
5925 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5926 GV->getValueType(), Alignment);
5930 SmallString<256> MangledNameBuffer;
5931 StringRef GlobalVariableName;
5932 llvm::GlobalValue::LinkageTypes LT;
5934 // Mangle the string literal if that's how the ABI merges duplicate strings.
5935 // Don't do it if they are writable, since we don't want writes in one TU to
5936 // affect strings in another.
5937 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5938 !LangOpts.WritableStrings) {
5939 llvm::raw_svector_ostream Out(MangledNameBuffer);
5940 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5941 LT = llvm::GlobalValue::LinkOnceODRLinkage;
5942 GlobalVariableName = MangledNameBuffer;
5943 } else {
5944 LT = llvm::GlobalValue::PrivateLinkage;
5945 GlobalVariableName = Name;
5948 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5950 CGDebugInfo *DI = getModuleDebugInfo();
5951 if (DI && getCodeGenOpts().hasReducedDebugInfo())
5952 DI->AddStringLiteralDebugInfo(GV, S);
5954 if (Entry)
5955 *Entry = GV;
5957 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
5959 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5960 GV->getValueType(), Alignment);
5963 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5964 /// array for the given ObjCEncodeExpr node.
5965 ConstantAddress
5966 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5967 std::string Str;
5968 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5970 return GetAddrOfConstantCString(Str);
5973 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5974 /// the literal and a terminating '\0' character.
5975 /// The result has pointer to array type.
5976 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5977 const std::string &Str, const char *GlobalName) {
5978 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5979 CharUnits Alignment =
5980 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5982 llvm::Constant *C =
5983 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5985 // Don't share any string literals if strings aren't constant.
5986 llvm::GlobalVariable **Entry = nullptr;
5987 if (!LangOpts.WritableStrings) {
5988 Entry = &ConstantStringMap[C];
5989 if (auto GV = *Entry) {
5990 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5991 GV->setAlignment(Alignment.getAsAlign());
5992 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5993 GV->getValueType(), Alignment);
5997 // Get the default prefix if a name wasn't specified.
5998 if (!GlobalName)
5999 GlobalName = ".str";
6000 // Create a global variable for this.
6001 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
6002 GlobalName, Alignment);
6003 if (Entry)
6004 *Entry = GV;
6006 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6007 GV->getValueType(), Alignment);
6010 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
6011 const MaterializeTemporaryExpr *E, const Expr *Init) {
6012 assert((E->getStorageDuration() == SD_Static ||
6013 E->getStorageDuration() == SD_Thread) && "not a global temporary");
6014 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
6016 // If we're not materializing a subobject of the temporary, keep the
6017 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6018 QualType MaterializedType = Init->getType();
6019 if (Init == E->getSubExpr())
6020 MaterializedType = E->getType();
6022 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
6024 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6025 if (!InsertResult.second) {
6026 // We've seen this before: either we already created it or we're in the
6027 // process of doing so.
6028 if (!InsertResult.first->second) {
6029 // We recursively re-entered this function, probably during emission of
6030 // the initializer. Create a placeholder. We'll clean this up in the
6031 // outer call, at the end of this function.
6032 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6033 InsertResult.first->second = new llvm::GlobalVariable(
6034 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6035 nullptr);
6037 return ConstantAddress(InsertResult.first->second,
6038 llvm::cast<llvm::GlobalVariable>(
6039 InsertResult.first->second->stripPointerCasts())
6040 ->getValueType(),
6041 Align);
6044 // FIXME: If an externally-visible declaration extends multiple temporaries,
6045 // we need to give each temporary the same name in every translation unit (and
6046 // we also need to make the temporaries externally-visible).
6047 SmallString<256> Name;
6048 llvm::raw_svector_ostream Out(Name);
6049 getCXXABI().getMangleContext().mangleReferenceTemporary(
6050 VD, E->getManglingNumber(), Out);
6052 APValue *Value = nullptr;
6053 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
6054 // If the initializer of the extending declaration is a constant
6055 // initializer, we should have a cached constant initializer for this
6056 // temporary. Note that this might have a different value from the value
6057 // computed by evaluating the initializer if the surrounding constant
6058 // expression modifies the temporary.
6059 Value = E->getOrCreateValue(false);
6062 // Try evaluating it now, it might have a constant initializer.
6063 Expr::EvalResult EvalResult;
6064 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
6065 !EvalResult.hasSideEffects())
6066 Value = &EvalResult.Val;
6068 LangAS AddrSpace =
6069 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
6071 std::optional<ConstantEmitter> emitter;
6072 llvm::Constant *InitialValue = nullptr;
6073 bool Constant = false;
6074 llvm::Type *Type;
6075 if (Value) {
6076 // The temporary has a constant initializer, use it.
6077 emitter.emplace(*this);
6078 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
6079 MaterializedType);
6080 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
6081 Type = InitialValue->getType();
6082 } else {
6083 // No initializer, the initialization will be provided when we
6084 // initialize the declaration which performed lifetime extension.
6085 Type = getTypes().ConvertTypeForMem(MaterializedType);
6088 // Create a global variable for this lifetime-extended temporary.
6089 llvm::GlobalValue::LinkageTypes Linkage =
6090 getLLVMLinkageVarDefinition(VD, Constant);
6091 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
6092 const VarDecl *InitVD;
6093 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6094 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
6095 // Temporaries defined inside a class get linkonce_odr linkage because the
6096 // class can be defined in multiple translation units.
6097 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6098 } else {
6099 // There is no need for this temporary to have external linkage if the
6100 // VarDecl has external linkage.
6101 Linkage = llvm::GlobalVariable::InternalLinkage;
6104 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
6105 auto *GV = new llvm::GlobalVariable(
6106 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
6107 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6108 if (emitter) emitter->finalize(GV);
6109 // Don't assign dllimport or dllexport to local linkage globals.
6110 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
6111 setGVProperties(GV, VD);
6112 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6113 // The reference temporary should never be dllexport.
6114 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6116 GV->setAlignment(Align.getAsAlign());
6117 if (supportsCOMDAT() && GV->isWeakForLinker())
6118 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6119 if (VD->getTLSKind())
6120 setTLSMode(GV, *VD);
6121 llvm::Constant *CV = GV;
6122 if (AddrSpace != LangAS::Default)
6123 CV = getTargetCodeGenInfo().performAddrSpaceCast(
6124 *this, GV, AddrSpace, LangAS::Default,
6125 Type->getPointerTo(
6126 getContext().getTargetAddressSpace(LangAS::Default)));
6128 // Update the map with the new temporary. If we created a placeholder above,
6129 // replace it with the new global now.
6130 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6131 if (Entry) {
6132 Entry->replaceAllUsesWith(
6133 llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
6134 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6136 Entry = CV;
6138 return ConstantAddress(CV, Type, Align);
6141 /// EmitObjCPropertyImplementations - Emit information for synthesized
6142 /// properties for an implementation.
6143 void CodeGenModule::EmitObjCPropertyImplementations(const
6144 ObjCImplementationDecl *D) {
6145 for (const auto *PID : D->property_impls()) {
6146 // Dynamic is just for type-checking.
6147 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
6148 ObjCPropertyDecl *PD = PID->getPropertyDecl();
6150 // Determine which methods need to be implemented, some may have
6151 // been overridden. Note that ::isPropertyAccessor is not the method
6152 // we want, that just indicates if the decl came from a
6153 // property. What we want to know is if the method is defined in
6154 // this implementation.
6155 auto *Getter = PID->getGetterMethodDecl();
6156 if (!Getter || Getter->isSynthesizedAccessorStub())
6157 CodeGenFunction(*this).GenerateObjCGetter(
6158 const_cast<ObjCImplementationDecl *>(D), PID);
6159 auto *Setter = PID->getSetterMethodDecl();
6160 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6161 CodeGenFunction(*this).GenerateObjCSetter(
6162 const_cast<ObjCImplementationDecl *>(D), PID);
6167 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
6168 const ObjCInterfaceDecl *iface = impl->getClassInterface();
6169 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
6170 ivar; ivar = ivar->getNextIvar())
6171 if (ivar->getType().isDestructedType())
6172 return true;
6174 return false;
6177 static bool AllTrivialInitializers(CodeGenModule &CGM,
6178 ObjCImplementationDecl *D) {
6179 CodeGenFunction CGF(CGM);
6180 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
6181 E = D->init_end(); B != E; ++B) {
6182 CXXCtorInitializer *CtorInitExp = *B;
6183 Expr *Init = CtorInitExp->getInit();
6184 if (!CGF.isTrivialInitializer(Init))
6185 return false;
6187 return true;
6190 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6191 /// for an implementation.
6192 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
6193 // We might need a .cxx_destruct even if we don't have any ivar initializers.
6194 if (needsDestructMethod(D)) {
6195 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
6196 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6197 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6198 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6199 getContext().VoidTy, nullptr, D,
6200 /*isInstance=*/true, /*isVariadic=*/false,
6201 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6202 /*isImplicitlyDeclared=*/true,
6203 /*isDefined=*/false, ObjCMethodDecl::Required);
6204 D->addInstanceMethod(DTORMethod);
6205 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
6206 D->setHasDestructors(true);
6209 // If the implementation doesn't have any ivar initializers, we don't need
6210 // a .cxx_construct.
6211 if (D->getNumIvarInitializers() == 0 ||
6212 AllTrivialInitializers(*this, D))
6213 return;
6215 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
6216 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6217 // The constructor returns 'self'.
6218 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6219 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6220 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
6221 /*isVariadic=*/false,
6222 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6223 /*isImplicitlyDeclared=*/true,
6224 /*isDefined=*/false, ObjCMethodDecl::Required);
6225 D->addInstanceMethod(CTORMethod);
6226 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
6227 D->setHasNonZeroConstructors(true);
6230 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6231 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6232 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
6233 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
6234 ErrorUnsupported(LSD, "linkage spec");
6235 return;
6238 EmitDeclContext(LSD);
6241 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6242 std::unique_ptr<CodeGenFunction> &CurCGF =
6243 GlobalTopLevelStmtBlockInFlight.first;
6245 // We emitted a top-level stmt but after it there is initialization.
6246 // Stop squashing the top-level stmts into a single function.
6247 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6248 CurCGF->FinishFunction(D->getEndLoc());
6249 CurCGF = nullptr;
6252 if (!CurCGF) {
6253 // void __stmts__N(void)
6254 // FIXME: Ask the ABI name mangler to pick a name.
6255 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6256 FunctionArgList Args;
6257 QualType RetTy = getContext().VoidTy;
6258 const CGFunctionInfo &FnInfo =
6259 getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6260 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6261 llvm::Function *Fn = llvm::Function::Create(
6262 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6264 CurCGF.reset(new CodeGenFunction(*this));
6265 GlobalTopLevelStmtBlockInFlight.second = D;
6266 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6267 D->getBeginLoc(), D->getBeginLoc());
6268 CXXGlobalInits.push_back(Fn);
6271 CurCGF->EmitStmt(D->getStmt());
6274 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6275 for (auto *I : DC->decls()) {
6276 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6277 // are themselves considered "top-level", so EmitTopLevelDecl on an
6278 // ObjCImplDecl does not recursively visit them. We need to do that in
6279 // case they're nested inside another construct (LinkageSpecDecl /
6280 // ExportDecl) that does stop them from being considered "top-level".
6281 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6282 for (auto *M : OID->methods())
6283 EmitTopLevelDecl(M);
6286 EmitTopLevelDecl(I);
6290 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6291 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6292 // Ignore dependent declarations.
6293 if (D->isTemplated())
6294 return;
6296 // Consteval function shouldn't be emitted.
6297 if (auto *FD = dyn_cast<FunctionDecl>(D))
6298 if (FD->isConsteval())
6299 return;
6301 switch (D->getKind()) {
6302 case Decl::CXXConversion:
6303 case Decl::CXXMethod:
6304 case Decl::Function:
6305 EmitGlobal(cast<FunctionDecl>(D));
6306 // Always provide some coverage mapping
6307 // even for the functions that aren't emitted.
6308 AddDeferredUnusedCoverageMapping(D);
6309 break;
6311 case Decl::CXXDeductionGuide:
6312 // Function-like, but does not result in code emission.
6313 break;
6315 case Decl::Var:
6316 case Decl::Decomposition:
6317 case Decl::VarTemplateSpecialization:
6318 EmitGlobal(cast<VarDecl>(D));
6319 if (auto *DD = dyn_cast<DecompositionDecl>(D))
6320 for (auto *B : DD->bindings())
6321 if (auto *HD = B->getHoldingVar())
6322 EmitGlobal(HD);
6323 break;
6325 // Indirect fields from global anonymous structs and unions can be
6326 // ignored; only the actual variable requires IR gen support.
6327 case Decl::IndirectField:
6328 break;
6330 // C++ Decls
6331 case Decl::Namespace:
6332 EmitDeclContext(cast<NamespaceDecl>(D));
6333 break;
6334 case Decl::ClassTemplateSpecialization: {
6335 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6336 if (CGDebugInfo *DI = getModuleDebugInfo())
6337 if (Spec->getSpecializationKind() ==
6338 TSK_ExplicitInstantiationDefinition &&
6339 Spec->hasDefinition())
6340 DI->completeTemplateDefinition(*Spec);
6341 } [[fallthrough]];
6342 case Decl::CXXRecord: {
6343 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6344 if (CGDebugInfo *DI = getModuleDebugInfo()) {
6345 if (CRD->hasDefinition())
6346 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6347 if (auto *ES = D->getASTContext().getExternalSource())
6348 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6349 DI->completeUnusedClass(*CRD);
6351 // Emit any static data members, they may be definitions.
6352 for (auto *I : CRD->decls())
6353 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6354 EmitTopLevelDecl(I);
6355 break;
6357 // No code generation needed.
6358 case Decl::UsingShadow:
6359 case Decl::ClassTemplate:
6360 case Decl::VarTemplate:
6361 case Decl::Concept:
6362 case Decl::VarTemplatePartialSpecialization:
6363 case Decl::FunctionTemplate:
6364 case Decl::TypeAliasTemplate:
6365 case Decl::Block:
6366 case Decl::Empty:
6367 case Decl::Binding:
6368 break;
6369 case Decl::Using: // using X; [C++]
6370 if (CGDebugInfo *DI = getModuleDebugInfo())
6371 DI->EmitUsingDecl(cast<UsingDecl>(*D));
6372 break;
6373 case Decl::UsingEnum: // using enum X; [C++]
6374 if (CGDebugInfo *DI = getModuleDebugInfo())
6375 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6376 break;
6377 case Decl::NamespaceAlias:
6378 if (CGDebugInfo *DI = getModuleDebugInfo())
6379 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6380 break;
6381 case Decl::UsingDirective: // using namespace X; [C++]
6382 if (CGDebugInfo *DI = getModuleDebugInfo())
6383 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6384 break;
6385 case Decl::CXXConstructor:
6386 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6387 break;
6388 case Decl::CXXDestructor:
6389 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6390 break;
6392 case Decl::StaticAssert:
6393 // Nothing to do.
6394 break;
6396 // Objective-C Decls
6398 // Forward declarations, no (immediate) code generation.
6399 case Decl::ObjCInterface:
6400 case Decl::ObjCCategory:
6401 break;
6403 case Decl::ObjCProtocol: {
6404 auto *Proto = cast<ObjCProtocolDecl>(D);
6405 if (Proto->isThisDeclarationADefinition())
6406 ObjCRuntime->GenerateProtocol(Proto);
6407 break;
6410 case Decl::ObjCCategoryImpl:
6411 // Categories have properties but don't support synthesize so we
6412 // can ignore them here.
6413 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6414 break;
6416 case Decl::ObjCImplementation: {
6417 auto *OMD = cast<ObjCImplementationDecl>(D);
6418 EmitObjCPropertyImplementations(OMD);
6419 EmitObjCIvarInitializations(OMD);
6420 ObjCRuntime->GenerateClass(OMD);
6421 // Emit global variable debug information.
6422 if (CGDebugInfo *DI = getModuleDebugInfo())
6423 if (getCodeGenOpts().hasReducedDebugInfo())
6424 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6425 OMD->getClassInterface()), OMD->getLocation());
6426 break;
6428 case Decl::ObjCMethod: {
6429 auto *OMD = cast<ObjCMethodDecl>(D);
6430 // If this is not a prototype, emit the body.
6431 if (OMD->getBody())
6432 CodeGenFunction(*this).GenerateObjCMethod(OMD);
6433 break;
6435 case Decl::ObjCCompatibleAlias:
6436 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6437 break;
6439 case Decl::PragmaComment: {
6440 const auto *PCD = cast<PragmaCommentDecl>(D);
6441 switch (PCD->getCommentKind()) {
6442 case PCK_Unknown:
6443 llvm_unreachable("unexpected pragma comment kind");
6444 case PCK_Linker:
6445 AppendLinkerOptions(PCD->getArg());
6446 break;
6447 case PCK_Lib:
6448 AddDependentLib(PCD->getArg());
6449 break;
6450 case PCK_Compiler:
6451 case PCK_ExeStr:
6452 case PCK_User:
6453 break; // We ignore all of these.
6455 break;
6458 case Decl::PragmaDetectMismatch: {
6459 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6460 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6461 break;
6464 case Decl::LinkageSpec:
6465 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6466 break;
6468 case Decl::FileScopeAsm: {
6469 // File-scope asm is ignored during device-side CUDA compilation.
6470 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6471 break;
6472 // File-scope asm is ignored during device-side OpenMP compilation.
6473 if (LangOpts.OpenMPIsDevice)
6474 break;
6475 // File-scope asm is ignored during device-side SYCL compilation.
6476 if (LangOpts.SYCLIsDevice)
6477 break;
6478 auto *AD = cast<FileScopeAsmDecl>(D);
6479 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6480 break;
6483 case Decl::TopLevelStmt:
6484 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6485 break;
6487 case Decl::Import: {
6488 auto *Import = cast<ImportDecl>(D);
6490 // If we've already imported this module, we're done.
6491 if (!ImportedModules.insert(Import->getImportedModule()))
6492 break;
6494 // Emit debug information for direct imports.
6495 if (!Import->getImportedOwningModule()) {
6496 if (CGDebugInfo *DI = getModuleDebugInfo())
6497 DI->EmitImportDecl(*Import);
6500 // For C++ standard modules we are done - we will call the module
6501 // initializer for imported modules, and that will likewise call those for
6502 // any imports it has.
6503 if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6504 !Import->getImportedOwningModule()->isModuleMapModule())
6505 break;
6507 // For clang C++ module map modules the initializers for sub-modules are
6508 // emitted here.
6510 // Find all of the submodules and emit the module initializers.
6511 llvm::SmallPtrSet<clang::Module *, 16> Visited;
6512 SmallVector<clang::Module *, 16> Stack;
6513 Visited.insert(Import->getImportedModule());
6514 Stack.push_back(Import->getImportedModule());
6516 while (!Stack.empty()) {
6517 clang::Module *Mod = Stack.pop_back_val();
6518 if (!EmittedModuleInitializers.insert(Mod).second)
6519 continue;
6521 for (auto *D : Context.getModuleInitializers(Mod))
6522 EmitTopLevelDecl(D);
6524 // Visit the submodules of this module.
6525 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
6526 SubEnd = Mod->submodule_end();
6527 Sub != SubEnd; ++Sub) {
6528 // Skip explicit children; they need to be explicitly imported to emit
6529 // the initializers.
6530 if ((*Sub)->IsExplicit)
6531 continue;
6533 if (Visited.insert(*Sub).second)
6534 Stack.push_back(*Sub);
6537 break;
6540 case Decl::Export:
6541 EmitDeclContext(cast<ExportDecl>(D));
6542 break;
6544 case Decl::OMPThreadPrivate:
6545 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
6546 break;
6548 case Decl::OMPAllocate:
6549 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
6550 break;
6552 case Decl::OMPDeclareReduction:
6553 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
6554 break;
6556 case Decl::OMPDeclareMapper:
6557 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
6558 break;
6560 case Decl::OMPRequires:
6561 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
6562 break;
6564 case Decl::Typedef:
6565 case Decl::TypeAlias: // using foo = bar; [C++11]
6566 if (CGDebugInfo *DI = getModuleDebugInfo())
6567 DI->EmitAndRetainType(
6568 getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6569 break;
6571 case Decl::Record:
6572 if (CGDebugInfo *DI = getModuleDebugInfo())
6573 if (cast<RecordDecl>(D)->getDefinition())
6574 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6575 break;
6577 case Decl::Enum:
6578 if (CGDebugInfo *DI = getModuleDebugInfo())
6579 if (cast<EnumDecl>(D)->getDefinition())
6580 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
6581 break;
6583 case Decl::HLSLBuffer:
6584 getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
6585 break;
6587 default:
6588 // Make sure we handled everything we should, every other kind is a
6589 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
6590 // function. Need to recode Decl::Kind to do that easily.
6591 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
6592 break;
6596 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
6597 // Do we need to generate coverage mapping?
6598 if (!CodeGenOpts.CoverageMapping)
6599 return;
6600 switch (D->getKind()) {
6601 case Decl::CXXConversion:
6602 case Decl::CXXMethod:
6603 case Decl::Function:
6604 case Decl::ObjCMethod:
6605 case Decl::CXXConstructor:
6606 case Decl::CXXDestructor: {
6607 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
6608 break;
6609 SourceManager &SM = getContext().getSourceManager();
6610 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
6611 break;
6612 auto I = DeferredEmptyCoverageMappingDecls.find(D);
6613 if (I == DeferredEmptyCoverageMappingDecls.end())
6614 DeferredEmptyCoverageMappingDecls[D] = true;
6615 break;
6617 default:
6618 break;
6622 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
6623 // Do we need to generate coverage mapping?
6624 if (!CodeGenOpts.CoverageMapping)
6625 return;
6626 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
6627 if (Fn->isTemplateInstantiation())
6628 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6630 auto I = DeferredEmptyCoverageMappingDecls.find(D);
6631 if (I == DeferredEmptyCoverageMappingDecls.end())
6632 DeferredEmptyCoverageMappingDecls[D] = false;
6633 else
6634 I->second = false;
6637 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6638 // We call takeVector() here to avoid use-after-free.
6639 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6640 // we deserialize function bodies to emit coverage info for them, and that
6641 // deserializes more declarations. How should we handle that case?
6642 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6643 if (!Entry.second)
6644 continue;
6645 const Decl *D = Entry.first;
6646 switch (D->getKind()) {
6647 case Decl::CXXConversion:
6648 case Decl::CXXMethod:
6649 case Decl::Function:
6650 case Decl::ObjCMethod: {
6651 CodeGenPGO PGO(*this);
6652 GlobalDecl GD(cast<FunctionDecl>(D));
6653 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6654 getFunctionLinkage(GD));
6655 break;
6657 case Decl::CXXConstructor: {
6658 CodeGenPGO PGO(*this);
6659 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6660 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6661 getFunctionLinkage(GD));
6662 break;
6664 case Decl::CXXDestructor: {
6665 CodeGenPGO PGO(*this);
6666 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6667 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6668 getFunctionLinkage(GD));
6669 break;
6671 default:
6672 break;
6677 void CodeGenModule::EmitMainVoidAlias() {
6678 // In order to transition away from "__original_main" gracefully, emit an
6679 // alias for "main" in the no-argument case so that libc can detect when
6680 // new-style no-argument main is in used.
6681 if (llvm::Function *F = getModule().getFunction("main")) {
6682 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6683 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
6684 auto *GA = llvm::GlobalAlias::create("__main_void", F);
6685 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
6690 /// Turns the given pointer into a constant.
6691 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6692 const void *Ptr) {
6693 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6694 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6695 return llvm::ConstantInt::get(i64, PtrInt);
6698 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6699 llvm::NamedMDNode *&GlobalMetadata,
6700 GlobalDecl D,
6701 llvm::GlobalValue *Addr) {
6702 if (!GlobalMetadata)
6703 GlobalMetadata =
6704 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6706 // TODO: should we report variant information for ctors/dtors?
6707 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6708 llvm::ConstantAsMetadata::get(GetPointerConstant(
6709 CGM.getLLVMContext(), D.getDecl()))};
6710 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6713 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
6714 llvm::GlobalValue *CppFunc) {
6715 // Store the list of ifuncs we need to replace uses in.
6716 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
6717 // List of ConstantExprs that we should be able to delete when we're done
6718 // here.
6719 llvm::SmallVector<llvm::ConstantExpr *> CEs;
6721 // It isn't valid to replace the extern-C ifuncs if all we find is itself!
6722 if (Elem == CppFunc)
6723 return false;
6725 // First make sure that all users of this are ifuncs (or ifuncs via a
6726 // bitcast), and collect the list of ifuncs and CEs so we can work on them
6727 // later.
6728 for (llvm::User *User : Elem->users()) {
6729 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
6730 // ifunc directly. In any other case, just give up, as we don't know what we
6731 // could break by changing those.
6732 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
6733 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
6734 return false;
6736 for (llvm::User *CEUser : ConstExpr->users()) {
6737 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
6738 IFuncs.push_back(IFunc);
6739 } else {
6740 return false;
6743 CEs.push_back(ConstExpr);
6744 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
6745 IFuncs.push_back(IFunc);
6746 } else {
6747 // This user is one we don't know how to handle, so fail redirection. This
6748 // will result in an ifunc retaining a resolver name that will ultimately
6749 // fail to be resolved to a defined function.
6750 return false;
6754 // Now we know this is a valid case where we can do this alias replacement, we
6755 // need to remove all of the references to Elem (and the bitcasts!) so we can
6756 // delete it.
6757 for (llvm::GlobalIFunc *IFunc : IFuncs)
6758 IFunc->setResolver(nullptr);
6759 for (llvm::ConstantExpr *ConstExpr : CEs)
6760 ConstExpr->destroyConstant();
6762 // We should now be out of uses for the 'old' version of this function, so we
6763 // can erase it as well.
6764 Elem->eraseFromParent();
6766 for (llvm::GlobalIFunc *IFunc : IFuncs) {
6767 // The type of the resolver is always just a function-type that returns the
6768 // type of the IFunc, so create that here. If the type of the actual
6769 // resolver doesn't match, it just gets bitcast to the right thing.
6770 auto *ResolverTy =
6771 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
6772 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
6773 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
6774 IFunc->setResolver(Resolver);
6776 return true;
6779 /// For each function which is declared within an extern "C" region and marked
6780 /// as 'used', but has internal linkage, create an alias from the unmangled
6781 /// name to the mangled name if possible. People expect to be able to refer
6782 /// to such functions with an unmangled name from inline assembly within the
6783 /// same translation unit.
6784 void CodeGenModule::EmitStaticExternCAliases() {
6785 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6786 return;
6787 for (auto &I : StaticExternCValues) {
6788 IdentifierInfo *Name = I.first;
6789 llvm::GlobalValue *Val = I.second;
6791 // If Val is null, that implies there were multiple declarations that each
6792 // had a claim to the unmangled name. In this case, generation of the alias
6793 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
6794 if (!Val)
6795 break;
6797 llvm::GlobalValue *ExistingElem =
6798 getModule().getNamedValue(Name->getName());
6800 // If there is either not something already by this name, or we were able to
6801 // replace all uses from IFuncs, create the alias.
6802 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
6803 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6807 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6808 GlobalDecl &Result) const {
6809 auto Res = Manglings.find(MangledName);
6810 if (Res == Manglings.end())
6811 return false;
6812 Result = Res->getValue();
6813 return true;
6816 /// Emits metadata nodes associating all the global values in the
6817 /// current module with the Decls they came from. This is useful for
6818 /// projects using IR gen as a subroutine.
6820 /// Since there's currently no way to associate an MDNode directly
6821 /// with an llvm::GlobalValue, we create a global named metadata
6822 /// with the name 'clang.global.decl.ptrs'.
6823 void CodeGenModule::EmitDeclMetadata() {
6824 llvm::NamedMDNode *GlobalMetadata = nullptr;
6826 for (auto &I : MangledDeclNames) {
6827 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6828 // Some mangled names don't necessarily have an associated GlobalValue
6829 // in this module, e.g. if we mangled it for DebugInfo.
6830 if (Addr)
6831 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6835 /// Emits metadata nodes for all the local variables in the current
6836 /// function.
6837 void CodeGenFunction::EmitDeclMetadata() {
6838 if (LocalDeclMap.empty()) return;
6840 llvm::LLVMContext &Context = getLLVMContext();
6842 // Find the unique metadata ID for this name.
6843 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6845 llvm::NamedMDNode *GlobalMetadata = nullptr;
6847 for (auto &I : LocalDeclMap) {
6848 const Decl *D = I.first;
6849 llvm::Value *Addr = I.second.getPointer();
6850 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6851 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6852 Alloca->setMetadata(
6853 DeclPtrKind, llvm::MDNode::get(
6854 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6855 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6856 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6857 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6862 void CodeGenModule::EmitVersionIdentMetadata() {
6863 llvm::NamedMDNode *IdentMetadata =
6864 TheModule.getOrInsertNamedMetadata("llvm.ident");
6865 std::string Version = getClangFullVersion();
6866 llvm::LLVMContext &Ctx = TheModule.getContext();
6868 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6869 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6872 void CodeGenModule::EmitCommandLineMetadata() {
6873 llvm::NamedMDNode *CommandLineMetadata =
6874 TheModule.getOrInsertNamedMetadata("llvm.commandline");
6875 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6876 llvm::LLVMContext &Ctx = TheModule.getContext();
6878 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6879 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6882 void CodeGenModule::EmitCoverageFile() {
6883 if (getCodeGenOpts().CoverageDataFile.empty() &&
6884 getCodeGenOpts().CoverageNotesFile.empty())
6885 return;
6887 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6888 if (!CUNode)
6889 return;
6891 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6892 llvm::LLVMContext &Ctx = TheModule.getContext();
6893 auto *CoverageDataFile =
6894 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6895 auto *CoverageNotesFile =
6896 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6897 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6898 llvm::MDNode *CU = CUNode->getOperand(i);
6899 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6900 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6904 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6905 bool ForEH) {
6906 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6907 // FIXME: should we even be calling this method if RTTI is disabled
6908 // and it's not for EH?
6909 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6910 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6911 getTriple().isNVPTX()))
6912 return llvm::Constant::getNullValue(Int8PtrTy);
6914 if (ForEH && Ty->isObjCObjectPointerType() &&
6915 LangOpts.ObjCRuntime.isGNUFamily())
6916 return ObjCRuntime->GetEHType(Ty);
6918 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6921 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6922 // Do not emit threadprivates in simd-only mode.
6923 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6924 return;
6925 for (auto RefExpr : D->varlists()) {
6926 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6927 bool PerformInit =
6928 VD->getAnyInitializer() &&
6929 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6930 /*ForRef=*/false);
6932 Address Addr(GetAddrOfGlobalVar(VD),
6933 getTypes().ConvertTypeForMem(VD->getType()),
6934 getContext().getDeclAlign(VD));
6935 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6936 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6937 CXXGlobalInits.push_back(InitFunction);
6941 llvm::Metadata *
6942 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6943 StringRef Suffix) {
6944 if (auto *FnType = T->getAs<FunctionProtoType>())
6945 T = getContext().getFunctionType(
6946 FnType->getReturnType(), FnType->getParamTypes(),
6947 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
6949 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6950 if (InternalId)
6951 return InternalId;
6953 if (isExternallyVisible(T->getLinkage())) {
6954 std::string OutName;
6955 llvm::raw_string_ostream Out(OutName);
6956 getCXXABI().getMangleContext().mangleTypeName(
6957 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
6959 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
6960 Out << ".normalized";
6962 Out << Suffix;
6964 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6965 } else {
6966 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6967 llvm::ArrayRef<llvm::Metadata *>());
6970 return InternalId;
6973 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6974 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6977 llvm::Metadata *
6978 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6979 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6982 // Generalize pointer types to a void pointer with the qualifiers of the
6983 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6984 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6985 // 'void *'.
6986 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6987 if (!Ty->isPointerType())
6988 return Ty;
6990 return Ctx.getPointerType(
6991 QualType(Ctx.VoidTy).withCVRQualifiers(
6992 Ty->getPointeeType().getCVRQualifiers()));
6995 // Apply type generalization to a FunctionType's return and argument types
6996 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6997 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6998 SmallVector<QualType, 8> GeneralizedParams;
6999 for (auto &Param : FnType->param_types())
7000 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
7002 return Ctx.getFunctionType(
7003 GeneralizeType(Ctx, FnType->getReturnType()),
7004 GeneralizedParams, FnType->getExtProtoInfo());
7007 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
7008 return Ctx.getFunctionNoProtoType(
7009 GeneralizeType(Ctx, FnType->getReturnType()));
7011 llvm_unreachable("Encountered unknown FunctionType");
7014 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
7015 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
7016 GeneralizedMetadataIdMap, ".generalized");
7019 /// Returns whether this module needs the "all-vtables" type identifier.
7020 bool CodeGenModule::NeedAllVtablesTypeId() const {
7021 // Returns true if at least one of vtable-based CFI checkers is enabled and
7022 // is not in the trapping mode.
7023 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
7024 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
7025 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
7026 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
7027 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
7028 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
7029 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
7030 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
7033 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
7034 CharUnits Offset,
7035 const CXXRecordDecl *RD) {
7036 llvm::Metadata *MD =
7037 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
7038 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7040 if (CodeGenOpts.SanitizeCfiCrossDso)
7041 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
7042 VTable->addTypeMetadata(Offset.getQuantity(),
7043 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7045 if (NeedAllVtablesTypeId()) {
7046 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
7047 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7051 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
7052 if (!SanStats)
7053 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
7055 return *SanStats;
7058 llvm::Value *
7059 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
7060 CodeGenFunction &CGF) {
7061 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
7062 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
7063 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7064 auto *Call = CGF.EmitRuntimeCall(
7065 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
7066 return Call;
7069 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
7070 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
7071 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
7072 /* forPointeeType= */ true);
7075 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
7076 LValueBaseInfo *BaseInfo,
7077 TBAAAccessInfo *TBAAInfo,
7078 bool forPointeeType) {
7079 if (TBAAInfo)
7080 *TBAAInfo = getTBAAAccessInfo(T);
7082 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7083 // that doesn't return the information we need to compute BaseInfo.
7085 // Honor alignment typedef attributes even on incomplete types.
7086 // We also honor them straight for C++ class types, even as pointees;
7087 // there's an expressivity gap here.
7088 if (auto TT = T->getAs<TypedefType>()) {
7089 if (auto Align = TT->getDecl()->getMaxAlignment()) {
7090 if (BaseInfo)
7091 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
7092 return getContext().toCharUnitsFromBits(Align);
7096 bool AlignForArray = T->isArrayType();
7098 // Analyze the base element type, so we don't get confused by incomplete
7099 // array types.
7100 T = getContext().getBaseElementType(T);
7102 if (T->isIncompleteType()) {
7103 // We could try to replicate the logic from
7104 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7105 // type is incomplete, so it's impossible to test. We could try to reuse
7106 // getTypeAlignIfKnown, but that doesn't return the information we need
7107 // to set BaseInfo. So just ignore the possibility that the alignment is
7108 // greater than one.
7109 if (BaseInfo)
7110 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7111 return CharUnits::One();
7114 if (BaseInfo)
7115 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7117 CharUnits Alignment;
7118 const CXXRecordDecl *RD;
7119 if (T.getQualifiers().hasUnaligned()) {
7120 Alignment = CharUnits::One();
7121 } else if (forPointeeType && !AlignForArray &&
7122 (RD = T->getAsCXXRecordDecl())) {
7123 // For C++ class pointees, we don't know whether we're pointing at a
7124 // base or a complete object, so we generally need to use the
7125 // non-virtual alignment.
7126 Alignment = getClassPointerAlignment(RD);
7127 } else {
7128 Alignment = getContext().getTypeAlignInChars(T);
7131 // Cap to the global maximum type alignment unless the alignment
7132 // was somehow explicit on the type.
7133 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
7134 if (Alignment.getQuantity() > MaxAlign &&
7135 !getContext().isAlignmentRequired(T))
7136 Alignment = CharUnits::fromQuantity(MaxAlign);
7138 return Alignment;
7141 bool CodeGenModule::stopAutoInit() {
7142 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
7143 if (StopAfter) {
7144 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7145 // used
7146 if (NumAutoVarInit >= StopAfter) {
7147 return true;
7149 if (!NumAutoVarInit) {
7150 unsigned DiagID = getDiags().getCustomDiagID(
7151 DiagnosticsEngine::Warning,
7152 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7153 "number of times ftrivial-auto-var-init=%1 gets applied.");
7154 getDiags().Report(DiagID)
7155 << StopAfter
7156 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7157 LangOptions::TrivialAutoVarInitKind::Zero
7158 ? "zero"
7159 : "pattern");
7161 ++NumAutoVarInit;
7163 return false;
7166 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
7167 const Decl *D) const {
7168 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7169 // postfix beginning with '.' since the symbol name can be demangled.
7170 if (LangOpts.HIP)
7171 OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
7172 else
7173 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
7175 // If the CUID is not specified we try to generate a unique postfix.
7176 if (getLangOpts().CUID.empty()) {
7177 SourceManager &SM = getContext().getSourceManager();
7178 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
7179 assert(PLoc.isValid() && "Source location is expected to be valid.");
7181 // Get the hash of the user defined macros.
7182 llvm::MD5 Hash;
7183 llvm::MD5::MD5Result Result;
7184 for (const auto &Arg : PreprocessorOpts.Macros)
7185 Hash.update(Arg.first);
7186 Hash.final(Result);
7188 // Get the UniqueID for the file containing the decl.
7189 llvm::sys::fs::UniqueID ID;
7190 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
7191 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
7192 assert(PLoc.isValid() && "Source location is expected to be valid.");
7193 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
7194 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7195 << PLoc.getFilename() << EC.message();
7197 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
7198 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
7199 } else {
7200 OS << getContext().getCUIDHash();
7204 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7205 assert(DeferredDeclsToEmit.empty() &&
7206 "Should have emitted all decls deferred to emit.");
7207 assert(NewBuilder->DeferredDecls.empty() &&
7208 "Newly created module should not have deferred decls");
7209 NewBuilder->DeferredDecls = std::move(DeferredDecls);
7211 assert(NewBuilder->DeferredVTables.empty() &&
7212 "Newly created module should not have deferred vtables");
7213 NewBuilder->DeferredVTables = std::move(DeferredVTables);
7215 assert(NewBuilder->MangledDeclNames.empty() &&
7216 "Newly created module should not have mangled decl names");
7217 assert(NewBuilder->Manglings.empty() &&
7218 "Newly created module should not have manglings");
7219 NewBuilder->Manglings = std::move(Manglings);
7221 assert(WeakRefReferences.empty() && "Not all WeakRefRefs have been applied");
7222 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7224 NewBuilder->TBAA = std::move(TBAA);
7226 assert(NewBuilder->EmittedDeferredDecls.empty() &&
7227 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7229 NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls);
7231 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);