1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
16 #include "CGCUDARuntime.h"
19 #include "CGDebugInfo.h"
20 #include "CGObjCRuntime.h"
21 #include "CGOpenCLRuntime.h"
22 #include "CGOpenMPRuntime.h"
23 #include "CGOpenMPRuntimeNVPTX.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenPGO.h"
26 #include "ConstantEmitter.h"
27 #include "CoverageMappingGen.h"
28 #include "TargetInfo.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/DeclTemplate.h"
34 #include "clang/AST/Mangle.h"
35 #include "clang/AST/RecordLayout.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/Diagnostic.h"
40 #include "clang/Basic/Module.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/Version.h"
44 #include "clang/CodeGen/ConstantInitBuilder.h"
45 #include "clang/Frontend/CodeGenOptions.h"
46 #include "clang/Sema/SemaDiagnostic.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/IR/CallSite.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/ProfileData/InstrProfReader.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MD5.h"
60 using namespace clang;
61 using namespace CodeGen;
63 static llvm::cl::opt<bool> LimitedCoverage(
64 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
65 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
66 llvm::cl::init(false));
68 static const char AnnotationSection[] = "llvm.metadata";
70 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
71 switch (CGM.getTarget().getCXXABI().getKind()) {
72 case TargetCXXABI::GenericAArch64:
73 case TargetCXXABI::GenericARM:
74 case TargetCXXABI::iOS:
75 case TargetCXXABI::iOS64:
76 case TargetCXXABI::WatchOS:
77 case TargetCXXABI::GenericMIPS:
78 case TargetCXXABI::GenericItanium:
79 case TargetCXXABI::WebAssembly:
80 return CreateItaniumCXXABI(CGM);
81 case TargetCXXABI::Microsoft:
82 return CreateMicrosoftCXXABI(CGM);
85 llvm_unreachable("invalid C++ ABI kind");
88 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
89 const PreprocessorOptions &PPO,
90 const CodeGenOptions &CGO, llvm::Module &M,
91 DiagnosticsEngine &diags,
92 CoverageSourceInfo *CoverageInfo)
93 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
95 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
96 VMContext(M.getContext()), Types(*this), VTables(*this),
97 SanitizerMD(new SanitizerMetadata(*this)) {
99 // Initialize the type cache.
100 llvm::LLVMContext &LLVMContext = M.getContext();
101 VoidTy = llvm::Type::getVoidTy(LLVMContext);
102 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
106 HalfTy = llvm::Type::getHalfTy(LLVMContext);
107 FloatTy = llvm::Type::getFloatTy(LLVMContext);
108 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
109 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
110 PointerAlignInBytes =
111 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
113 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
115 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
116 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
117 IntPtrTy = llvm::IntegerType::get(LLVMContext,
118 C.getTargetInfo().getMaxPointerWidth());
119 Int8PtrTy = Int8Ty->getPointerTo(0);
120 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
121 AllocaInt8PtrTy = Int8Ty->getPointerTo(
122 M.getDataLayout().getAllocaAddrSpace());
123 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
125 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
130 createOpenCLRuntime();
132 createOpenMPRuntime();
136 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
137 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
138 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
139 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
140 getCXXABI().getMangleContext()));
142 // If debug info or coverage generation is enabled, create the CGDebugInfo
144 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
145 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
146 DebugInfo.reset(new CGDebugInfo(*this));
148 Block.GlobalUniqueCount = 0;
150 if (C.getLangOpts().ObjC1)
151 ObjCData.reset(new ObjCEntrypoints());
153 if (CodeGenOpts.hasProfileClangUse()) {
154 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
155 CodeGenOpts.ProfileInstrumentUsePath);
156 if (auto E = ReaderOrErr.takeError()) {
157 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
158 "Could not read profile %0: %1");
159 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
160 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
164 PGOReader = std::move(ReaderOrErr.get());
167 // If coverage mapping generation is enabled, create the
168 // CoverageMappingModuleGen object.
169 if (CodeGenOpts.CoverageMapping)
170 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
173 CodeGenModule::~CodeGenModule() {}
175 void CodeGenModule::createObjCRuntime() {
176 // This is just isGNUFamily(), but we want to force implementors of
177 // new ABIs to decide how best to do this.
178 switch (LangOpts.ObjCRuntime.getKind()) {
179 case ObjCRuntime::GNUstep:
180 case ObjCRuntime::GCC:
181 case ObjCRuntime::ObjFW:
182 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
185 case ObjCRuntime::FragileMacOSX:
186 case ObjCRuntime::MacOSX:
187 case ObjCRuntime::iOS:
188 case ObjCRuntime::WatchOS:
189 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
192 llvm_unreachable("bad runtime kind");
195 void CodeGenModule::createOpenCLRuntime() {
196 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
199 void CodeGenModule::createOpenMPRuntime() {
200 // Select a specialized code generation class based on the target, if any.
201 // If it does not exist use the default implementation.
202 switch (getTriple().getArch()) {
203 case llvm::Triple::nvptx:
204 case llvm::Triple::nvptx64:
205 assert(getLangOpts().OpenMPIsDevice &&
206 "OpenMP NVPTX is only prepared to deal with device code.");
207 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
210 if (LangOpts.OpenMPSimd)
211 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
213 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
218 void CodeGenModule::createCUDARuntime() {
219 CUDARuntime.reset(CreateNVCUDARuntime(*this));
222 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
223 Replacements[Name] = C;
226 void CodeGenModule::applyReplacements() {
227 for (auto &I : Replacements) {
228 StringRef MangledName = I.first();
229 llvm::Constant *Replacement = I.second;
230 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233 auto *OldF = cast<llvm::Function>(Entry);
234 auto *NewF = dyn_cast<llvm::Function>(Replacement);
236 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
237 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
239 auto *CE = cast<llvm::ConstantExpr>(Replacement);
240 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
241 CE->getOpcode() == llvm::Instruction::GetElementPtr);
242 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
246 // Replace old with new, but keep the old order.
247 OldF->replaceAllUsesWith(Replacement);
249 NewF->removeFromParent();
250 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253 OldF->eraseFromParent();
257 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
258 GlobalValReplacements.push_back(std::make_pair(GV, C));
261 void CodeGenModule::applyGlobalValReplacements() {
262 for (auto &I : GlobalValReplacements) {
263 llvm::GlobalValue *GV = I.first;
264 llvm::Constant *C = I.second;
266 GV->replaceAllUsesWith(C);
267 GV->eraseFromParent();
271 // This is only used in aliases that we created and we know they have a
273 static const llvm::GlobalObject *getAliasedGlobal(
274 const llvm::GlobalIndirectSymbol &GIS) {
275 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
276 const llvm::Constant *C = &GIS;
278 C = C->stripPointerCasts();
279 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
281 // stripPointerCasts will not walk over weak aliases.
282 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285 if (!Visited.insert(GIS2).second)
287 C = GIS2->getIndirectSymbol();
291 void CodeGenModule::checkAliases() {
292 // Check if the constructed aliases are well formed. It is really unfortunate
293 // that we have to do this in CodeGen, but we only construct mangled names
294 // and aliases during codegen.
296 DiagnosticsEngine &Diags = getDiags();
297 for (const GlobalDecl &GD : Aliases) {
298 const auto *D = cast<ValueDecl>(GD.getDecl());
299 SourceLocation Location;
300 bool IsIFunc = D->hasAttr<IFuncAttr>();
301 if (const Attr *A = D->getDefiningAttr())
302 Location = A->getLocation();
304 llvm_unreachable("Not an alias or ifunc?");
305 StringRef MangledName = getMangledName(GD);
306 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
307 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
308 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
311 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
312 } else if (GV->isDeclaration()) {
314 Diags.Report(Location, diag::err_alias_to_undefined)
315 << IsIFunc << IsIFunc;
316 } else if (IsIFunc) {
317 // Check resolver function type.
318 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
319 GV->getType()->getPointerElementType());
321 if (!FTy->getReturnType()->isPointerTy())
322 Diags.Report(Location, diag::err_ifunc_resolver_return);
325 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
326 llvm::GlobalValue *AliaseeGV;
327 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
328 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
330 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
332 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
333 StringRef AliasSection = SA->getName();
334 if (AliasSection != AliaseeGV->getSection())
335 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
336 << AliasSection << IsIFunc << IsIFunc;
339 // We have to handle alias to weak aliases in here. LLVM itself disallows
340 // this since the object semantics would not match the IL one. For
341 // compatibility with gcc we implement it by just pointing the alias
342 // to its aliasee's aliasee. We also warn, since the user is probably
343 // expecting the link to be weak.
344 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
345 if (GA->isInterposable()) {
346 Diags.Report(Location, diag::warn_alias_to_weak_alias)
347 << GV->getName() << GA->getName() << IsIFunc;
348 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
349 GA->getIndirectSymbol(), Alias->getType());
350 Alias->setIndirectSymbol(Aliasee);
357 for (const GlobalDecl &GD : Aliases) {
358 StringRef MangledName = getMangledName(GD);
359 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
360 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
361 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
362 Alias->eraseFromParent();
366 void CodeGenModule::clear() {
367 DeferredDeclsToEmit.clear();
369 OpenMPRuntime->clear();
372 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
373 StringRef MainFile) {
374 if (!hasDiagnostics())
376 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
377 if (MainFile.empty())
378 MainFile = "<stdin>";
379 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
382 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
389 void CodeGenModule::Release() {
391 EmitVTablesOpportunistically();
392 applyGlobalValReplacements();
395 emitMultiVersionFunctions();
396 EmitCXXGlobalInitFunc();
397 EmitCXXGlobalDtorFunc();
398 registerGlobalDtorsWithAtExit();
399 EmitCXXThreadLocalInitFunc();
401 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
402 AddGlobalCtor(ObjCInitFunction);
403 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
405 if (llvm::Function *CudaCtorFunction =
406 CUDARuntime->makeModuleCtorFunction())
407 AddGlobalCtor(CudaCtorFunction);
410 if (llvm::Function *OpenMPRegistrationFunction =
411 OpenMPRuntime->emitRegistrationFunction()) {
412 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
413 OpenMPRegistrationFunction : nullptr;
414 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
416 OpenMPRuntime->clear();
419 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
420 if (PGOStats.hasDiagnostics())
421 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
423 EmitCtorList(GlobalCtors, "llvm.global_ctors");
424 EmitCtorList(GlobalDtors, "llvm.global_dtors");
425 EmitGlobalAnnotations();
426 EmitStaticExternCAliases();
427 EmitDeferredUnusedCoverageMappings();
429 CoverageMapping->emit();
430 if (CodeGenOpts.SanitizeCfiCrossDso) {
431 CodeGenFunction(*this).EmitCfiCheckFail();
432 CodeGenFunction(*this).EmitCfiCheckStub();
434 emitAtAvailableLinkGuard();
439 if (CodeGenOpts.Autolink &&
440 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
441 EmitModuleLinkOptions();
444 // Record mregparm value now so it is visible through rest of codegen.
445 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
446 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
447 CodeGenOpts.NumRegisterParameters);
449 if (CodeGenOpts.DwarfVersion) {
450 // We actually want the latest version when there are conflicts.
451 // We can change from Warning to Latest if such mode is supported.
452 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
453 CodeGenOpts.DwarfVersion);
455 if (CodeGenOpts.EmitCodeView) {
456 // Indicate that we want CodeView in the metadata.
457 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
459 if (CodeGenOpts.ControlFlowGuard) {
460 // We want function ID tables for Control Flow Guard.
461 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
463 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
464 // We don't support LTO with 2 with different StrictVTablePointers
465 // FIXME: we could support it by stripping all the information introduced
466 // by StrictVTablePointers.
468 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
470 llvm::Metadata *Ops[2] = {
471 llvm::MDString::get(VMContext, "StrictVTablePointers"),
472 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
473 llvm::Type::getInt32Ty(VMContext), 1))};
475 getModule().addModuleFlag(llvm::Module::Require,
476 "StrictVTablePointersRequirement",
477 llvm::MDNode::get(VMContext, Ops));
480 // We support a single version in the linked module. The LLVM
481 // parser will drop debug info with a different version number
482 // (and warn about it, too).
483 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
484 llvm::DEBUG_METADATA_VERSION);
486 // We need to record the widths of enums and wchar_t, so that we can generate
487 // the correct build attributes in the ARM backend. wchar_size is also used by
488 // TargetLibraryInfo.
489 uint64_t WCharWidth =
490 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
491 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
493 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
494 if ( Arch == llvm::Triple::arm
495 || Arch == llvm::Triple::armeb
496 || Arch == llvm::Triple::thumb
497 || Arch == llvm::Triple::thumbeb) {
498 // The minimum width of an enum in bytes
499 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
500 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
503 if (CodeGenOpts.SanitizeCfiCrossDso) {
504 // Indicate that we want cross-DSO control flow integrity checks.
505 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
508 if (CodeGenOpts.CFProtectionReturn &&
509 Target.checkCFProtectionReturnSupported(getDiags())) {
510 // Indicate that we want to instrument return control flow protection.
511 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
515 if (CodeGenOpts.CFProtectionBranch &&
516 Target.checkCFProtectionBranchSupported(getDiags())) {
517 // Indicate that we want to instrument branch control flow protection.
518 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
522 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
523 // Indicate whether __nvvm_reflect should be configured to flush denormal
524 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
526 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
527 CodeGenOpts.FlushDenorm ? 1 : 0);
530 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
531 if (LangOpts.OpenCL) {
532 EmitOpenCLMetadata();
533 // Emit SPIR version.
534 if (getTriple().getArch() == llvm::Triple::spir ||
535 getTriple().getArch() == llvm::Triple::spir64) {
536 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
537 // opencl.spir.version named metadata.
538 llvm::Metadata *SPIRVerElts[] = {
539 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
540 Int32Ty, LangOpts.OpenCLVersion / 100)),
541 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
543 llvm::NamedMDNode *SPIRVerMD =
544 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
545 llvm::LLVMContext &Ctx = TheModule.getContext();
546 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
550 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
551 assert(PLevel < 3 && "Invalid PIC Level");
552 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
553 if (Context.getLangOpts().PIE)
554 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
557 if (CodeGenOpts.NoPLT)
558 getModule().setRtLibUseGOT();
560 SimplifyPersonality();
562 if (getCodeGenOpts().EmitDeclMetadata)
565 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
569 DebugInfo->finalize();
571 if (getCodeGenOpts().EmitVersionIdentMetadata)
572 EmitVersionIdentMetadata();
574 EmitTargetMetadata();
577 void CodeGenModule::EmitOpenCLMetadata() {
578 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
579 // opencl.ocl.version named metadata node.
580 llvm::Metadata *OCLVerElts[] = {
581 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
582 Int32Ty, LangOpts.OpenCLVersion / 100)),
583 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
584 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
585 llvm::NamedMDNode *OCLVerMD =
586 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
587 llvm::LLVMContext &Ctx = TheModule.getContext();
588 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
591 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
592 // Make sure that this type is translated.
593 Types.UpdateCompletedType(TD);
596 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
597 // Make sure that this type is translated.
598 Types.RefreshTypeCacheForClass(RD);
601 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
604 return TBAA->getTypeInfo(QTy);
607 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
609 return TBAAAccessInfo();
610 return TBAA->getAccessInfo(AccessType);
614 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
616 return TBAAAccessInfo();
617 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
620 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
623 return TBAA->getTBAAStructInfo(QTy);
626 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
629 return TBAA->getBaseTypeInfo(QTy);
632 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
635 return TBAA->getAccessTagInfo(Info);
638 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
639 TBAAAccessInfo TargetInfo) {
641 return TBAAAccessInfo();
642 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
646 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
647 TBAAAccessInfo InfoB) {
649 return TBAAAccessInfo();
650 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
654 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
655 TBAAAccessInfo SrcInfo) {
657 return TBAAAccessInfo();
658 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
661 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
662 TBAAAccessInfo TBAAInfo) {
663 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
664 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
667 void CodeGenModule::DecorateInstructionWithInvariantGroup(
668 llvm::Instruction *I, const CXXRecordDecl *RD) {
669 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
670 llvm::MDNode::get(getLLVMContext(), {}));
673 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
674 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
675 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
678 /// ErrorUnsupported - Print out an error that codegen doesn't support the
679 /// specified stmt yet.
680 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
681 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
682 "cannot compile this %0 yet");
683 std::string Msg = Type;
684 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
685 << Msg << S->getSourceRange();
688 /// ErrorUnsupported - Print out an error that codegen doesn't support the
689 /// specified decl yet.
690 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
691 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
692 "cannot compile this %0 yet");
693 std::string Msg = Type;
694 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
697 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
698 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
701 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
702 const NamedDecl *D) const {
703 if (GV->hasDLLImportStorageClass())
705 // Internal definitions always have default visibility.
706 if (GV->hasLocalLinkage()) {
707 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
712 // Set visibility for definitions.
713 LinkageInfo LV = D->getLinkageAndVisibility();
714 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
715 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
718 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
719 llvm::GlobalValue *GV) {
720 if (GV->hasLocalLinkage())
723 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
726 // DLLImport explicitly marks the GV as external.
727 if (GV->hasDLLImportStorageClass())
730 const llvm::Triple &TT = CGM.getTriple();
731 // Every other GV is local on COFF.
732 // Make an exception for windows OS in the triple: Some firmware builds use
733 // *-win32-macho triples. This (accidentally?) produced windows relocations
734 // without GOT tables in older clang versions; Keep this behaviour.
735 // FIXME: even thread local variables?
736 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
739 // Only handle COFF and ELF for now.
740 if (!TT.isOSBinFormatELF())
743 // If this is not an executable, don't assume anything is local.
744 const auto &CGOpts = CGM.getCodeGenOpts();
745 llvm::Reloc::Model RM = CGOpts.RelocationModel;
746 const auto &LOpts = CGM.getLangOpts();
747 if (RM != llvm::Reloc::Static && !LOpts.PIE)
750 // A definition cannot be preempted from an executable.
751 if (!GV->isDeclarationForLinker())
754 // Most PIC code sequences that assume that a symbol is local cannot produce a
755 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
756 // depended, it seems worth it to handle it here.
757 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
760 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
761 llvm::Triple::ArchType Arch = TT.getArch();
762 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
763 Arch == llvm::Triple::ppc64le)
766 // If we can use copy relocations we can assume it is local.
767 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
768 if (!Var->isThreadLocal() &&
769 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
772 // If we can use a plt entry as the symbol address we can assume it
774 // FIXME: This should work for PIE, but the gold linker doesn't support it.
775 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
778 // Otherwise don't assue it is local.
782 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
783 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
786 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
787 GlobalDecl GD) const {
788 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
789 // C++ destructors have a few C++ ABI specific special cases.
790 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
791 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
794 setDLLImportDLLExport(GV, D);
797 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
798 const NamedDecl *D) const {
799 if (D && D->isExternallyVisible()) {
800 if (D->hasAttr<DLLImportAttr>())
801 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
802 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
803 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
807 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
808 GlobalDecl GD) const {
809 setDLLImportDLLExport(GV, GD);
810 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
813 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
814 const NamedDecl *D) const {
815 setDLLImportDLLExport(GV, D);
816 setGlobalVisibilityAndLocal(GV, D);
819 void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
820 const NamedDecl *D) const {
821 setGlobalVisibility(GV, D);
825 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
826 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
827 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
828 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
829 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
830 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
833 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
834 CodeGenOptions::TLSModel M) {
836 case CodeGenOptions::GeneralDynamicTLSModel:
837 return llvm::GlobalVariable::GeneralDynamicTLSModel;
838 case CodeGenOptions::LocalDynamicTLSModel:
839 return llvm::GlobalVariable::LocalDynamicTLSModel;
840 case CodeGenOptions::InitialExecTLSModel:
841 return llvm::GlobalVariable::InitialExecTLSModel;
842 case CodeGenOptions::LocalExecTLSModel:
843 return llvm::GlobalVariable::LocalExecTLSModel;
845 llvm_unreachable("Invalid TLS model!");
848 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
849 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
851 llvm::GlobalValue::ThreadLocalMode TLM;
852 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
854 // Override the TLS model if it is explicitly specified.
855 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
856 TLM = GetLLVMTLSModel(Attr->getModel());
859 GV->setThreadLocalMode(TLM);
862 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
864 const TargetInfo &Target = CGM.getTarget();
865 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
868 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
869 const CPUSpecificAttr *Attr,
871 // cpu_specific gets the current name, dispatch gets the resolver.
873 Out << getCPUSpecificMangling(CGM, Attr->getCurCPUName()->getName());
878 static void AppendTargetMangling(const CodeGenModule &CGM,
879 const TargetAttr *Attr, raw_ostream &Out) {
880 if (Attr->isDefaultVersion())
884 const TargetInfo &Target = CGM.getTarget();
885 TargetAttr::ParsedTargetAttr Info =
886 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
887 // Multiversioning doesn't allow "no-${feature}", so we can
888 // only have "+" prefixes here.
889 assert(LHS.startswith("+") && RHS.startswith("+") &&
890 "Features should always have a prefix.");
891 return Target.multiVersionSortPriority(LHS.substr(1)) >
892 Target.multiVersionSortPriority(RHS.substr(1));
897 if (!Info.Architecture.empty()) {
899 Out << "arch_" << Info.Architecture;
902 for (StringRef Feat : Info.Features) {
906 Out << Feat.substr(1);
910 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
912 bool OmitMultiVersionMangling = false) {
913 SmallString<256> Buffer;
914 llvm::raw_svector_ostream Out(Buffer);
915 MangleContext &MC = CGM.getCXXABI().getMangleContext();
916 if (MC.shouldMangleDeclName(ND)) {
917 llvm::raw_svector_ostream Out(Buffer);
918 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
919 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
920 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
921 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
923 MC.mangleName(ND, Out);
925 IdentifierInfo *II = ND->getIdentifier();
926 assert(II && "Attempt to mangle unnamed decl.");
927 const auto *FD = dyn_cast<FunctionDecl>(ND);
930 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
931 llvm::raw_svector_ostream Out(Buffer);
932 Out << "__regcall3__" << II->getName();
934 Out << II->getName();
938 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
939 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
940 if (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())
941 AppendCPUSpecificCPUDispatchMangling(
942 CGM, FD->getAttr<CPUSpecificAttr>(), Out);
944 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
950 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
951 const FunctionDecl *FD) {
952 if (!FD->isMultiVersion())
955 // Get the name of what this would be without the 'target' attribute. This
956 // allows us to lookup the version that was emitted when this wasn't a
957 // multiversion function.
958 std::string NonTargetName =
959 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
961 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
962 assert(OtherGD.getCanonicalDecl()
965 ->isMultiVersion() &&
966 "Other GD should now be a multiversioned function");
967 // OtherFD is the version of this function that was mangled BEFORE
968 // becoming a MultiVersion function. It potentially needs to be updated.
969 const FunctionDecl *OtherFD =
970 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
971 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
972 // This is so that if the initial version was already the 'default'
973 // version, we don't try to update it.
974 if (OtherName != NonTargetName) {
975 // Remove instead of erase, since others may have stored the StringRef
977 const auto ExistingRecord = Manglings.find(NonTargetName);
978 if (ExistingRecord != std::end(Manglings))
979 Manglings.remove(&(*ExistingRecord));
980 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
981 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
982 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
983 Entry->setName(OtherName);
988 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
989 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
991 // Some ABIs don't have constructor variants. Make sure that base and
992 // complete constructors get mangled the same.
993 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
994 if (!getTarget().getCXXABI().hasConstructorVariants()) {
995 CXXCtorType OrigCtorType = GD.getCtorType();
996 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
997 if (OrigCtorType == Ctor_Base)
998 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1002 const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
1003 // Since CPUSpecific can require multiple emits per decl, store the manglings
1006 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())) {
1007 const auto *SD = FD->getAttr<CPUSpecificAttr>();
1009 std::pair<GlobalDecl, unsigned> SpecCanonicalGD{
1011 SD ? SD->ActiveArgIndex : std::numeric_limits<unsigned>::max()};
1013 auto FoundName = CPUSpecificMangledDeclNames.find(SpecCanonicalGD);
1014 if (FoundName != CPUSpecificMangledDeclNames.end())
1015 return FoundName->second;
1017 auto Result = CPUSpecificManglings.insert(
1018 std::make_pair(getMangledNameImpl(*this, GD, FD), SpecCanonicalGD));
1019 return CPUSpecificMangledDeclNames[SpecCanonicalGD] = Result.first->first();
1022 auto FoundName = MangledDeclNames.find(CanonicalGD);
1023 if (FoundName != MangledDeclNames.end())
1024 return FoundName->second;
1026 // Keep the first result in the case of a mangling collision.
1027 const auto *ND = cast<NamedDecl>(GD.getDecl());
1029 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
1030 return MangledDeclNames[CanonicalGD] = Result.first->first();
1033 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1034 const BlockDecl *BD) {
1035 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1036 const Decl *D = GD.getDecl();
1038 SmallString<256> Buffer;
1039 llvm::raw_svector_ostream Out(Buffer);
1041 MangleCtx.mangleGlobalBlock(BD,
1042 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1043 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1044 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1045 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1046 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1048 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1050 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1051 return Result.first->first();
1054 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1055 return getModule().getNamedValue(Name);
1058 /// AddGlobalCtor - Add a function to the list that will be called before
1060 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1061 llvm::Constant *AssociatedData) {
1062 // FIXME: Type coercion of void()* types.
1063 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1066 /// AddGlobalDtor - Add a function to the list that will be called
1067 /// when the module is unloaded.
1068 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1069 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1070 DtorsUsingAtExit[Priority].push_back(Dtor);
1074 // FIXME: Type coercion of void()* types.
1075 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1078 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1079 if (Fns.empty()) return;
1081 // Ctor function type is void()*.
1082 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1083 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
1085 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1086 llvm::StructType *CtorStructTy = llvm::StructType::get(
1087 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
1089 // Construct the constructor and destructor arrays.
1090 ConstantInitBuilder builder(*this);
1091 auto ctors = builder.beginArray(CtorStructTy);
1092 for (const auto &I : Fns) {
1093 auto ctor = ctors.beginStruct(CtorStructTy);
1094 ctor.addInt(Int32Ty, I.Priority);
1095 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1096 if (I.AssociatedData)
1097 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1099 ctor.addNullPointer(VoidPtrTy);
1100 ctor.finishAndAddTo(ctors);
1104 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1106 llvm::GlobalValue::AppendingLinkage);
1108 // The LTO linker doesn't seem to like it when we set an alignment
1109 // on appending variables. Take it off as a workaround.
1110 list->setAlignment(0);
1115 llvm::GlobalValue::LinkageTypes
1116 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1117 const auto *D = cast<FunctionDecl>(GD.getDecl());
1119 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1121 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1122 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1124 if (isa<CXXConstructorDecl>(D) &&
1125 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1126 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1127 // Our approach to inheriting constructors is fundamentally different from
1128 // that used by the MS ABI, so keep our inheriting constructor thunks
1129 // internal rather than trying to pick an unambiguous mangling for them.
1130 return llvm::GlobalValue::InternalLinkage;
1133 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
1136 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1137 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1138 if (!MDS) return nullptr;
1140 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1143 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
1144 const CGFunctionInfo &Info,
1145 llvm::Function *F) {
1146 unsigned CallingConv;
1147 llvm::AttributeList PAL;
1148 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1149 F->setAttributes(PAL);
1150 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1153 /// Determines whether the language options require us to model
1154 /// unwind exceptions. We treat -fexceptions as mandating this
1155 /// except under the fragile ObjC ABI with only ObjC exceptions
1156 /// enabled. This means, for example, that C with -fexceptions
1158 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1159 // If exceptions are completely disabled, obviously this is false.
1160 if (!LangOpts.Exceptions) return false;
1162 // If C++ exceptions are enabled, this is true.
1163 if (LangOpts.CXXExceptions) return true;
1165 // If ObjC exceptions are enabled, this depends on the ABI.
1166 if (LangOpts.ObjCExceptions) {
1167 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1173 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1174 const CXXMethodDecl *MD) {
1175 // Check that the type metadata can ever actually be used by a call.
1176 if (!CGM.getCodeGenOpts().LTOUnit ||
1177 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1180 // Only functions whose address can be taken with a member function pointer
1181 // need this sort of type metadata.
1182 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1183 !isa<CXXDestructorDecl>(MD);
1186 std::vector<const CXXRecordDecl *>
1187 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1188 llvm::SetVector<const CXXRecordDecl *> MostBases;
1190 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1191 CollectMostBases = [&](const CXXRecordDecl *RD) {
1192 if (RD->getNumBases() == 0)
1193 MostBases.insert(RD);
1194 for (const CXXBaseSpecifier &B : RD->bases())
1195 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1197 CollectMostBases(RD);
1198 return MostBases.takeVector();
1201 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1202 llvm::Function *F) {
1203 llvm::AttrBuilder B;
1205 if (CodeGenOpts.UnwindTables)
1206 B.addAttribute(llvm::Attribute::UWTable);
1208 if (!hasUnwindExceptions(LangOpts))
1209 B.addAttribute(llvm::Attribute::NoUnwind);
1211 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1212 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1213 B.addAttribute(llvm::Attribute::StackProtect);
1214 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1215 B.addAttribute(llvm::Attribute::StackProtectStrong);
1216 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1217 B.addAttribute(llvm::Attribute::StackProtectReq);
1221 // If we don't have a declaration to control inlining, the function isn't
1222 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1223 // disabled, mark the function as noinline.
1224 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1225 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1226 B.addAttribute(llvm::Attribute::NoInline);
1228 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1232 // Track whether we need to add the optnone LLVM attribute,
1233 // starting with the default for this optimization level.
1234 bool ShouldAddOptNone =
1235 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1236 // We can't add optnone in the following cases, it won't pass the verifier.
1237 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1238 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1239 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1241 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
1242 B.addAttribute(llvm::Attribute::OptimizeNone);
1244 // OptimizeNone implies noinline; we should not be inlining such functions.
1245 B.addAttribute(llvm::Attribute::NoInline);
1246 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1247 "OptimizeNone and AlwaysInline on same function!");
1249 // We still need to handle naked functions even though optnone subsumes
1250 // much of their semantics.
1251 if (D->hasAttr<NakedAttr>())
1252 B.addAttribute(llvm::Attribute::Naked);
1254 // OptimizeNone wins over OptimizeForSize and MinSize.
1255 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1256 F->removeFnAttr(llvm::Attribute::MinSize);
1257 } else if (D->hasAttr<NakedAttr>()) {
1258 // Naked implies noinline: we should not be inlining such functions.
1259 B.addAttribute(llvm::Attribute::Naked);
1260 B.addAttribute(llvm::Attribute::NoInline);
1261 } else if (D->hasAttr<NoDuplicateAttr>()) {
1262 B.addAttribute(llvm::Attribute::NoDuplicate);
1263 } else if (D->hasAttr<NoInlineAttr>()) {
1264 B.addAttribute(llvm::Attribute::NoInline);
1265 } else if (D->hasAttr<AlwaysInlineAttr>() &&
1266 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1267 // (noinline wins over always_inline, and we can't specify both in IR)
1268 B.addAttribute(llvm::Attribute::AlwaysInline);
1269 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1270 // If we're not inlining, then force everything that isn't always_inline to
1271 // carry an explicit noinline attribute.
1272 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1273 B.addAttribute(llvm::Attribute::NoInline);
1275 // Otherwise, propagate the inline hint attribute and potentially use its
1276 // absence to mark things as noinline.
1277 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1278 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1279 return Redecl->isInlineSpecified();
1281 B.addAttribute(llvm::Attribute::InlineHint);
1282 } else if (CodeGenOpts.getInlining() ==
1283 CodeGenOptions::OnlyHintInlining &&
1285 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1286 B.addAttribute(llvm::Attribute::NoInline);
1291 // Add other optimization related attributes if we are optimizing this
1293 if (!D->hasAttr<OptimizeNoneAttr>()) {
1294 if (D->hasAttr<ColdAttr>()) {
1295 if (!ShouldAddOptNone)
1296 B.addAttribute(llvm::Attribute::OptimizeForSize);
1297 B.addAttribute(llvm::Attribute::Cold);
1300 if (D->hasAttr<MinSizeAttr>())
1301 B.addAttribute(llvm::Attribute::MinSize);
1304 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1306 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1308 F->setAlignment(alignment);
1310 if (!D->hasAttr<AlignedAttr>())
1311 if (LangOpts.FunctionAlignment)
1312 F->setAlignment(1 << LangOpts.FunctionAlignment);
1314 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1315 // reserve a bit for differentiating between virtual and non-virtual member
1316 // functions. If the current target's C++ ABI requires this and this is a
1317 // member function, set its alignment accordingly.
1318 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1319 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1323 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1324 if (CodeGenOpts.SanitizeCfiCrossDso)
1325 if (auto *FD = dyn_cast<FunctionDecl>(D))
1326 CreateFunctionTypeMetadataForIcall(FD, F);
1328 // Emit type metadata on member functions for member function pointer checks.
1329 // These are only ever necessary on definitions; we're guaranteed that the
1330 // definition will be present in the LTO unit as a result of LTO visibility.
1331 auto *MD = dyn_cast<CXXMethodDecl>(D);
1332 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1333 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1334 llvm::Metadata *Id =
1335 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1336 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1337 F->addTypeMetadata(0, Id);
1342 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1343 const Decl *D = GD.getDecl();
1344 if (dyn_cast_or_null<NamedDecl>(D))
1345 setGVProperties(GV, GD);
1347 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1349 if (D && D->hasAttr<UsedAttr>())
1353 bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1354 llvm::AttrBuilder &Attrs) {
1355 // Add target-cpu and target-features attributes to functions. If
1356 // we have a decl for the function and it has a target attribute then
1357 // parse that and add it to the feature set.
1358 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1359 std::vector<std::string> Features;
1360 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1361 FD = FD ? FD->getMostRecentDecl() : FD;
1362 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1363 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1364 bool AddedAttr = false;
1366 llvm::StringMap<bool> FeatureMap;
1367 getFunctionFeatureMap(FeatureMap, FD);
1369 // Produce the canonical string for this set of features.
1370 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1371 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1373 // Now add the target-cpu and target-features to the function.
1374 // While we populated the feature map above, we still need to
1375 // get and parse the target attribute so we can get the cpu for
1378 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1379 if (ParsedAttr.Architecture != "" &&
1380 getTarget().isValidCPUName(ParsedAttr.Architecture))
1381 TargetCPU = ParsedAttr.Architecture;
1384 // Otherwise just add the existing target cpu and target features to the
1386 Features = getTarget().getTargetOpts().Features;
1389 if (TargetCPU != "") {
1390 Attrs.addAttribute("target-cpu", TargetCPU);
1393 if (!Features.empty()) {
1394 llvm::sort(Features.begin(), Features.end());
1395 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1402 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1403 llvm::GlobalObject *GO) {
1404 const Decl *D = GD.getDecl();
1405 SetCommonAttributes(GD, GO);
1408 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1409 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1410 GV->addAttribute("bss-section", SA->getName());
1411 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1412 GV->addAttribute("data-section", SA->getName());
1413 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1414 GV->addAttribute("rodata-section", SA->getName());
1417 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1418 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1419 if (!D->getAttr<SectionAttr>())
1420 F->addFnAttr("implicit-section-name", SA->getName());
1422 llvm::AttrBuilder Attrs;
1423 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1424 // We know that GetCPUAndFeaturesAttributes will always have the
1425 // newest set, since it has the newest possible FunctionDecl, so the
1426 // new ones should replace the old.
1427 F->removeFnAttr("target-cpu");
1428 F->removeFnAttr("target-features");
1429 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1433 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1434 GO->setSection(CSA->getName());
1435 else if (const auto *SA = D->getAttr<SectionAttr>())
1436 GO->setSection(SA->getName());
1439 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1442 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1444 const CGFunctionInfo &FI) {
1445 const Decl *D = GD.getDecl();
1446 SetLLVMFunctionAttributes(D, FI, F);
1447 SetLLVMFunctionAttributesForDefinition(D, F);
1449 F->setLinkage(llvm::Function::InternalLinkage);
1451 setNonAliasAttributes(GD, F);
1454 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1455 // Set linkage and visibility in case we never see a definition.
1456 LinkageInfo LV = ND->getLinkageAndVisibility();
1457 // Don't set internal linkage on declarations.
1458 // "extern_weak" is overloaded in LLVM; we probably should have
1459 // separate linkage types for this.
1460 if (isExternallyVisible(LV.getLinkage()) &&
1461 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1462 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1465 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1466 llvm::Function *F) {
1467 // Only if we are checking indirect calls.
1468 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1471 // Non-static class methods are handled via vtable or member function pointer
1472 // checks elsewhere.
1473 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1476 // Additionally, if building with cross-DSO support...
1477 if (CodeGenOpts.SanitizeCfiCrossDso) {
1478 // Skip available_externally functions. They won't be codegen'ed in the
1479 // current module anyway.
1480 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1484 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1485 F->addTypeMetadata(0, MD);
1486 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1488 // Emit a hash-based bit set entry for cross-DSO calls.
1489 if (CodeGenOpts.SanitizeCfiCrossDso)
1490 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1491 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1494 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1495 bool IsIncompleteFunction,
1498 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1499 // If this is an intrinsic function, set the function's attributes
1500 // to the intrinsic's attributes.
1501 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1505 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1507 if (!IsIncompleteFunction) {
1508 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1509 // Setup target-specific attributes.
1510 if (F->isDeclaration())
1511 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1514 // Add the Returned attribute for "this", except for iOS 5 and earlier
1515 // where substantial code, including the libstdc++ dylib, was compiled with
1516 // GCC and does not actually return "this".
1517 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1518 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1519 assert(!F->arg_empty() &&
1520 F->arg_begin()->getType()
1521 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1522 "unexpected this return");
1523 F->addAttribute(1, llvm::Attribute::Returned);
1526 // Only a few attributes are set on declarations; these may later be
1527 // overridden by a definition.
1529 setLinkageForGV(F, FD);
1530 setGVProperties(F, FD);
1532 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1533 F->setSection(CSA->getName());
1534 else if (const auto *SA = FD->getAttr<SectionAttr>())
1535 F->setSection(SA->getName());
1537 if (FD->isReplaceableGlobalAllocationFunction()) {
1538 // A replaceable global allocation function does not act like a builtin by
1539 // default, only if it is invoked by a new-expression or delete-expression.
1540 F->addAttribute(llvm::AttributeList::FunctionIndex,
1541 llvm::Attribute::NoBuiltin);
1543 // A sane operator new returns a non-aliasing pointer.
1544 // FIXME: Also add NonNull attribute to the return value
1545 // for the non-nothrow forms?
1546 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1547 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1548 (Kind == OO_New || Kind == OO_Array_New))
1549 F->addAttribute(llvm::AttributeList::ReturnIndex,
1550 llvm::Attribute::NoAlias);
1553 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1554 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1555 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1556 if (MD->isVirtual())
1557 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1559 // Don't emit entries for function declarations in the cross-DSO mode. This
1560 // is handled with better precision by the receiving DSO.
1561 if (!CodeGenOpts.SanitizeCfiCrossDso)
1562 CreateFunctionTypeMetadataForIcall(FD, F);
1564 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1565 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1568 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1569 assert(!GV->isDeclaration() &&
1570 "Only globals with definition can force usage.");
1571 LLVMUsed.emplace_back(GV);
1574 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1575 assert(!GV->isDeclaration() &&
1576 "Only globals with definition can force usage.");
1577 LLVMCompilerUsed.emplace_back(GV);
1580 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1581 std::vector<llvm::WeakTrackingVH> &List) {
1582 // Don't create llvm.used if there is no need.
1586 // Convert List to what ConstantArray needs.
1587 SmallVector<llvm::Constant*, 8> UsedArray;
1588 UsedArray.resize(List.size());
1589 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1591 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1592 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1595 if (UsedArray.empty())
1597 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1599 auto *GV = new llvm::GlobalVariable(
1600 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1601 llvm::ConstantArray::get(ATy, UsedArray), Name);
1603 GV->setSection("llvm.metadata");
1606 void CodeGenModule::emitLLVMUsed() {
1607 emitUsed(*this, "llvm.used", LLVMUsed);
1608 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1611 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1612 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1613 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1616 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1617 llvm::SmallString<32> Opt;
1618 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1619 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1620 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1623 void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1624 auto &C = getLLVMContext();
1625 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1626 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1629 void CodeGenModule::AddDependentLib(StringRef Lib) {
1630 llvm::SmallString<24> Opt;
1631 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1632 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1633 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1636 /// Add link options implied by the given module, including modules
1637 /// it depends on, using a postorder walk.
1638 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1639 SmallVectorImpl<llvm::MDNode *> &Metadata,
1640 llvm::SmallPtrSet<Module *, 16> &Visited) {
1641 // Import this module's parent.
1642 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1643 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1646 // Import this module's dependencies.
1647 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1648 if (Visited.insert(Mod->Imports[I - 1]).second)
1649 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1652 // Add linker options to link against the libraries/frameworks
1653 // described by this module.
1654 llvm::LLVMContext &Context = CGM.getLLVMContext();
1656 // For modules that use export_as for linking, use that module
1658 if (Mod->UseExportAsModuleLinkName)
1661 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1662 // Link against a framework. Frameworks are currently Darwin only, so we
1663 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1664 if (Mod->LinkLibraries[I-1].IsFramework) {
1665 llvm::Metadata *Args[2] = {
1666 llvm::MDString::get(Context, "-framework"),
1667 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1669 Metadata.push_back(llvm::MDNode::get(Context, Args));
1673 // Link against a library.
1674 llvm::SmallString<24> Opt;
1675 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1676 Mod->LinkLibraries[I-1].Library, Opt);
1677 auto *OptString = llvm::MDString::get(Context, Opt);
1678 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1682 void CodeGenModule::EmitModuleLinkOptions() {
1683 // Collect the set of all of the modules we want to visit to emit link
1684 // options, which is essentially the imported modules and all of their
1685 // non-explicit child modules.
1686 llvm::SetVector<clang::Module *> LinkModules;
1687 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1688 SmallVector<clang::Module *, 16> Stack;
1690 // Seed the stack with imported modules.
1691 for (Module *M : ImportedModules) {
1692 // Do not add any link flags when an implementation TU of a module imports
1693 // a header of that same module.
1694 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1695 !getLangOpts().isCompilingModule())
1697 if (Visited.insert(M).second)
1701 // Find all of the modules to import, making a little effort to prune
1702 // non-leaf modules.
1703 while (!Stack.empty()) {
1704 clang::Module *Mod = Stack.pop_back_val();
1706 bool AnyChildren = false;
1708 // Visit the submodules of this module.
1709 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1710 SubEnd = Mod->submodule_end();
1711 Sub != SubEnd; ++Sub) {
1712 // Skip explicit children; they need to be explicitly imported to be
1714 if ((*Sub)->IsExplicit)
1717 if (Visited.insert(*Sub).second) {
1718 Stack.push_back(*Sub);
1723 // We didn't find any children, so add this module to the list of
1724 // modules to link against.
1726 LinkModules.insert(Mod);
1730 // Add link options for all of the imported modules in reverse topological
1731 // order. We don't do anything to try to order import link flags with respect
1732 // to linker options inserted by things like #pragma comment().
1733 SmallVector<llvm::MDNode *, 16> MetadataArgs;
1735 for (Module *M : LinkModules)
1736 if (Visited.insert(M).second)
1737 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1738 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1739 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1741 // Add the linker options metadata flag.
1742 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1743 for (auto *MD : LinkerOptionsMetadata)
1744 NMD->addOperand(MD);
1747 void CodeGenModule::EmitDeferred() {
1748 // Emit code for any potentially referenced deferred decls. Since a
1749 // previously unused static decl may become used during the generation of code
1750 // for a static function, iterate until no changes are made.
1752 if (!DeferredVTables.empty()) {
1753 EmitDeferredVTables();
1755 // Emitting a vtable doesn't directly cause more vtables to
1756 // become deferred, although it can cause functions to be
1757 // emitted that then need those vtables.
1758 assert(DeferredVTables.empty());
1761 // Stop if we're out of both deferred vtables and deferred declarations.
1762 if (DeferredDeclsToEmit.empty())
1765 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1766 // work, it will not interfere with this.
1767 std::vector<GlobalDecl> CurDeclsToEmit;
1768 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1770 for (GlobalDecl &D : CurDeclsToEmit) {
1771 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1772 // to get GlobalValue with exactly the type we need, not something that
1773 // might had been created for another decl with the same mangled name but
1775 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1776 GetAddrOfGlobal(D, ForDefinition));
1778 // In case of different address spaces, we may still get a cast, even with
1779 // IsForDefinition equal to true. Query mangled names table to get
1782 GV = GetGlobalValue(getMangledName(D));
1784 // Make sure GetGlobalValue returned non-null.
1787 // Check to see if we've already emitted this. This is necessary
1788 // for a couple of reasons: first, decls can end up in the
1789 // deferred-decls queue multiple times, and second, decls can end
1790 // up with definitions in unusual ways (e.g. by an extern inline
1791 // function acquiring a strong function redefinition). Just
1792 // ignore these cases.
1793 if (!GV->isDeclaration())
1796 // Otherwise, emit the definition and move on to the next one.
1797 EmitGlobalDefinition(D, GV);
1799 // If we found out that we need to emit more decls, do that recursively.
1800 // This has the advantage that the decls are emitted in a DFS and related
1801 // ones are close together, which is convenient for testing.
1802 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1804 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1809 void CodeGenModule::EmitVTablesOpportunistically() {
1810 // Try to emit external vtables as available_externally if they have emitted
1811 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1812 // is not allowed to create new references to things that need to be emitted
1813 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1815 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1816 && "Only emit opportunistic vtables with optimizations");
1818 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1819 assert(getVTables().isVTableExternal(RD) &&
1820 "This queue should only contain external vtables");
1821 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1822 VTables.GenerateClassData(RD);
1824 OpportunisticVTables.clear();
1827 void CodeGenModule::EmitGlobalAnnotations() {
1828 if (Annotations.empty())
1831 // Create a new global variable for the ConstantStruct in the Module.
1832 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1833 Annotations[0]->getType(), Annotations.size()), Annotations);
1834 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1835 llvm::GlobalValue::AppendingLinkage,
1836 Array, "llvm.global.annotations");
1837 gv->setSection(AnnotationSection);
1840 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1841 llvm::Constant *&AStr = AnnotationStrings[Str];
1845 // Not found yet, create a new global.
1846 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1848 new llvm::GlobalVariable(getModule(), s->getType(), true,
1849 llvm::GlobalValue::PrivateLinkage, s, ".str");
1850 gv->setSection(AnnotationSection);
1851 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1856 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1857 SourceManager &SM = getContext().getSourceManager();
1858 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1860 return EmitAnnotationString(PLoc.getFilename());
1861 return EmitAnnotationString(SM.getBufferName(Loc));
1864 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1865 SourceManager &SM = getContext().getSourceManager();
1866 PresumedLoc PLoc = SM.getPresumedLoc(L);
1867 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1868 SM.getExpansionLineNumber(L);
1869 return llvm::ConstantInt::get(Int32Ty, LineNo);
1872 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1873 const AnnotateAttr *AA,
1875 // Get the globals for file name, annotation, and the line number.
1876 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1877 *UnitGV = EmitAnnotationUnit(L),
1878 *LineNoCst = EmitAnnotationLineNo(L);
1880 // Create the ConstantStruct for the global annotation.
1881 llvm::Constant *Fields[4] = {
1882 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1883 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1884 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1887 return llvm::ConstantStruct::getAnon(Fields);
1890 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1891 llvm::GlobalValue *GV) {
1892 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1893 // Get the struct elements for these annotations.
1894 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1895 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1898 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1900 SourceLocation Loc) const {
1901 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1902 // Blacklist by function name.
1903 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1905 // Blacklist by location.
1907 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
1908 // If location is unknown, this may be a compiler-generated function. Assume
1909 // it's located in the main file.
1910 auto &SM = Context.getSourceManager();
1911 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1912 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1917 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1918 SourceLocation Loc, QualType Ty,
1919 StringRef Category) const {
1920 // For now globals can be blacklisted only in ASan and KASan.
1921 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
1922 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1923 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
1924 if (!EnabledAsanMask)
1926 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1927 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
1929 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1931 // Check global type.
1933 // Drill down the array types: if global variable of a fixed type is
1934 // blacklisted, we also don't instrument arrays of them.
1935 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1936 Ty = AT->getElementType();
1937 Ty = Ty.getCanonicalType().getUnqualifiedType();
1938 // We allow to blacklist only record types (classes, structs etc.)
1939 if (Ty->isRecordType()) {
1940 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1941 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
1948 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1949 StringRef Category) const {
1950 if (!LangOpts.XRayInstrument)
1953 const auto &XRayFilter = getContext().getXRayFilter();
1954 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1955 auto Attr = ImbueAttr::NONE;
1957 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1958 if (Attr == ImbueAttr::NONE)
1959 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1961 case ImbueAttr::NONE:
1963 case ImbueAttr::ALWAYS:
1964 Fn->addFnAttr("function-instrument", "xray-always");
1966 case ImbueAttr::ALWAYS_ARG1:
1967 Fn->addFnAttr("function-instrument", "xray-always");
1968 Fn->addFnAttr("xray-log-args", "1");
1970 case ImbueAttr::NEVER:
1971 Fn->addFnAttr("function-instrument", "xray-never");
1977 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1978 // Never defer when EmitAllDecls is specified.
1979 if (LangOpts.EmitAllDecls)
1982 return getContext().DeclMustBeEmitted(Global);
1985 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1986 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1987 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1988 // Implicit template instantiations may change linkage if they are later
1989 // explicitly instantiated, so they should not be emitted eagerly.
1991 if (const auto *VD = dyn_cast<VarDecl>(Global))
1992 if (Context.getInlineVariableDefinitionKind(VD) ==
1993 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1994 // A definition of an inline constexpr static data member may change
1995 // linkage later if it's redeclared outside the class.
1997 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1998 // codegen for global variables, because they may be marked as threadprivate.
1999 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2000 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2001 !isTypeConstant(Global->getType(), false))
2007 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
2008 const CXXUuidofExpr* E) {
2009 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2011 StringRef Uuid = E->getUuidStr();
2012 std::string Name = "_GUID_" + Uuid.lower();
2013 std::replace(Name.begin(), Name.end(), '-', '_');
2015 // The UUID descriptor should be pointer aligned.
2016 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2018 // Look for an existing global.
2019 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2020 return ConstantAddress(GV, Alignment);
2022 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2023 assert(Init && "failed to initialize as constant");
2025 auto *GV = new llvm::GlobalVariable(
2026 getModule(), Init->getType(),
2027 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2028 if (supportsCOMDAT())
2029 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2031 return ConstantAddress(GV, Alignment);
2034 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2035 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2036 assert(AA && "No alias?");
2038 CharUnits Alignment = getContext().getDeclAlign(VD);
2039 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2041 // See if there is already something with the target's name in the module.
2042 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2044 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2045 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2046 return ConstantAddress(Ptr, Alignment);
2049 llvm::Constant *Aliasee;
2050 if (isa<llvm::FunctionType>(DeclTy))
2051 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2052 GlobalDecl(cast<FunctionDecl>(VD)),
2053 /*ForVTable=*/false);
2055 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2056 llvm::PointerType::getUnqual(DeclTy),
2059 auto *F = cast<llvm::GlobalValue>(Aliasee);
2060 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2061 WeakRefReferences.insert(F);
2063 return ConstantAddress(Aliasee, Alignment);
2066 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2067 const auto *Global = cast<ValueDecl>(GD.getDecl());
2069 // Weak references don't produce any output by themselves.
2070 if (Global->hasAttr<WeakRefAttr>())
2073 // If this is an alias definition (which otherwise looks like a declaration)
2075 if (Global->hasAttr<AliasAttr>())
2076 return EmitAliasDefinition(GD);
2078 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2079 if (Global->hasAttr<IFuncAttr>())
2080 return emitIFuncDefinition(GD);
2082 // If this is a cpu_dispatch multiversion function, emit the resolver.
2083 if (Global->hasAttr<CPUDispatchAttr>())
2084 return emitCPUDispatchDefinition(GD);
2086 // If this is CUDA, be selective about which declarations we emit.
2087 if (LangOpts.CUDA) {
2088 if (LangOpts.CUDAIsDevice) {
2089 if (!Global->hasAttr<CUDADeviceAttr>() &&
2090 !Global->hasAttr<CUDAGlobalAttr>() &&
2091 !Global->hasAttr<CUDAConstantAttr>() &&
2092 !Global->hasAttr<CUDASharedAttr>())
2095 // We need to emit host-side 'shadows' for all global
2096 // device-side variables because the CUDA runtime needs their
2097 // size and host-side address in order to provide access to
2098 // their device-side incarnations.
2100 // So device-only functions are the only things we skip.
2101 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2102 Global->hasAttr<CUDADeviceAttr>())
2105 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2106 "Expected Variable or Function");
2110 if (LangOpts.OpenMP) {
2111 // If this is OpenMP device, check if it is legal to emit this global
2113 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2115 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2116 if (MustBeEmitted(Global))
2117 EmitOMPDeclareReduction(DRD);
2122 // Ignore declarations, they will be emitted on their first use.
2123 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2124 // Forward declarations are emitted lazily on first use.
2125 if (!FD->doesThisDeclarationHaveABody()) {
2126 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2129 StringRef MangledName = getMangledName(GD);
2131 // Compute the function info and LLVM type.
2132 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2133 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2135 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2136 /*DontDefer=*/false);
2140 const auto *VD = cast<VarDecl>(Global);
2141 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2142 // We need to emit device-side global CUDA variables even if a
2143 // variable does not have a definition -- we still need to define
2144 // host-side shadow for it.
2145 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2146 !VD->hasDefinition() &&
2147 (VD->hasAttr<CUDAConstantAttr>() ||
2148 VD->hasAttr<CUDADeviceAttr>());
2149 if (!MustEmitForCuda &&
2150 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2151 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2152 // If this declaration may have caused an inline variable definition to
2153 // change linkage, make sure that it's emitted.
2154 if (Context.getInlineVariableDefinitionKind(VD) ==
2155 ASTContext::InlineVariableDefinitionKind::Strong)
2156 GetAddrOfGlobalVar(VD);
2161 // Defer code generation to first use when possible, e.g. if this is an inline
2162 // function. If the global must always be emitted, do it eagerly if possible
2163 // to benefit from cache locality.
2164 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2165 // Emit the definition if it can't be deferred.
2166 EmitGlobalDefinition(GD);
2170 // If we're deferring emission of a C++ variable with an
2171 // initializer, remember the order in which it appeared in the file.
2172 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2173 cast<VarDecl>(Global)->hasInit()) {
2174 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2175 CXXGlobalInits.push_back(nullptr);
2178 StringRef MangledName = getMangledName(GD);
2179 if (GetGlobalValue(MangledName) != nullptr) {
2180 // The value has already been used and should therefore be emitted.
2181 addDeferredDeclToEmit(GD);
2182 } else if (MustBeEmitted(Global)) {
2183 // The value must be emitted, but cannot be emitted eagerly.
2184 assert(!MayBeEmittedEagerly(Global));
2185 addDeferredDeclToEmit(GD);
2187 // Otherwise, remember that we saw a deferred decl with this name. The
2188 // first use of the mangled name will cause it to move into
2189 // DeferredDeclsToEmit.
2190 DeferredDecls[MangledName] = GD;
2194 // Check if T is a class type with a destructor that's not dllimport.
2195 static bool HasNonDllImportDtor(QualType T) {
2196 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2197 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2198 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2205 struct FunctionIsDirectlyRecursive :
2206 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2207 const StringRef Name;
2208 const Builtin::Context &BI;
2210 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2211 Name(N), BI(C), Result(false) {
2213 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2215 bool TraverseCallExpr(CallExpr *E) {
2216 const FunctionDecl *FD = E->getDirectCallee();
2219 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2220 if (Attr && Name == Attr->getLabel()) {
2224 unsigned BuiltinID = FD->getBuiltinID();
2225 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2227 StringRef BuiltinName = BI.getName(BuiltinID);
2228 if (BuiltinName.startswith("__builtin_") &&
2229 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2237 // Make sure we're not referencing non-imported vars or functions.
2238 struct DLLImportFunctionVisitor
2239 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2240 bool SafeToInline = true;
2242 bool shouldVisitImplicitCode() const { return true; }
2244 bool VisitVarDecl(VarDecl *VD) {
2245 if (VD->getTLSKind()) {
2246 // A thread-local variable cannot be imported.
2247 SafeToInline = false;
2248 return SafeToInline;
2251 // A variable definition might imply a destructor call.
2252 if (VD->isThisDeclarationADefinition())
2253 SafeToInline = !HasNonDllImportDtor(VD->getType());
2255 return SafeToInline;
2258 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2259 if (const auto *D = E->getTemporary()->getDestructor())
2260 SafeToInline = D->hasAttr<DLLImportAttr>();
2261 return SafeToInline;
2264 bool VisitDeclRefExpr(DeclRefExpr *E) {
2265 ValueDecl *VD = E->getDecl();
2266 if (isa<FunctionDecl>(VD))
2267 SafeToInline = VD->hasAttr<DLLImportAttr>();
2268 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2269 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2270 return SafeToInline;
2273 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2274 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2275 return SafeToInline;
2278 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2279 CXXMethodDecl *M = E->getMethodDecl();
2281 // Call through a pointer to member function. This is safe to inline.
2282 SafeToInline = true;
2284 SafeToInline = M->hasAttr<DLLImportAttr>();
2286 return SafeToInline;
2289 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2290 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2291 return SafeToInline;
2294 bool VisitCXXNewExpr(CXXNewExpr *E) {
2295 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2296 return SafeToInline;
2301 // isTriviallyRecursive - Check if this function calls another
2302 // decl that, because of the asm attribute or the other decl being a builtin,
2303 // ends up pointing to itself.
2305 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2307 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2308 // asm labels are a special kind of mangling we have to support.
2309 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2312 Name = Attr->getLabel();
2314 Name = FD->getName();
2317 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2318 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2319 return Walker.Result;
2322 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2323 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2325 const auto *F = cast<FunctionDecl>(GD.getDecl());
2326 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2329 if (F->hasAttr<DLLImportAttr>()) {
2330 // Check whether it would be safe to inline this dllimport function.
2331 DLLImportFunctionVisitor Visitor;
2332 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2333 if (!Visitor.SafeToInline)
2336 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2337 // Implicit destructor invocations aren't captured in the AST, so the
2338 // check above can't see them. Check for them manually here.
2339 for (const Decl *Member : Dtor->getParent()->decls())
2340 if (isa<FieldDecl>(Member))
2341 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2343 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2344 if (HasNonDllImportDtor(B.getType()))
2349 // PR9614. Avoid cases where the source code is lying to us. An available
2350 // externally function should have an equivalent function somewhere else,
2351 // but a function that calls itself is clearly not equivalent to the real
2353 // This happens in glibc's btowc and in some configure checks.
2354 return !isTriviallyRecursive(F);
2357 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2358 return CodeGenOpts.OptimizationLevel > 0;
2361 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2362 const auto *D = cast<ValueDecl>(GD.getDecl());
2364 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2365 Context.getSourceManager(),
2366 "Generating code for declaration");
2368 if (isa<FunctionDecl>(D)) {
2369 // At -O0, don't generate IR for functions with available_externally
2371 if (!shouldEmitFunction(GD))
2374 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2375 // Make sure to emit the definition(s) before we emit the thunks.
2376 // This is necessary for the generation of certain thunks.
2377 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2378 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
2379 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2380 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2382 EmitGlobalFunctionDefinition(GD, GV);
2384 if (Method->isVirtual())
2385 getVTables().EmitThunks(GD);
2390 return EmitGlobalFunctionDefinition(GD, GV);
2393 if (const auto *VD = dyn_cast<VarDecl>(D))
2394 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2396 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2399 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2400 llvm::Function *NewFn);
2403 TargetMVPriority(const TargetInfo &TI,
2404 const CodeGenFunction::MultiVersionResolverOption &RO) {
2405 unsigned Priority = 0;
2406 for (StringRef Feat : RO.Conditions.Features)
2407 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2409 if (!RO.Conditions.Architecture.empty())
2410 Priority = std::max(
2411 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2415 void CodeGenModule::emitMultiVersionFunctions() {
2416 for (GlobalDecl GD : MultiVersionFuncs) {
2417 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2418 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2419 getContext().forEachMultiversionedFunctionVersion(
2420 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2422 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2423 StringRef MangledName = getMangledName(CurGD);
2424 llvm::Constant *Func = GetGlobalValue(MangledName);
2426 if (CurFD->isDefined()) {
2427 EmitGlobalFunctionDefinition(CurGD, nullptr);
2428 Func = GetGlobalValue(MangledName);
2430 const CGFunctionInfo &FI =
2431 getTypes().arrangeGlobalDeclaration(GD);
2432 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2433 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2434 /*DontDefer=*/false, ForDefinition);
2436 assert(Func && "This should have just been created");
2439 const auto *TA = CurFD->getAttr<TargetAttr>();
2440 llvm::SmallVector<StringRef, 8> Feats;
2441 TA->getAddedFeatures(Feats);
2443 Options.emplace_back(cast<llvm::Function>(Func),
2444 TA->getArchitecture(), Feats);
2447 llvm::Function *ResolverFunc = cast<llvm::Function>(
2448 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2449 if (supportsCOMDAT())
2450 ResolverFunc->setComdat(
2451 getModule().getOrInsertComdat(ResolverFunc->getName()));
2453 const TargetInfo &TI = getTarget();
2455 Options.begin(), Options.end(),
2456 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2457 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2458 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2460 CodeGenFunction CGF(*this);
2461 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2465 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2466 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2467 assert(FD && "Not a FunctionDecl?");
2468 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2469 assert(DD && "Not a cpu_dispatch Function?");
2470 QualType CanonTy = Context.getCanonicalType(FD->getType());
2471 llvm::Type *DeclTy = getTypes().ConvertFunctionType(CanonTy, FD);
2473 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2474 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2475 DeclTy = getTypes().GetFunctionType(FInfo);
2478 StringRef ResolverName = getMangledName(GD);
2479 llvm::Type *ResolverType = llvm::FunctionType::get(
2480 llvm::PointerType::get(DeclTy,
2481 Context.getTargetAddressSpace(FD->getType())),
2483 auto *ResolverFunc = cast<llvm::Function>(
2484 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2485 /*ForVTable=*/false));
2487 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2488 const TargetInfo &Target = getTarget();
2489 for (const IdentifierInfo *II : DD->cpus()) {
2490 // Get the name of the target function so we can look it up/create it.
2491 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2492 getCPUSpecificMangling(*this, II->getName());
2493 llvm::Constant *Func = GetOrCreateLLVMFunction(
2494 MangledName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
2495 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2496 llvm::SmallVector<StringRef, 32> Features;
2497 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2498 llvm::transform(Features, Features.begin(),
2499 [](StringRef Str) { return Str.substr(1); });
2500 Features.erase(std::remove_if(
2501 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2502 return !Target.validateCpuSupports(Feat);
2503 }), Features.end());
2504 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
2508 Options.begin(), Options.end(),
2509 [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2510 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2511 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2512 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2515 // If the list contains multiple 'default' versions, such as when it contains
2516 // 'pentium' and 'generic', don't emit the call to the generic one (since we
2517 // always run on at least a 'pentium'). We do this by deleting the 'least
2518 // advanced' (read, lowest mangling letter).
2519 while (Options.size() > 1 &&
2520 CodeGenFunction::GetX86CpuSupportsMask(
2521 (Options.end() - 2)->Conditions.Features) == 0) {
2522 StringRef LHSName = (Options.end() - 2)->Function->getName();
2523 StringRef RHSName = (Options.end() - 1)->Function->getName();
2524 if (LHSName.compare(RHSName) < 0)
2525 Options.erase(Options.end() - 2);
2527 Options.erase(Options.end() - 1);
2530 CodeGenFunction CGF(*this);
2531 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2534 /// If an ifunc for the specified mangled name is not in the module, create and
2535 /// return an llvm IFunc Function with the specified type.
2537 CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2538 const FunctionDecl *FD) {
2539 std::string MangledName =
2540 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2541 std::string IFuncName = MangledName + ".ifunc";
2542 if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2545 // Since this is the first time we've created this IFunc, make sure
2546 // that we put this multiversioned function into the list to be
2547 // replaced later if necessary (target multiversioning only).
2548 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2549 MultiVersionFuncs.push_back(GD);
2551 std::string ResolverName = MangledName + ".resolver";
2552 llvm::Type *ResolverType = llvm::FunctionType::get(
2553 llvm::PointerType::get(DeclTy,
2554 Context.getTargetAddressSpace(FD->getType())),
2556 llvm::Constant *Resolver =
2557 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2558 /*ForVTable=*/false);
2559 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2560 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2561 GIF->setName(IFuncName);
2562 SetCommonAttributes(FD, GIF);
2567 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2568 /// module, create and return an llvm Function with the specified type. If there
2569 /// is something in the module with the specified name, return it potentially
2570 /// bitcasted to the right type.
2572 /// If D is non-null, it specifies a decl that correspond to this. This is used
2573 /// to set the attributes on the function when it is first created.
2574 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2575 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2576 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2577 ForDefinition_t IsForDefinition) {
2578 const Decl *D = GD.getDecl();
2580 // Any attempts to use a MultiVersion function should result in retrieving
2581 // the iFunc instead. Name Mangling will handle the rest of the changes.
2582 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2583 // For the device mark the function as one that should be emitted.
2584 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2585 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
2586 !DontDefer && !IsForDefinition) {
2587 if (const FunctionDecl *FDDef = FD->getDefinition())
2588 if (getContext().DeclMustBeEmitted(FDDef)) {
2590 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2591 GDDef = GlobalDecl(CD, GD.getCtorType());
2592 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2593 GDDef = GlobalDecl(DD, GD.getDtorType());
2595 GDDef = GlobalDecl(FDDef);
2596 addDeferredDeclToEmit(GDDef);
2600 if (FD->isMultiVersion()) {
2601 const auto *TA = FD->getAttr<TargetAttr>();
2602 if (TA && TA->isDefaultVersion())
2603 UpdateMultiVersionNames(GD, FD);
2604 if (!IsForDefinition)
2605 return GetOrCreateMultiVersionIFunc(GD, Ty, FD);
2609 // Lookup the entry, lazily creating it if necessary.
2610 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2612 if (WeakRefReferences.erase(Entry)) {
2613 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2614 if (FD && !FD->hasAttr<WeakAttr>())
2615 Entry->setLinkage(llvm::Function::ExternalLinkage);
2618 // Handle dropped DLL attributes.
2619 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
2620 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2624 // If there are two attempts to define the same mangled name, issue an
2626 if (IsForDefinition && !Entry->isDeclaration()) {
2628 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2629 // to make sure that we issue an error only once.
2630 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2631 (GD.getCanonicalDecl().getDecl() !=
2632 OtherGD.getCanonicalDecl().getDecl()) &&
2633 DiagnosedConflictingDefinitions.insert(GD).second) {
2634 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2636 getDiags().Report(OtherGD.getDecl()->getLocation(),
2637 diag::note_previous_definition);
2641 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2642 (Entry->getType()->getElementType() == Ty)) {
2646 // Make sure the result is of the correct type.
2647 // (If function is requested for a definition, we always need to create a new
2648 // function, not just return a bitcast.)
2649 if (!IsForDefinition)
2650 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2653 // This function doesn't have a complete type (for example, the return
2654 // type is an incomplete struct). Use a fake type instead, and make
2655 // sure not to try to set attributes.
2656 bool IsIncompleteFunction = false;
2658 llvm::FunctionType *FTy;
2659 if (isa<llvm::FunctionType>(Ty)) {
2660 FTy = cast<llvm::FunctionType>(Ty);
2662 FTy = llvm::FunctionType::get(VoidTy, false);
2663 IsIncompleteFunction = true;
2667 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2668 Entry ? StringRef() : MangledName, &getModule());
2670 // If we already created a function with the same mangled name (but different
2671 // type) before, take its name and add it to the list of functions to be
2672 // replaced with F at the end of CodeGen.
2674 // This happens if there is a prototype for a function (e.g. "int f()") and
2675 // then a definition of a different type (e.g. "int f(int x)").
2679 // This might be an implementation of a function without a prototype, in
2680 // which case, try to do special replacement of calls which match the new
2681 // prototype. The really key thing here is that we also potentially drop
2682 // arguments from the call site so as to make a direct call, which makes the
2683 // inliner happier and suppresses a number of optimizer warnings (!) about
2684 // dropping arguments.
2685 if (!Entry->use_empty()) {
2686 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2687 Entry->removeDeadConstantUsers();
2690 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2691 F, Entry->getType()->getElementType()->getPointerTo());
2692 addGlobalValReplacement(Entry, BC);
2695 assert(F->getName() == MangledName && "name was uniqued!");
2697 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2698 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2699 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2700 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2704 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2705 // each other bottoming out with the base dtor. Therefore we emit non-base
2706 // dtors on usage, even if there is no dtor definition in the TU.
2707 if (D && isa<CXXDestructorDecl>(D) &&
2708 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2710 addDeferredDeclToEmit(GD);
2712 // This is the first use or definition of a mangled name. If there is a
2713 // deferred decl with this name, remember that we need to emit it at the end
2715 auto DDI = DeferredDecls.find(MangledName);
2716 if (DDI != DeferredDecls.end()) {
2717 // Move the potentially referenced deferred decl to the
2718 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2719 // don't need it anymore).
2720 addDeferredDeclToEmit(DDI->second);
2721 DeferredDecls.erase(DDI);
2723 // Otherwise, there are cases we have to worry about where we're
2724 // using a declaration for which we must emit a definition but where
2725 // we might not find a top-level definition:
2726 // - member functions defined inline in their classes
2727 // - friend functions defined inline in some class
2728 // - special member functions with implicit definitions
2729 // If we ever change our AST traversal to walk into class methods,
2730 // this will be unnecessary.
2732 // We also don't emit a definition for a function if it's going to be an
2733 // entry in a vtable, unless it's already marked as used.
2734 } else if (getLangOpts().CPlusPlus && D) {
2735 // Look for a declaration that's lexically in a record.
2736 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2737 FD = FD->getPreviousDecl()) {
2738 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2739 if (FD->doesThisDeclarationHaveABody()) {
2740 addDeferredDeclToEmit(GD.getWithDecl(FD));
2748 // Make sure the result is of the requested type.
2749 if (!IsIncompleteFunction) {
2750 assert(F->getType()->getElementType() == Ty);
2754 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2755 return llvm::ConstantExpr::getBitCast(F, PTy);
2758 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2759 /// non-null, then this function will use the specified type if it has to
2760 /// create it (this occurs when we see a definition of the function).
2761 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2765 ForDefinition_t IsForDefinition) {
2766 // If there was no specific requested type, just convert it now.
2768 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2769 auto CanonTy = Context.getCanonicalType(FD->getType());
2770 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2773 // Devirtualized destructor calls may come through here instead of via
2774 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2775 // of the complete destructor when necessary.
2776 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2777 if (getTarget().getCXXABI().isMicrosoft() &&
2778 GD.getDtorType() == Dtor_Complete &&
2779 DD->getParent()->getNumVBases() == 0)
2780 GD = GlobalDecl(DD, Dtor_Base);
2783 StringRef MangledName = getMangledName(GD);
2784 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2785 /*IsThunk=*/false, llvm::AttributeList(),
2789 static const FunctionDecl *
2790 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2791 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2792 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2794 IdentifierInfo &CII = C.Idents.get(Name);
2795 for (const auto &Result : DC->lookup(&CII))
2796 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2799 if (!C.getLangOpts().CPlusPlus)
2802 // Demangle the premangled name from getTerminateFn()
2803 IdentifierInfo &CXXII =
2804 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
2805 ? C.Idents.get("terminate")
2806 : C.Idents.get(Name);
2808 for (const auto &N : {"__cxxabiv1", "std"}) {
2809 IdentifierInfo &NS = C.Idents.get(N);
2810 for (const auto &Result : DC->lookup(&NS)) {
2811 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2812 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2813 for (const auto &Result : LSD->lookup(&NS))
2814 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2818 for (const auto &Result : ND->lookup(&CXXII))
2819 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2827 /// CreateRuntimeFunction - Create a new runtime function with the specified
2830 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2831 llvm::AttributeList ExtraAttrs,
2834 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2835 /*DontDefer=*/false, /*IsThunk=*/false,
2838 if (auto *F = dyn_cast<llvm::Function>(C)) {
2840 F->setCallingConv(getRuntimeCC());
2842 if (!Local && getTriple().isOSBinFormatCOFF() &&
2843 !getCodeGenOpts().LTOVisibilityPublicStd &&
2844 !getTriple().isWindowsGNUEnvironment()) {
2845 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2846 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2847 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2848 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2858 /// CreateBuiltinFunction - Create a new builtin function with the specified
2861 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2862 llvm::AttributeList ExtraAttrs) {
2863 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
2866 /// isTypeConstant - Determine whether an object of this type can be emitted
2869 /// If ExcludeCtor is true, the duration when the object's constructor runs
2870 /// will not be considered. The caller will need to verify that the object is
2871 /// not written to during its construction.
2872 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2873 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2876 if (Context.getLangOpts().CPlusPlus) {
2877 if (const CXXRecordDecl *Record
2878 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2879 return ExcludeCtor && !Record->hasMutableFields() &&
2880 Record->hasTrivialDestructor();
2886 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2887 /// create and return an llvm GlobalVariable with the specified type. If there
2888 /// is something in the module with the specified name, return it potentially
2889 /// bitcasted to the right type.
2891 /// If D is non-null, it specifies a decl that correspond to this. This is used
2892 /// to set the attributes on the global when it is first created.
2894 /// If IsForDefinition is true, it is guaranteed that an actual global with
2895 /// type Ty will be returned, not conversion of a variable with the same
2896 /// mangled name but some other type.
2898 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2899 llvm::PointerType *Ty,
2901 ForDefinition_t IsForDefinition) {
2902 // Lookup the entry, lazily creating it if necessary.
2903 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2905 if (WeakRefReferences.erase(Entry)) {
2906 if (D && !D->hasAttr<WeakAttr>())
2907 Entry->setLinkage(llvm::Function::ExternalLinkage);
2910 // Handle dropped DLL attributes.
2911 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2912 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2914 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2915 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2917 if (Entry->getType() == Ty)
2920 // If there are two attempts to define the same mangled name, issue an
2922 if (IsForDefinition && !Entry->isDeclaration()) {
2924 const VarDecl *OtherD;
2926 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2927 // to make sure that we issue an error only once.
2928 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2929 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2930 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2931 OtherD->hasInit() &&
2932 DiagnosedConflictingDefinitions.insert(D).second) {
2933 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2935 getDiags().Report(OtherGD.getDecl()->getLocation(),
2936 diag::note_previous_definition);
2940 // Make sure the result is of the correct type.
2941 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2942 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2944 // (If global is requested for a definition, we always need to create a new
2945 // global, not just return a bitcast.)
2946 if (!IsForDefinition)
2947 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2950 auto AddrSpace = GetGlobalVarAddressSpace(D);
2951 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2953 auto *GV = new llvm::GlobalVariable(
2954 getModule(), Ty->getElementType(), false,
2955 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2956 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2958 // If we already created a global with the same mangled name (but different
2959 // type) before, take its name and remove it from its parent.
2961 GV->takeName(Entry);
2963 if (!Entry->use_empty()) {
2964 llvm::Constant *NewPtrForOldDecl =
2965 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2966 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2969 Entry->eraseFromParent();
2972 // This is the first use or definition of a mangled name. If there is a
2973 // deferred decl with this name, remember that we need to emit it at the end
2975 auto DDI = DeferredDecls.find(MangledName);
2976 if (DDI != DeferredDecls.end()) {
2977 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2978 // list, and remove it from DeferredDecls (since we don't need it anymore).
2979 addDeferredDeclToEmit(DDI->second);
2980 DeferredDecls.erase(DDI);
2983 // Handle things which are present even on external declarations.
2985 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
2986 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
2988 // FIXME: This code is overly simple and should be merged with other global
2990 GV->setConstant(isTypeConstant(D->getType(), false));
2992 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2994 setLinkageForGV(GV, D);
2996 if (D->getTLSKind()) {
2997 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2998 CXXThreadLocals.push_back(D);
3002 setGVProperties(GV, D);
3004 // If required by the ABI, treat declarations of static data members with
3005 // inline initializers as definitions.
3006 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3007 EmitGlobalVarDefinition(D);
3010 // Emit section information for extern variables.
3011 if (D->hasExternalStorage()) {
3012 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3013 GV->setSection(SA->getName());
3016 // Handle XCore specific ABI requirements.
3017 if (getTriple().getArch() == llvm::Triple::xcore &&
3018 D->getLanguageLinkage() == CLanguageLinkage &&
3019 D->getType().isConstant(Context) &&
3020 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3021 GV->setSection(".cp.rodata");
3023 // Check if we a have a const declaration with an initializer, we may be
3024 // able to emit it as available_externally to expose it's value to the
3026 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3027 D->getType().isConstQualified() && !GV->hasInitializer() &&
3028 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3029 const auto *Record =
3030 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3031 bool HasMutableFields = Record && Record->hasMutableFields();
3032 if (!HasMutableFields) {
3033 const VarDecl *InitDecl;
3034 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3036 ConstantEmitter emitter(*this);
3037 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3039 auto *InitType = Init->getType();
3040 if (GV->getType()->getElementType() != InitType) {
3041 // The type of the initializer does not match the definition.
3042 // This happens when an initializer has a different type from
3043 // the type of the global (because of padding at the end of a
3044 // structure for instance).
3045 GV->setName(StringRef());
3046 // Make a new global with the correct type, this is now guaranteed
3048 auto *NewGV = cast<llvm::GlobalVariable>(
3049 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3051 // Erase the old global, since it is no longer used.
3052 GV->eraseFromParent();
3055 GV->setInitializer(Init);
3056 GV->setConstant(true);
3057 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3059 emitter.finalize(GV);
3067 D ? D->getType().getAddressSpace()
3068 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3069 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3070 Ty->getPointerAddressSpace());
3071 if (AddrSpace != ExpectedAS)
3072 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3079 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
3080 ForDefinition_t IsForDefinition) {
3081 const Decl *D = GD.getDecl();
3082 if (isa<CXXConstructorDecl>(D))
3083 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
3084 getFromCtorType(GD.getCtorType()),
3085 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3086 /*DontDefer=*/false, IsForDefinition);
3087 else if (isa<CXXDestructorDecl>(D))
3088 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
3089 getFromDtorType(GD.getDtorType()),
3090 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3091 /*DontDefer=*/false, IsForDefinition);
3092 else if (isa<CXXMethodDecl>(D)) {
3093 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3094 cast<CXXMethodDecl>(D));
3095 auto Ty = getTypes().GetFunctionType(*FInfo);
3096 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3098 } else if (isa<FunctionDecl>(D)) {
3099 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3100 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3101 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3104 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3108 llvm::GlobalVariable *
3109 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
3111 llvm::GlobalValue::LinkageTypes Linkage) {
3112 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3113 llvm::GlobalVariable *OldGV = nullptr;
3116 // Check if the variable has the right type.
3117 if (GV->getType()->getElementType() == Ty)
3120 // Because C++ name mangling, the only way we can end up with an already
3121 // existing global with the same name is if it has been declared extern "C".
3122 assert(GV->isDeclaration() && "Declaration has wrong type!");
3126 // Create a new variable.
3127 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3128 Linkage, nullptr, Name);
3131 // Replace occurrences of the old variable if needed.
3132 GV->takeName(OldGV);
3134 if (!OldGV->use_empty()) {
3135 llvm::Constant *NewPtrForOldDecl =
3136 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3137 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3140 OldGV->eraseFromParent();
3143 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3144 !GV->hasAvailableExternallyLinkage())
3145 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3150 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3151 /// given global variable. If Ty is non-null and if the global doesn't exist,
3152 /// then it will be created with the specified type instead of whatever the
3153 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3154 /// that an actual global with type Ty will be returned, not conversion of a
3155 /// variable with the same mangled name but some other type.
3156 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3158 ForDefinition_t IsForDefinition) {
3159 assert(D->hasGlobalStorage() && "Not a global variable");
3160 QualType ASTTy = D->getType();
3162 Ty = getTypes().ConvertTypeForMem(ASTTy);
3164 llvm::PointerType *PTy =
3165 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3167 StringRef MangledName = getMangledName(D);
3168 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3171 /// CreateRuntimeVariable - Create a new runtime global variable with the
3172 /// specified type and name.
3174 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3177 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3178 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3182 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3183 assert(!D->getInit() && "Cannot emit definite definitions here!");
3185 StringRef MangledName = getMangledName(D);
3186 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3188 // We already have a definition, not declaration, with the same mangled name.
3189 // Emitting of declaration is not required (and actually overwrites emitted
3191 if (GV && !GV->isDeclaration())
3194 // If we have not seen a reference to this variable yet, place it into the
3195 // deferred declarations table to be emitted if needed later.
3196 if (!MustBeEmitted(D) && !GV) {
3197 DeferredDecls[MangledName] = D;
3201 // The tentative definition is the only definition.
3202 EmitGlobalVarDefinition(D);
3205 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3206 return Context.toCharUnitsFromBits(
3207 getDataLayout().getTypeStoreSizeInBits(Ty));
3210 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3211 LangAS AddrSpace = LangAS::Default;
3212 if (LangOpts.OpenCL) {
3213 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3214 assert(AddrSpace == LangAS::opencl_global ||
3215 AddrSpace == LangAS::opencl_constant ||
3216 AddrSpace == LangAS::opencl_local ||
3217 AddrSpace >= LangAS::FirstTargetAddressSpace);
3221 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3222 if (D && D->hasAttr<CUDAConstantAttr>())
3223 return LangAS::cuda_constant;
3224 else if (D && D->hasAttr<CUDASharedAttr>())
3225 return LangAS::cuda_shared;
3226 else if (D && D->hasAttr<CUDADeviceAttr>())
3227 return LangAS::cuda_device;
3228 else if (D && D->getType().isConstQualified())
3229 return LangAS::cuda_constant;
3231 return LangAS::cuda_device;
3234 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3237 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3238 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3239 if (LangOpts.OpenCL)
3240 return LangAS::opencl_constant;
3241 if (auto AS = getTarget().getConstantAddressSpace())
3242 return AS.getValue();
3243 return LangAS::Default;
3246 // In address space agnostic languages, string literals are in default address
3247 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3248 // emitted in constant address space in LLVM IR. To be consistent with other
3249 // parts of AST, string literal global variables in constant address space
3250 // need to be casted to default address space before being put into address
3251 // map and referenced by other part of CodeGen.
3252 // In OpenCL, string literals are in constant address space in AST, therefore
3253 // they should not be casted to default address space.
3254 static llvm::Constant *
3255 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3256 llvm::GlobalVariable *GV) {
3257 llvm::Constant *Cast = GV;
3258 if (!CGM.getLangOpts().OpenCL) {
3259 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3260 if (AS != LangAS::Default)
3261 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3262 CGM, GV, AS.getValue(), LangAS::Default,
3263 GV->getValueType()->getPointerTo(
3264 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3270 template<typename SomeDecl>
3271 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3272 llvm::GlobalValue *GV) {
3273 if (!getLangOpts().CPlusPlus)
3276 // Must have 'used' attribute, or else inline assembly can't rely on
3277 // the name existing.
3278 if (!D->template hasAttr<UsedAttr>())
3281 // Must have internal linkage and an ordinary name.
3282 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3285 // Must be in an extern "C" context. Entities declared directly within
3286 // a record are not extern "C" even if the record is in such a context.
3287 const SomeDecl *First = D->getFirstDecl();
3288 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3291 // OK, this is an internal linkage entity inside an extern "C" linkage
3292 // specification. Make a note of that so we can give it the "expected"
3293 // mangled name if nothing else is using that name.
3294 std::pair<StaticExternCMap::iterator, bool> R =
3295 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3297 // If we have multiple internal linkage entities with the same name
3298 // in extern "C" regions, none of them gets that name.
3300 R.first->second = nullptr;
3303 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3304 if (!CGM.supportsCOMDAT())
3307 if (D.hasAttr<SelectAnyAttr>())
3311 if (auto *VD = dyn_cast<VarDecl>(&D))
3312 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3314 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3318 case GVA_AvailableExternally:
3319 case GVA_StrongExternal:
3321 case GVA_DiscardableODR:
3325 llvm_unreachable("No such linkage");
3328 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3329 llvm::GlobalObject &GO) {
3330 if (!shouldBeInCOMDAT(*this, D))
3332 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3335 /// Pass IsTentative as true if you want to create a tentative definition.
3336 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3338 // OpenCL global variables of sampler type are translated to function calls,
3339 // therefore no need to be translated.
3340 QualType ASTTy = D->getType();
3341 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3344 // If this is OpenMP device, check if it is legal to emit this global
3346 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3347 OpenMPRuntime->emitTargetGlobalVariable(D))
3350 llvm::Constant *Init = nullptr;
3351 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3352 bool NeedsGlobalCtor = false;
3353 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3355 const VarDecl *InitDecl;
3356 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3358 Optional<ConstantEmitter> emitter;
3360 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3361 // as part of their declaration." Sema has already checked for
3362 // error cases, so we just need to set Init to UndefValue.
3363 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3364 D->hasAttr<CUDASharedAttr>())
3365 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3366 else if (!InitExpr) {
3367 // This is a tentative definition; tentative definitions are
3368 // implicitly initialized with { 0 }.
3370 // Note that tentative definitions are only emitted at the end of
3371 // a translation unit, so they should never have incomplete
3372 // type. In addition, EmitTentativeDefinition makes sure that we
3373 // never attempt to emit a tentative definition if a real one
3374 // exists. A use may still exists, however, so we still may need
3376 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3377 Init = EmitNullConstant(D->getType());
3379 initializedGlobalDecl = GlobalDecl(D);
3380 emitter.emplace(*this);
3381 Init = emitter->tryEmitForInitializer(*InitDecl);
3384 QualType T = InitExpr->getType();
3385 if (D->getType()->isReferenceType())
3388 if (getLangOpts().CPlusPlus) {
3389 Init = EmitNullConstant(T);
3390 NeedsGlobalCtor = true;
3392 ErrorUnsupported(D, "static initializer");
3393 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3396 // We don't need an initializer, so remove the entry for the delayed
3397 // initializer position (just in case this entry was delayed) if we
3398 // also don't need to register a destructor.
3399 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3400 DelayedCXXInitPosition.erase(D);
3404 llvm::Type* InitType = Init->getType();
3405 llvm::Constant *Entry =
3406 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3408 // Strip off a bitcast if we got one back.
3409 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3410 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3411 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3412 // All zero index gep.
3413 CE->getOpcode() == llvm::Instruction::GetElementPtr);
3414 Entry = CE->getOperand(0);
3417 // Entry is now either a Function or GlobalVariable.
3418 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3420 // We have a definition after a declaration with the wrong type.
3421 // We must make a new GlobalVariable* and update everything that used OldGV
3422 // (a declaration or tentative definition) with the new GlobalVariable*
3423 // (which will be a definition).
3425 // This happens if there is a prototype for a global (e.g.
3426 // "extern int x[];") and then a definition of a different type (e.g.
3427 // "int x[10];"). This also happens when an initializer has a different type
3428 // from the type of the global (this happens with unions).
3429 if (!GV || GV->getType()->getElementType() != InitType ||
3430 GV->getType()->getAddressSpace() !=
3431 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3433 // Move the old entry aside so that we'll create a new one.
3434 Entry->setName(StringRef());
3436 // Make a new global with the correct type, this is now guaranteed to work.
3437 GV = cast<llvm::GlobalVariable>(
3438 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3440 // Replace all uses of the old global with the new global
3441 llvm::Constant *NewPtrForOldDecl =
3442 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3443 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3445 // Erase the old global, since it is no longer used.
3446 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3449 MaybeHandleStaticInExternC(D, GV);
3451 if (D->hasAttr<AnnotateAttr>())
3452 AddGlobalAnnotations(D, GV);
3454 // Set the llvm linkage type as appropriate.
3455 llvm::GlobalValue::LinkageTypes Linkage =
3456 getLLVMLinkageVarDefinition(D, GV->isConstant());
3458 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3459 // the device. [...]"
3460 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3461 // __device__, declares a variable that: [...]
3462 // Is accessible from all the threads within the grid and from the host
3463 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3464 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3465 if (GV && LangOpts.CUDA) {
3466 if (LangOpts.CUDAIsDevice) {
3467 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3468 GV->setExternallyInitialized(true);
3470 // Host-side shadows of external declarations of device-side
3471 // global variables become internal definitions. These have to
3472 // be internal in order to prevent name conflicts with global
3473 // host variables with the same name in a different TUs.
3474 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3475 Linkage = llvm::GlobalValue::InternalLinkage;
3477 // Shadow variables and their properties must be registered
3478 // with CUDA runtime.
3480 if (!D->hasDefinition())
3481 Flags |= CGCUDARuntime::ExternDeviceVar;
3482 if (D->hasAttr<CUDAConstantAttr>())
3483 Flags |= CGCUDARuntime::ConstantDeviceVar;
3484 getCUDARuntime().registerDeviceVar(*GV, Flags);
3485 } else if (D->hasAttr<CUDASharedAttr>())
3486 // __shared__ variables are odd. Shadows do get created, but
3487 // they are not registered with the CUDA runtime, so they
3488 // can't really be used to access their device-side
3489 // counterparts. It's not clear yet whether it's nvcc's bug or
3490 // a feature, but we've got to do the same for compatibility.
3491 Linkage = llvm::GlobalValue::InternalLinkage;
3495 GV->setInitializer(Init);
3496 if (emitter) emitter->finalize(GV);
3498 // If it is safe to mark the global 'constant', do so now.
3499 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3500 isTypeConstant(D->getType(), true));
3502 // If it is in a read-only section, mark it 'constant'.
3503 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3504 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3505 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3506 GV->setConstant(true);
3509 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3512 // On Darwin, if the normal linkage of a C++ thread_local variable is
3513 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3514 // copies within a linkage unit; otherwise, the backing variable has
3515 // internal linkage and all accesses should just be calls to the
3516 // Itanium-specified entry point, which has the normal linkage of the
3517 // variable. This is to preserve the ability to change the implementation
3518 // behind the scenes.
3519 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
3520 Context.getTargetInfo().getTriple().isOSDarwin() &&
3521 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3522 !llvm::GlobalVariable::isWeakLinkage(Linkage))
3523 Linkage = llvm::GlobalValue::InternalLinkage;
3525 GV->setLinkage(Linkage);
3526 if (D->hasAttr<DLLImportAttr>())
3527 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3528 else if (D->hasAttr<DLLExportAttr>())
3529 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3531 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3533 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3534 // common vars aren't constant even if declared const.
3535 GV->setConstant(false);
3536 // Tentative definition of global variables may be initialized with
3537 // non-zero null pointers. In this case they should have weak linkage
3538 // since common linkage must have zero initializer and must not have
3539 // explicit section therefore cannot have non-zero initial value.
3540 if (!GV->getInitializer()->isNullValue())
3541 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3544 setNonAliasAttributes(D, GV);
3546 if (D->getTLSKind() && !GV->isThreadLocal()) {
3547 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3548 CXXThreadLocals.push_back(D);
3552 maybeSetTrivialComdat(*D, *GV);
3554 // Emit the initializer function if necessary.
3555 if (NeedsGlobalCtor || NeedsGlobalDtor)
3556 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3558 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3560 // Emit global variable debug information.
3561 if (CGDebugInfo *DI = getModuleDebugInfo())
3562 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3563 DI->EmitGlobalVariable(GV, D);
3566 static bool isVarDeclStrongDefinition(const ASTContext &Context,
3567 CodeGenModule &CGM, const VarDecl *D,
3569 // Don't give variables common linkage if -fno-common was specified unless it
3570 // was overridden by a NoCommon attribute.
3571 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3575 // A declaration of an identifier for an object that has file scope without
3576 // an initializer, and without a storage-class specifier or with the
3577 // storage-class specifier static, constitutes a tentative definition.
3578 if (D->getInit() || D->hasExternalStorage())
3581 // A variable cannot be both common and exist in a section.
3582 if (D->hasAttr<SectionAttr>())
3585 // A variable cannot be both common and exist in a section.
3586 // We don't try to determine which is the right section in the front-end.
3587 // If no specialized section name is applicable, it will resort to default.
3588 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3589 D->hasAttr<PragmaClangDataSectionAttr>() ||
3590 D->hasAttr<PragmaClangRodataSectionAttr>())
3593 // Thread local vars aren't considered common linkage.
3594 if (D->getTLSKind())
3597 // Tentative definitions marked with WeakImportAttr are true definitions.
3598 if (D->hasAttr<WeakImportAttr>())
3601 // A variable cannot be both common and exist in a comdat.
3602 if (shouldBeInCOMDAT(CGM, *D))
3605 // Declarations with a required alignment do not have common linkage in MSVC
3607 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3608 if (D->hasAttr<AlignedAttr>())
3610 QualType VarType = D->getType();
3611 if (Context.isAlignmentRequired(VarType))
3614 if (const auto *RT = VarType->getAs<RecordType>()) {
3615 const RecordDecl *RD = RT->getDecl();
3616 for (const FieldDecl *FD : RD->fields()) {
3617 if (FD->isBitField())
3619 if (FD->hasAttr<AlignedAttr>())
3621 if (Context.isAlignmentRequired(FD->getType()))
3630 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
3631 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
3632 if (Linkage == GVA_Internal)
3633 return llvm::Function::InternalLinkage;
3635 if (D->hasAttr<WeakAttr>()) {
3636 if (IsConstantVariable)
3637 return llvm::GlobalVariable::WeakODRLinkage;
3639 return llvm::GlobalVariable::WeakAnyLinkage;
3642 // We are guaranteed to have a strong definition somewhere else,
3643 // so we can use available_externally linkage.
3644 if (Linkage == GVA_AvailableExternally)
3645 return llvm::GlobalValue::AvailableExternallyLinkage;
3647 // Note that Apple's kernel linker doesn't support symbol
3648 // coalescing, so we need to avoid linkonce and weak linkages there.
3649 // Normally, this means we just map to internal, but for explicit
3650 // instantiations we'll map to external.
3652 // In C++, the compiler has to emit a definition in every translation unit
3653 // that references the function. We should use linkonce_odr because
3654 // a) if all references in this translation unit are optimized away, we
3655 // don't need to codegen it. b) if the function persists, it needs to be
3656 // merged with other definitions. c) C++ has the ODR, so we know the
3657 // definition is dependable.
3658 if (Linkage == GVA_DiscardableODR)
3659 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3660 : llvm::Function::InternalLinkage;
3662 // An explicit instantiation of a template has weak linkage, since
3663 // explicit instantiations can occur in multiple translation units
3664 // and must all be equivalent. However, we are not allowed to
3665 // throw away these explicit instantiations.
3667 // We don't currently support CUDA device code spread out across multiple TUs,
3668 // so say that CUDA templates are either external (for kernels) or internal.
3669 // This lets llvm perform aggressive inter-procedural optimizations.
3670 if (Linkage == GVA_StrongODR) {
3671 if (Context.getLangOpts().AppleKext)
3672 return llvm::Function::ExternalLinkage;
3673 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3674 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3675 : llvm::Function::InternalLinkage;
3676 return llvm::Function::WeakODRLinkage;
3679 // C++ doesn't have tentative definitions and thus cannot have common
3681 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3682 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
3683 CodeGenOpts.NoCommon))
3684 return llvm::GlobalVariable::CommonLinkage;
3686 // selectany symbols are externally visible, so use weak instead of
3687 // linkonce. MSVC optimizes away references to const selectany globals, so
3688 // all definitions should be the same and ODR linkage should be used.
3689 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3690 if (D->hasAttr<SelectAnyAttr>())
3691 return llvm::GlobalVariable::WeakODRLinkage;
3693 // Otherwise, we have strong external linkage.
3694 assert(Linkage == GVA_StrongExternal);
3695 return llvm::GlobalVariable::ExternalLinkage;
3698 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3699 const VarDecl *VD, bool IsConstant) {
3700 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
3701 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
3704 /// Replace the uses of a function that was declared with a non-proto type.
3705 /// We want to silently drop extra arguments from call sites
3706 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3707 llvm::Function *newFn) {
3709 if (old->use_empty()) return;
3711 llvm::Type *newRetTy = newFn->getReturnType();
3712 SmallVector<llvm::Value*, 4> newArgs;
3713 SmallVector<llvm::OperandBundleDef, 1> newBundles;
3715 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3717 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
3718 llvm::User *user = use->getUser();
3720 // Recognize and replace uses of bitcasts. Most calls to
3721 // unprototyped functions will use bitcasts.
3722 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3723 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3724 replaceUsesOfNonProtoConstant(bitcast, newFn);
3728 // Recognize calls to the function.
3729 llvm::CallSite callSite(user);
3730 if (!callSite) continue;
3731 if (!callSite.isCallee(&*use)) continue;
3733 // If the return types don't match exactly, then we can't
3734 // transform this call unless it's dead.
3735 if (callSite->getType() != newRetTy && !callSite->use_empty())
3738 // Get the call site's attribute list.
3739 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3740 llvm::AttributeList oldAttrs = callSite.getAttributes();
3742 // If the function was passed too few arguments, don't transform.
3743 unsigned newNumArgs = newFn->arg_size();
3744 if (callSite.arg_size() < newNumArgs) continue;
3746 // If extra arguments were passed, we silently drop them.
3747 // If any of the types mismatch, we don't transform.
3749 bool dontTransform = false;
3750 for (llvm::Argument &A : newFn->args()) {
3751 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3752 dontTransform = true;
3756 // Add any parameter attributes.
3757 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3763 // Okay, we can transform this. Create the new call instruction and copy
3764 // over the required information.
3765 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3767 // Copy over any operand bundles.
3768 callSite.getOperandBundlesAsDefs(newBundles);
3770 llvm::CallSite newCall;
3771 if (callSite.isCall()) {
3772 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3773 callSite.getInstruction());
3775 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3776 newCall = llvm::InvokeInst::Create(newFn,
3777 oldInvoke->getNormalDest(),
3778 oldInvoke->getUnwindDest(),
3779 newArgs, newBundles, "",
3780 callSite.getInstruction());
3782 newArgs.clear(); // for the next iteration
3784 if (!newCall->getType()->isVoidTy())
3785 newCall->takeName(callSite.getInstruction());
3786 newCall.setAttributes(llvm::AttributeList::get(
3787 newFn->getContext(), oldAttrs.getFnAttributes(),
3788 oldAttrs.getRetAttributes(), newArgAttrs));
3789 newCall.setCallingConv(callSite.getCallingConv());
3791 // Finally, remove the old call, replacing any uses with the new one.
3792 if (!callSite->use_empty())
3793 callSite->replaceAllUsesWith(newCall.getInstruction());
3795 // Copy debug location attached to CI.
3796 if (callSite->getDebugLoc())
3797 newCall->setDebugLoc(callSite->getDebugLoc());
3799 callSite->eraseFromParent();
3803 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3804 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3805 /// existing call uses of the old function in the module, this adjusts them to
3806 /// call the new function directly.
3808 /// This is not just a cleanup: the always_inline pass requires direct calls to
3809 /// functions to be able to inline them. If there is a bitcast in the way, it
3810 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3812 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3813 llvm::Function *NewFn) {
3814 // If we're redefining a global as a function, don't transform it.
3815 if (!isa<llvm::Function>(Old)) return;
3817 replaceUsesOfNonProtoConstant(Old, NewFn);
3820 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3821 auto DK = VD->isThisDeclarationADefinition();
3822 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3825 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3826 // If we have a definition, this might be a deferred decl. If the
3827 // instantiation is explicit, make sure we emit it at the end.
3828 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3829 GetAddrOfGlobalVar(VD);
3831 EmitTopLevelDecl(VD);
3834 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3835 llvm::GlobalValue *GV) {
3836 const auto *D = cast<FunctionDecl>(GD.getDecl());
3838 // Compute the function info and LLVM type.
3839 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3840 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3842 // Get or create the prototype for the function.
3843 if (!GV || (GV->getType()->getElementType() != Ty))
3844 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3849 if (!GV->isDeclaration())
3852 // We need to set linkage and visibility on the function before
3853 // generating code for it because various parts of IR generation
3854 // want to propagate this information down (e.g. to local static
3856 auto *Fn = cast<llvm::Function>(GV);
3857 setFunctionLinkage(GD, Fn);
3859 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3860 setGVProperties(Fn, GD);
3862 MaybeHandleStaticInExternC(D, Fn);
3865 maybeSetTrivialComdat(*D, *Fn);
3867 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3869 setNonAliasAttributes(GD, Fn);
3870 SetLLVMFunctionAttributesForDefinition(D, Fn);
3872 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3873 AddGlobalCtor(Fn, CA->getPriority());
3874 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3875 AddGlobalDtor(Fn, DA->getPriority());
3876 if (D->hasAttr<AnnotateAttr>())
3877 AddGlobalAnnotations(D, Fn);
3879 if (D->isCPUSpecificMultiVersion()) {
3880 auto *Spec = D->getAttr<CPUSpecificAttr>();
3881 // If there is another specific version we need to emit, do so here.
3882 if (Spec->ActiveArgIndex + 1 < Spec->cpus_size()) {
3883 ++Spec->ActiveArgIndex;
3884 EmitGlobalFunctionDefinition(GD, nullptr);
3889 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3890 const auto *D = cast<ValueDecl>(GD.getDecl());
3891 const AliasAttr *AA = D->getAttr<AliasAttr>();
3892 assert(AA && "Not an alias?");
3894 StringRef MangledName = getMangledName(GD);
3896 if (AA->getAliasee() == MangledName) {
3897 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3901 // If there is a definition in the module, then it wins over the alias.
3902 // This is dubious, but allow it to be safe. Just ignore the alias.
3903 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3904 if (Entry && !Entry->isDeclaration())
3907 Aliases.push_back(GD);
3909 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3911 // Create a reference to the named value. This ensures that it is emitted
3912 // if a deferred decl.
3913 llvm::Constant *Aliasee;
3914 if (isa<llvm::FunctionType>(DeclTy))
3915 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3916 /*ForVTable=*/false);
3918 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3919 llvm::PointerType::getUnqual(DeclTy),
3922 // Create the new alias itself, but don't set a name yet.
3923 auto *GA = llvm::GlobalAlias::create(
3924 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3927 if (GA->getAliasee() == Entry) {
3928 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3932 assert(Entry->isDeclaration());
3934 // If there is a declaration in the module, then we had an extern followed
3935 // by the alias, as in:
3936 // extern int test6();
3938 // int test6() __attribute__((alias("test7")));
3940 // Remove it and replace uses of it with the alias.
3941 GA->takeName(Entry);
3943 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3945 Entry->eraseFromParent();
3947 GA->setName(MangledName);
3950 // Set attributes which are particular to an alias; this is a
3951 // specialization of the attributes which may be set on a global
3952 // variable/function.
3953 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3954 D->isWeakImported()) {
3955 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3958 if (const auto *VD = dyn_cast<VarDecl>(D))
3959 if (VD->getTLSKind())
3960 setTLSMode(GA, *VD);
3962 SetCommonAttributes(GD, GA);
3965 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3966 const auto *D = cast<ValueDecl>(GD.getDecl());
3967 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3968 assert(IFA && "Not an ifunc?");
3970 StringRef MangledName = getMangledName(GD);
3972 if (IFA->getResolver() == MangledName) {
3973 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3977 // Report an error if some definition overrides ifunc.
3978 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3979 if (Entry && !Entry->isDeclaration()) {
3981 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3982 DiagnosedConflictingDefinitions.insert(GD).second) {
3983 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
3985 Diags.Report(OtherGD.getDecl()->getLocation(),
3986 diag::note_previous_definition);
3991 Aliases.push_back(GD);
3993 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3994 llvm::Constant *Resolver =
3995 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3996 /*ForVTable=*/false);
3997 llvm::GlobalIFunc *GIF =
3998 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3999 "", Resolver, &getModule());
4001 if (GIF->getResolver() == Entry) {
4002 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4005 assert(Entry->isDeclaration());
4007 // If there is a declaration in the module, then we had an extern followed
4008 // by the ifunc, as in:
4009 // extern int test();
4011 // int test() __attribute__((ifunc("resolver")));
4013 // Remove it and replace uses of it with the ifunc.
4014 GIF->takeName(Entry);
4016 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4018 Entry->eraseFromParent();
4020 GIF->setName(MangledName);
4022 SetCommonAttributes(GD, GIF);
4025 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4026 ArrayRef<llvm::Type*> Tys) {
4027 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4031 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4032 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4033 const StringLiteral *Literal, bool TargetIsLSB,
4034 bool &IsUTF16, unsigned &StringLength) {
4035 StringRef String = Literal->getString();
4036 unsigned NumBytes = String.size();
4038 // Check for simple case.
4039 if (!Literal->containsNonAsciiOrNull()) {
4040 StringLength = NumBytes;
4041 return *Map.insert(std::make_pair(String, nullptr)).first;
4044 // Otherwise, convert the UTF8 literals into a string of shorts.
4047 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4048 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4049 llvm::UTF16 *ToPtr = &ToBuf[0];
4051 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4052 ToPtr + NumBytes, llvm::strictConversion);
4054 // ConvertUTF8toUTF16 returns the length in ToPtr.
4055 StringLength = ToPtr - &ToBuf[0];
4057 // Add an explicit null.
4059 return *Map.insert(std::make_pair(
4060 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4061 (StringLength + 1) * 2),
4066 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4067 unsigned StringLength = 0;
4068 bool isUTF16 = false;
4069 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4070 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4071 getDataLayout().isLittleEndian(), isUTF16,
4074 if (auto *C = Entry.second)
4075 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4077 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4078 llvm::Constant *Zeros[] = { Zero, Zero };
4080 // If we don't already have it, get __CFConstantStringClassReference.
4081 if (!CFConstantStringClassRef) {
4082 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4083 Ty = llvm::ArrayType::get(Ty, 0);
4084 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
4085 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
4087 if (getTriple().isOSBinFormatCOFF()) {
4088 IdentifierInfo &II = getContext().Idents.get(GV->getName());
4089 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
4090 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4092 const VarDecl *VD = nullptr;
4093 for (const auto &Result : DC->lookup(&II))
4094 if ((VD = dyn_cast<VarDecl>(Result)))
4097 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
4098 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4099 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4101 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4102 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4107 // Decay array -> ptr
4108 CFConstantStringClassRef =
4109 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
4112 QualType CFTy = getContext().getCFConstantStringType();
4114 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4116 ConstantInitBuilder Builder(*this);
4117 auto Fields = Builder.beginStruct(STy);
4120 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4123 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4126 llvm::Constant *C = nullptr;
4128 auto Arr = llvm::makeArrayRef(
4129 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4130 Entry.first().size() / 2);
4131 C = llvm::ConstantDataArray::get(VMContext, Arr);
4133 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4136 // Note: -fwritable-strings doesn't make the backing store strings of
4137 // CFStrings writable. (See <rdar://problem/10657500>)
4139 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4140 llvm::GlobalValue::PrivateLinkage, C, ".str");
4141 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4142 // Don't enforce the target's minimum global alignment, since the only use
4143 // of the string is via this class initializer.
4144 CharUnits Align = isUTF16
4145 ? getContext().getTypeAlignInChars(getContext().ShortTy)
4146 : getContext().getTypeAlignInChars(getContext().CharTy);
4147 GV->setAlignment(Align.getQuantity());
4149 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4150 // Without it LLVM can merge the string with a non unnamed_addr one during
4151 // LTO. Doing that changes the section it ends in, which surprises ld64.
4152 if (getTriple().isOSBinFormatMachO())
4153 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4154 : "__TEXT,__cstring,cstring_literals");
4157 llvm::Constant *Str =
4158 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4161 // Cast the UTF16 string to the correct type.
4162 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4166 auto Ty = getTypes().ConvertType(getContext().LongTy);
4167 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
4169 CharUnits Alignment = getPointerAlign();
4172 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4173 /*isConstant=*/false,
4174 llvm::GlobalVariable::PrivateLinkage);
4175 switch (getTriple().getObjectFormat()) {
4176 case llvm::Triple::UnknownObjectFormat:
4177 llvm_unreachable("unknown file format");
4178 case llvm::Triple::COFF:
4179 case llvm::Triple::ELF:
4180 case llvm::Triple::Wasm:
4181 GV->setSection("cfstring");
4183 case llvm::Triple::MachO:
4184 GV->setSection("__DATA,__cfstring");
4189 return ConstantAddress(GV, Alignment);
4192 bool CodeGenModule::getExpressionLocationsEnabled() const {
4193 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4196 QualType CodeGenModule::getObjCFastEnumerationStateType() {
4197 if (ObjCFastEnumerationStateType.isNull()) {
4198 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4199 D->startDefinition();
4201 QualType FieldTypes[] = {
4202 Context.UnsignedLongTy,
4203 Context.getPointerType(Context.getObjCIdType()),
4204 Context.getPointerType(Context.UnsignedLongTy),
4205 Context.getConstantArrayType(Context.UnsignedLongTy,
4206 llvm::APInt(32, 5), ArrayType::Normal, 0)
4209 for (size_t i = 0; i < 4; ++i) {
4210 FieldDecl *Field = FieldDecl::Create(Context,
4213 SourceLocation(), nullptr,
4214 FieldTypes[i], /*TInfo=*/nullptr,
4215 /*BitWidth=*/nullptr,
4218 Field->setAccess(AS_public);
4222 D->completeDefinition();
4223 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4226 return ObjCFastEnumerationStateType;
4230 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4231 assert(!E->getType()->isPointerType() && "Strings are always arrays");
4233 // Don't emit it as the address of the string, emit the string data itself
4234 // as an inline array.
4235 if (E->getCharByteWidth() == 1) {
4236 SmallString<64> Str(E->getString());
4238 // Resize the string to the right size, which is indicated by its type.
4239 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4240 Str.resize(CAT->getSize().getZExtValue());
4241 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4244 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4245 llvm::Type *ElemTy = AType->getElementType();
4246 unsigned NumElements = AType->getNumElements();
4248 // Wide strings have either 2-byte or 4-byte elements.
4249 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4250 SmallVector<uint16_t, 32> Elements;
4251 Elements.reserve(NumElements);
4253 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4254 Elements.push_back(E->getCodeUnit(i));
4255 Elements.resize(NumElements);
4256 return llvm::ConstantDataArray::get(VMContext, Elements);
4259 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4260 SmallVector<uint32_t, 32> Elements;
4261 Elements.reserve(NumElements);
4263 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4264 Elements.push_back(E->getCodeUnit(i));
4265 Elements.resize(NumElements);
4266 return llvm::ConstantDataArray::get(VMContext, Elements);
4269 static llvm::GlobalVariable *
4270 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4271 CodeGenModule &CGM, StringRef GlobalName,
4272 CharUnits Alignment) {
4273 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4274 CGM.getStringLiteralAddressSpace());
4276 llvm::Module &M = CGM.getModule();
4277 // Create a global variable for this string
4278 auto *GV = new llvm::GlobalVariable(
4279 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4280 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4281 GV->setAlignment(Alignment.getQuantity());
4282 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4283 if (GV->isWeakForLinker()) {
4284 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4285 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4287 CGM.setDSOLocal(GV);
4292 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4293 /// constant array for the given string literal.
4295 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4297 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4299 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4300 llvm::GlobalVariable **Entry = nullptr;
4301 if (!LangOpts.WritableStrings) {
4302 Entry = &ConstantStringMap[C];
4303 if (auto GV = *Entry) {
4304 if (Alignment.getQuantity() > GV->getAlignment())
4305 GV->setAlignment(Alignment.getQuantity());
4306 return ConstantAddress(GV, Alignment);
4310 SmallString<256> MangledNameBuffer;
4311 StringRef GlobalVariableName;
4312 llvm::GlobalValue::LinkageTypes LT;
4314 // Mangle the string literal if the ABI allows for it. However, we cannot
4315 // do this if we are compiling with ASan or -fwritable-strings because they
4316 // rely on strings having normal linkage.
4317 if (!LangOpts.WritableStrings &&
4318 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4319 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
4320 llvm::raw_svector_ostream Out(MangledNameBuffer);
4321 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4323 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4324 GlobalVariableName = MangledNameBuffer;
4326 LT = llvm::GlobalValue::PrivateLinkage;
4327 GlobalVariableName = Name;
4330 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4334 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4337 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4341 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4342 /// array for the given ObjCEncodeExpr node.
4344 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4346 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4348 return GetAddrOfConstantCString(Str);
4351 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
4352 /// the literal and a terminating '\0' character.
4353 /// The result has pointer to array type.
4354 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4355 const std::string &Str, const char *GlobalName) {
4356 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4357 CharUnits Alignment =
4358 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4361 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4363 // Don't share any string literals if strings aren't constant.
4364 llvm::GlobalVariable **Entry = nullptr;
4365 if (!LangOpts.WritableStrings) {
4366 Entry = &ConstantStringMap[C];
4367 if (auto GV = *Entry) {
4368 if (Alignment.getQuantity() > GV->getAlignment())
4369 GV->setAlignment(Alignment.getQuantity());
4370 return ConstantAddress(GV, Alignment);
4374 // Get the default prefix if a name wasn't specified.
4376 GlobalName = ".str";
4377 // Create a global variable for this.
4378 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4379 GlobalName, Alignment);
4383 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4387 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
4388 const MaterializeTemporaryExpr *E, const Expr *Init) {
4389 assert((E->getStorageDuration() == SD_Static ||
4390 E->getStorageDuration() == SD_Thread) && "not a global temporary");
4391 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4393 // If we're not materializing a subobject of the temporary, keep the
4394 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4395 QualType MaterializedType = Init->getType();
4396 if (Init == E->GetTemporaryExpr())
4397 MaterializedType = E->getType();
4399 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4401 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4402 return ConstantAddress(Slot, Align);
4404 // FIXME: If an externally-visible declaration extends multiple temporaries,
4405 // we need to give each temporary the same name in every translation unit (and
4406 // we also need to make the temporaries externally-visible).
4407 SmallString<256> Name;
4408 llvm::raw_svector_ostream Out(Name);
4409 getCXXABI().getMangleContext().mangleReferenceTemporary(
4410 VD, E->getManglingNumber(), Out);
4412 APValue *Value = nullptr;
4413 if (E->getStorageDuration() == SD_Static) {
4414 // We might have a cached constant initializer for this temporary. Note
4415 // that this might have a different value from the value computed by
4416 // evaluating the initializer if the surrounding constant expression
4417 // modifies the temporary.
4418 Value = getContext().getMaterializedTemporaryValue(E, false);
4419 if (Value && Value->isUninit())
4423 // Try evaluating it now, it might have a constant initializer.
4424 Expr::EvalResult EvalResult;
4425 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4426 !EvalResult.hasSideEffects())
4427 Value = &EvalResult.Val;
4430 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4432 Optional<ConstantEmitter> emitter;
4433 llvm::Constant *InitialValue = nullptr;
4434 bool Constant = false;
4437 // The temporary has a constant initializer, use it.
4438 emitter.emplace(*this);
4439 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4441 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4442 Type = InitialValue->getType();
4444 // No initializer, the initialization will be provided when we
4445 // initialize the declaration which performed lifetime extension.
4446 Type = getTypes().ConvertTypeForMem(MaterializedType);
4449 // Create a global variable for this lifetime-extended temporary.
4450 llvm::GlobalValue::LinkageTypes Linkage =
4451 getLLVMLinkageVarDefinition(VD, Constant);
4452 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4453 const VarDecl *InitVD;
4454 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4455 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4456 // Temporaries defined inside a class get linkonce_odr linkage because the
4457 // class can be defined in multiple translation units.
4458 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4460 // There is no need for this temporary to have external linkage if the
4461 // VarDecl has external linkage.
4462 Linkage = llvm::GlobalVariable::InternalLinkage;
4465 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4466 auto *GV = new llvm::GlobalVariable(
4467 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4468 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4469 if (emitter) emitter->finalize(GV);
4470 setGVProperties(GV, VD);
4471 GV->setAlignment(Align.getQuantity());
4472 if (supportsCOMDAT() && GV->isWeakForLinker())
4473 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4474 if (VD->getTLSKind())
4475 setTLSMode(GV, *VD);
4476 llvm::Constant *CV = GV;
4477 if (AddrSpace != LangAS::Default)
4478 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4479 *this, GV, AddrSpace, LangAS::Default,
4481 getContext().getTargetAddressSpace(LangAS::Default)));
4482 MaterializedGlobalTemporaryMap[E] = CV;
4483 return ConstantAddress(CV, Align);
4486 /// EmitObjCPropertyImplementations - Emit information for synthesized
4487 /// properties for an implementation.
4488 void CodeGenModule::EmitObjCPropertyImplementations(const
4489 ObjCImplementationDecl *D) {
4490 for (const auto *PID : D->property_impls()) {
4491 // Dynamic is just for type-checking.
4492 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4493 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4495 // Determine which methods need to be implemented, some may have
4496 // been overridden. Note that ::isPropertyAccessor is not the method
4497 // we want, that just indicates if the decl came from a
4498 // property. What we want to know is if the method is defined in
4499 // this implementation.
4500 if (!D->getInstanceMethod(PD->getGetterName()))
4501 CodeGenFunction(*this).GenerateObjCGetter(
4502 const_cast<ObjCImplementationDecl *>(D), PID);
4503 if (!PD->isReadOnly() &&
4504 !D->getInstanceMethod(PD->getSetterName()))
4505 CodeGenFunction(*this).GenerateObjCSetter(
4506 const_cast<ObjCImplementationDecl *>(D), PID);
4511 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
4512 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4513 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
4514 ivar; ivar = ivar->getNextIvar())
4515 if (ivar->getType().isDestructedType())
4521 static bool AllTrivialInitializers(CodeGenModule &CGM,
4522 ObjCImplementationDecl *D) {
4523 CodeGenFunction CGF(CGM);
4524 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4525 E = D->init_end(); B != E; ++B) {
4526 CXXCtorInitializer *CtorInitExp = *B;
4527 Expr *Init = CtorInitExp->getInit();
4528 if (!CGF.isTrivialInitializer(Init))
4534 /// EmitObjCIvarInitializations - Emit information for ivar initialization
4535 /// for an implementation.
4536 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
4537 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4538 if (needsDestructMethod(D)) {
4539 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4540 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4541 ObjCMethodDecl *DTORMethod =
4542 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
4543 cxxSelector, getContext().VoidTy, nullptr, D,
4544 /*isInstance=*/true, /*isVariadic=*/false,
4545 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
4546 /*isDefined=*/false, ObjCMethodDecl::Required);
4547 D->addInstanceMethod(DTORMethod);
4548 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
4549 D->setHasDestructors(true);
4552 // If the implementation doesn't have any ivar initializers, we don't need
4553 // a .cxx_construct.
4554 if (D->getNumIvarInitializers() == 0 ||
4555 AllTrivialInitializers(*this, D))
4558 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4559 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4560 // The constructor returns 'self'.
4561 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
4565 getContext().getObjCIdType(),
4566 nullptr, D, /*isInstance=*/true,
4567 /*isVariadic=*/false,
4568 /*isPropertyAccessor=*/true,
4569 /*isImplicitlyDeclared=*/true,
4570 /*isDefined=*/false,
4571 ObjCMethodDecl::Required);
4572 D->addInstanceMethod(CTORMethod);
4573 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
4574 D->setHasNonZeroConstructors(true);
4577 // EmitLinkageSpec - Emit all declarations in a linkage spec.
4578 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
4579 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4580 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
4581 ErrorUnsupported(LSD, "linkage spec");
4585 EmitDeclContext(LSD);
4588 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4589 for (auto *I : DC->decls()) {
4590 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4591 // are themselves considered "top-level", so EmitTopLevelDecl on an
4592 // ObjCImplDecl does not recursively visit them. We need to do that in
4593 // case they're nested inside another construct (LinkageSpecDecl /
4594 // ExportDecl) that does stop them from being considered "top-level".
4595 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4596 for (auto *M : OID->methods())
4597 EmitTopLevelDecl(M);
4600 EmitTopLevelDecl(I);
4604 /// EmitTopLevelDecl - Emit code for a single top level declaration.
4605 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
4606 // Ignore dependent declarations.
4607 if (D->isTemplated())
4610 switch (D->getKind()) {
4611 case Decl::CXXConversion:
4612 case Decl::CXXMethod:
4613 case Decl::Function:
4614 EmitGlobal(cast<FunctionDecl>(D));
4615 // Always provide some coverage mapping
4616 // even for the functions that aren't emitted.
4617 AddDeferredUnusedCoverageMapping(D);
4620 case Decl::CXXDeductionGuide:
4621 // Function-like, but does not result in code emission.
4625 case Decl::Decomposition:
4626 case Decl::VarTemplateSpecialization:
4627 EmitGlobal(cast<VarDecl>(D));
4628 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4629 for (auto *B : DD->bindings())
4630 if (auto *HD = B->getHoldingVar())
4634 // Indirect fields from global anonymous structs and unions can be
4635 // ignored; only the actual variable requires IR gen support.
4636 case Decl::IndirectField:
4640 case Decl::Namespace:
4641 EmitDeclContext(cast<NamespaceDecl>(D));
4643 case Decl::ClassTemplateSpecialization: {
4644 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4646 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4647 Spec->hasDefinition())
4648 DebugInfo->completeTemplateDefinition(*Spec);
4650 case Decl::CXXRecord:
4652 if (auto *ES = D->getASTContext().getExternalSource())
4653 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4654 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4656 // Emit any static data members, they may be definitions.
4657 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4658 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4659 EmitTopLevelDecl(I);
4661 // No code generation needed.
4662 case Decl::UsingShadow:
4663 case Decl::ClassTemplate:
4664 case Decl::VarTemplate:
4665 case Decl::VarTemplatePartialSpecialization:
4666 case Decl::FunctionTemplate:
4667 case Decl::TypeAliasTemplate:
4671 case Decl::Using: // using X; [C++]
4672 if (CGDebugInfo *DI = getModuleDebugInfo())
4673 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4675 case Decl::NamespaceAlias:
4676 if (CGDebugInfo *DI = getModuleDebugInfo())
4677 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4679 case Decl::UsingDirective: // using namespace X; [C++]
4680 if (CGDebugInfo *DI = getModuleDebugInfo())
4681 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4683 case Decl::CXXConstructor:
4684 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4686 case Decl::CXXDestructor:
4687 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4690 case Decl::StaticAssert:
4694 // Objective-C Decls
4696 // Forward declarations, no (immediate) code generation.
4697 case Decl::ObjCInterface:
4698 case Decl::ObjCCategory:
4701 case Decl::ObjCProtocol: {
4702 auto *Proto = cast<ObjCProtocolDecl>(D);
4703 if (Proto->isThisDeclarationADefinition())
4704 ObjCRuntime->GenerateProtocol(Proto);
4708 case Decl::ObjCCategoryImpl:
4709 // Categories have properties but don't support synthesize so we
4710 // can ignore them here.
4711 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4714 case Decl::ObjCImplementation: {
4715 auto *OMD = cast<ObjCImplementationDecl>(D);
4716 EmitObjCPropertyImplementations(OMD);
4717 EmitObjCIvarInitializations(OMD);
4718 ObjCRuntime->GenerateClass(OMD);
4719 // Emit global variable debug information.
4720 if (CGDebugInfo *DI = getModuleDebugInfo())
4721 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4722 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4723 OMD->getClassInterface()), OMD->getLocation());
4726 case Decl::ObjCMethod: {
4727 auto *OMD = cast<ObjCMethodDecl>(D);
4728 // If this is not a prototype, emit the body.
4730 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4733 case Decl::ObjCCompatibleAlias:
4734 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4737 case Decl::PragmaComment: {
4738 const auto *PCD = cast<PragmaCommentDecl>(D);
4739 switch (PCD->getCommentKind()) {
4741 llvm_unreachable("unexpected pragma comment kind");
4743 AppendLinkerOptions(PCD->getArg());
4746 if (getTarget().getTriple().isOSBinFormatELF() &&
4747 !getTarget().getTriple().isPS4())
4748 AddELFLibDirective(PCD->getArg());
4750 AddDependentLib(PCD->getArg());
4755 break; // We ignore all of these.
4760 case Decl::PragmaDetectMismatch: {
4761 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4762 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4766 case Decl::LinkageSpec:
4767 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4770 case Decl::FileScopeAsm: {
4771 // File-scope asm is ignored during device-side CUDA compilation.
4772 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4774 // File-scope asm is ignored during device-side OpenMP compilation.
4775 if (LangOpts.OpenMPIsDevice)
4777 auto *AD = cast<FileScopeAsmDecl>(D);
4778 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4782 case Decl::Import: {
4783 auto *Import = cast<ImportDecl>(D);
4785 // If we've already imported this module, we're done.
4786 if (!ImportedModules.insert(Import->getImportedModule()))
4789 // Emit debug information for direct imports.
4790 if (!Import->getImportedOwningModule()) {
4791 if (CGDebugInfo *DI = getModuleDebugInfo())
4792 DI->EmitImportDecl(*Import);
4795 // Find all of the submodules and emit the module initializers.
4796 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4797 SmallVector<clang::Module *, 16> Stack;
4798 Visited.insert(Import->getImportedModule());
4799 Stack.push_back(Import->getImportedModule());
4801 while (!Stack.empty()) {
4802 clang::Module *Mod = Stack.pop_back_val();
4803 if (!EmittedModuleInitializers.insert(Mod).second)
4806 for (auto *D : Context.getModuleInitializers(Mod))
4807 EmitTopLevelDecl(D);
4809 // Visit the submodules of this module.
4810 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4811 SubEnd = Mod->submodule_end();
4812 Sub != SubEnd; ++Sub) {
4813 // Skip explicit children; they need to be explicitly imported to emit
4814 // the initializers.
4815 if ((*Sub)->IsExplicit)
4818 if (Visited.insert(*Sub).second)
4819 Stack.push_back(*Sub);
4826 EmitDeclContext(cast<ExportDecl>(D));
4829 case Decl::OMPThreadPrivate:
4830 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4833 case Decl::OMPDeclareReduction:
4834 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4838 // Make sure we handled everything we should, every other kind is a
4839 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4840 // function. Need to recode Decl::Kind to do that easily.
4841 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4846 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4847 // Do we need to generate coverage mapping?
4848 if (!CodeGenOpts.CoverageMapping)
4850 switch (D->getKind()) {
4851 case Decl::CXXConversion:
4852 case Decl::CXXMethod:
4853 case Decl::Function:
4854 case Decl::ObjCMethod:
4855 case Decl::CXXConstructor:
4856 case Decl::CXXDestructor: {
4857 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4859 SourceManager &SM = getContext().getSourceManager();
4860 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4862 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4863 if (I == DeferredEmptyCoverageMappingDecls.end())
4864 DeferredEmptyCoverageMappingDecls[D] = true;
4872 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4873 // Do we need to generate coverage mapping?
4874 if (!CodeGenOpts.CoverageMapping)
4876 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4877 if (Fn->isTemplateInstantiation())
4878 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4880 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4881 if (I == DeferredEmptyCoverageMappingDecls.end())
4882 DeferredEmptyCoverageMappingDecls[D] = false;
4887 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4888 // We call takeVector() here to avoid use-after-free.
4889 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4890 // we deserialize function bodies to emit coverage info for them, and that
4891 // deserializes more declarations. How should we handle that case?
4892 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
4895 const Decl *D = Entry.first;
4896 switch (D->getKind()) {
4897 case Decl::CXXConversion:
4898 case Decl::CXXMethod:
4899 case Decl::Function:
4900 case Decl::ObjCMethod: {
4901 CodeGenPGO PGO(*this);
4902 GlobalDecl GD(cast<FunctionDecl>(D));
4903 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4904 getFunctionLinkage(GD));
4907 case Decl::CXXConstructor: {
4908 CodeGenPGO PGO(*this);
4909 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4910 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4911 getFunctionLinkage(GD));
4914 case Decl::CXXDestructor: {
4915 CodeGenPGO PGO(*this);
4916 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4917 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4918 getFunctionLinkage(GD));
4927 /// Turns the given pointer into a constant.
4928 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4930 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4931 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4932 return llvm::ConstantInt::get(i64, PtrInt);
4935 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4936 llvm::NamedMDNode *&GlobalMetadata,
4938 llvm::GlobalValue *Addr) {
4939 if (!GlobalMetadata)
4941 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4943 // TODO: should we report variant information for ctors/dtors?
4944 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4945 llvm::ConstantAsMetadata::get(GetPointerConstant(
4946 CGM.getLLVMContext(), D.getDecl()))};
4947 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4950 /// For each function which is declared within an extern "C" region and marked
4951 /// as 'used', but has internal linkage, create an alias from the unmangled
4952 /// name to the mangled name if possible. People expect to be able to refer
4953 /// to such functions with an unmangled name from inline assembly within the
4954 /// same translation unit.
4955 void CodeGenModule::EmitStaticExternCAliases() {
4956 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
4958 for (auto &I : StaticExternCValues) {
4959 IdentifierInfo *Name = I.first;
4960 llvm::GlobalValue *Val = I.second;
4961 if (Val && !getModule().getNamedValue(Name->getName()))
4962 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4966 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4967 GlobalDecl &Result) const {
4968 auto Res = Manglings.find(MangledName);
4969 if (Res == Manglings.end())
4971 Result = Res->getValue();
4975 /// Emits metadata nodes associating all the global values in the
4976 /// current module with the Decls they came from. This is useful for
4977 /// projects using IR gen as a subroutine.
4979 /// Since there's currently no way to associate an MDNode directly
4980 /// with an llvm::GlobalValue, we create a global named metadata
4981 /// with the name 'clang.global.decl.ptrs'.
4982 void CodeGenModule::EmitDeclMetadata() {
4983 llvm::NamedMDNode *GlobalMetadata = nullptr;
4985 for (auto &I : MangledDeclNames) {
4986 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4987 // Some mangled names don't necessarily have an associated GlobalValue
4988 // in this module, e.g. if we mangled it for DebugInfo.
4990 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4994 /// Emits metadata nodes for all the local variables in the current
4996 void CodeGenFunction::EmitDeclMetadata() {
4997 if (LocalDeclMap.empty()) return;
4999 llvm::LLVMContext &Context = getLLVMContext();
5001 // Find the unique metadata ID for this name.
5002 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5004 llvm::NamedMDNode *GlobalMetadata = nullptr;
5006 for (auto &I : LocalDeclMap) {
5007 const Decl *D = I.first;
5008 llvm::Value *Addr = I.second.getPointer();
5009 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5010 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5011 Alloca->setMetadata(
5012 DeclPtrKind, llvm::MDNode::get(
5013 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5014 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5015 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5016 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5021 void CodeGenModule::EmitVersionIdentMetadata() {
5022 llvm::NamedMDNode *IdentMetadata =
5023 TheModule.getOrInsertNamedMetadata("llvm.ident");
5024 std::string Version = getClangFullVersion();
5025 llvm::LLVMContext &Ctx = TheModule.getContext();
5027 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5028 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5031 void CodeGenModule::EmitTargetMetadata() {
5032 // Warning, new MangledDeclNames may be appended within this loop.
5033 // We rely on MapVector insertions adding new elements to the end
5034 // of the container.
5035 // FIXME: Move this loop into the one target that needs it, and only
5036 // loop over those declarations for which we couldn't emit the target
5037 // metadata when we emitted the declaration.
5038 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5039 auto Val = *(MangledDeclNames.begin() + I);
5040 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5041 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
5042 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5046 void CodeGenModule::EmitCoverageFile() {
5047 if (getCodeGenOpts().CoverageDataFile.empty() &&
5048 getCodeGenOpts().CoverageNotesFile.empty())
5051 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5055 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5056 llvm::LLVMContext &Ctx = TheModule.getContext();
5057 auto *CoverageDataFile =
5058 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5059 auto *CoverageNotesFile =
5060 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5061 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5062 llvm::MDNode *CU = CUNode->getOperand(i);
5063 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5064 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5068 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5069 // Sema has checked that all uuid strings are of the form
5070 // "12345678-1234-1234-1234-1234567890ab".
5071 assert(Uuid.size() == 36);
5072 for (unsigned i = 0; i < 36; ++i) {
5073 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5074 else assert(isHexDigit(Uuid[i]));
5077 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5078 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5080 llvm::Constant *Field3[8];
5081 for (unsigned Idx = 0; Idx < 8; ++Idx)
5082 Field3[Idx] = llvm::ConstantInt::get(
5083 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5085 llvm::Constant *Fields[4] = {
5086 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5087 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5088 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5089 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5092 return llvm::ConstantStruct::getAnon(Fields);
5095 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5097 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5098 // FIXME: should we even be calling this method if RTTI is disabled
5099 // and it's not for EH?
5100 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
5101 return llvm::Constant::getNullValue(Int8PtrTy);
5103 if (ForEH && Ty->isObjCObjectPointerType() &&
5104 LangOpts.ObjCRuntime.isGNUFamily())
5105 return ObjCRuntime->GetEHType(Ty);
5107 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5110 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5111 // Do not emit threadprivates in simd-only mode.
5112 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5114 for (auto RefExpr : D->varlists()) {
5115 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5117 VD->getAnyInitializer() &&
5118 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5121 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5122 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5123 VD, Addr, RefExpr->getLocStart(), PerformInit))
5124 CXXGlobalInits.push_back(InitFunction);
5129 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5131 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5135 if (isExternallyVisible(T->getLinkage())) {
5136 std::string OutName;
5137 llvm::raw_string_ostream Out(OutName);
5138 getCXXABI().getMangleContext().mangleTypeName(T, Out);
5141 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5143 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5144 llvm::ArrayRef<llvm::Metadata *>());
5150 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5151 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5155 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5156 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5159 // Generalize pointer types to a void pointer with the qualifiers of the
5160 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5161 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5163 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5164 if (!Ty->isPointerType())
5167 return Ctx.getPointerType(
5168 QualType(Ctx.VoidTy).withCVRQualifiers(
5169 Ty->getPointeeType().getCVRQualifiers()));
5172 // Apply type generalization to a FunctionType's return and argument types
5173 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5174 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5175 SmallVector<QualType, 8> GeneralizedParams;
5176 for (auto &Param : FnType->param_types())
5177 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5179 return Ctx.getFunctionType(
5180 GeneralizeType(Ctx, FnType->getReturnType()),
5181 GeneralizedParams, FnType->getExtProtoInfo());
5184 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5185 return Ctx.getFunctionNoProtoType(
5186 GeneralizeType(Ctx, FnType->getReturnType()));
5188 llvm_unreachable("Encountered unknown FunctionType");
5191 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5192 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5193 GeneralizedMetadataIdMap, ".generalized");
5196 /// Returns whether this module needs the "all-vtables" type identifier.
5197 bool CodeGenModule::NeedAllVtablesTypeId() const {
5198 // Returns true if at least one of vtable-based CFI checkers is enabled and
5199 // is not in the trapping mode.
5200 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5201 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5202 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5203 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5204 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5205 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5206 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5207 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5210 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5212 const CXXRecordDecl *RD) {
5213 llvm::Metadata *MD =
5214 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5215 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5217 if (CodeGenOpts.SanitizeCfiCrossDso)
5218 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5219 VTable->addTypeMetadata(Offset.getQuantity(),
5220 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5222 if (NeedAllVtablesTypeId()) {
5223 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5224 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5228 TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5229 assert(TD != nullptr);
5230 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5232 ParsedAttr.Features.erase(
5233 llvm::remove_if(ParsedAttr.Features,
5234 [&](const std::string &Feat) {
5235 return !Target.isValidFeatureName(
5236 StringRef{Feat}.substr(1));
5238 ParsedAttr.Features.end());
5243 // Fills in the supplied string map with the set of target features for the
5244 // passed in function.
5245 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5246 const FunctionDecl *FD) {
5247 StringRef TargetCPU = Target.getTargetOpts().CPU;
5248 if (const auto *TD = FD->getAttr<TargetAttr>()) {
5249 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
5251 // Make a copy of the features as passed on the command line into the
5252 // beginning of the additional features from the function to override.
5253 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5254 Target.getTargetOpts().FeaturesAsWritten.begin(),
5255 Target.getTargetOpts().FeaturesAsWritten.end());
5257 if (ParsedAttr.Architecture != "" &&
5258 Target.isValidCPUName(ParsedAttr.Architecture))
5259 TargetCPU = ParsedAttr.Architecture;
5261 // Now populate the feature map, first with the TargetCPU which is either
5262 // the default or a new one from the target attribute string. Then we'll use
5263 // the passed in features (FeaturesAsWritten) along with the new ones from
5265 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5266 ParsedAttr.Features);
5267 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5268 llvm::SmallVector<StringRef, 32> FeaturesTmp;
5269 Target.getCPUSpecificCPUDispatchFeatures(SD->getCurCPUName()->getName(),
5271 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5272 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
5274 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5275 Target.getTargetOpts().Features);
5279 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5281 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5286 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5287 CodeGenFunction &CGF) {
5288 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5289 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5290 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5291 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5292 "__translate_sampler_initializer"),