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 "CodeGenTBAA.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 const char AnnotationSection[] = "llvm.metadata";
65 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
66 switch (CGM.getTarget().getCXXABI().getKind()) {
67 case TargetCXXABI::GenericAArch64:
68 case TargetCXXABI::GenericARM:
69 case TargetCXXABI::iOS:
70 case TargetCXXABI::iOS64:
71 case TargetCXXABI::WatchOS:
72 case TargetCXXABI::GenericMIPS:
73 case TargetCXXABI::GenericItanium:
74 case TargetCXXABI::WebAssembly:
75 return CreateItaniumCXXABI(CGM);
76 case TargetCXXABI::Microsoft:
77 return CreateMicrosoftCXXABI(CGM);
80 llvm_unreachable("invalid C++ ABI kind");
83 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
84 const PreprocessorOptions &PPO,
85 const CodeGenOptions &CGO, llvm::Module &M,
86 DiagnosticsEngine &diags,
87 CoverageSourceInfo *CoverageInfo)
88 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
89 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
90 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
91 VMContext(M.getContext()), Types(*this), VTables(*this),
92 SanitizerMD(new SanitizerMetadata(*this)) {
94 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 VoidTy = llvm::Type::getVoidTy(LLVMContext);
97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 FloatTy = llvm::Type::getFloatTy(LLVMContext);
102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104 PointerAlignInBytes =
105 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
109 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
110 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
111 IntPtrTy = llvm::IntegerType::get(LLVMContext,
112 C.getTargetInfo().getMaxPointerWidth());
113 Int8PtrTy = Int8Ty->getPointerTo(0);
114 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
115 AllocaInt8PtrTy = Int8Ty->getPointerTo(
116 M.getDataLayout().getAllocaAddrSpace());
117 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
119 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
120 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
125 createOpenCLRuntime();
127 createOpenMPRuntime();
131 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
132 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
133 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
134 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
135 getCXXABI().getMangleContext()));
137 // If debug info or coverage generation is enabled, create the CGDebugInfo
139 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
140 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
141 DebugInfo.reset(new CGDebugInfo(*this));
143 Block.GlobalUniqueCount = 0;
145 if (C.getLangOpts().ObjC1)
146 ObjCData.reset(new ObjCEntrypoints());
148 if (CodeGenOpts.hasProfileClangUse()) {
149 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
150 CodeGenOpts.ProfileInstrumentUsePath);
151 if (auto E = ReaderOrErr.takeError()) {
152 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
153 "Could not read profile %0: %1");
154 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
155 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
159 PGOReader = std::move(ReaderOrErr.get());
162 // If coverage mapping generation is enabled, create the
163 // CoverageMappingModuleGen object.
164 if (CodeGenOpts.CoverageMapping)
165 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
168 CodeGenModule::~CodeGenModule() {}
170 void CodeGenModule::createObjCRuntime() {
171 // This is just isGNUFamily(), but we want to force implementors of
172 // new ABIs to decide how best to do this.
173 switch (LangOpts.ObjCRuntime.getKind()) {
174 case ObjCRuntime::GNUstep:
175 case ObjCRuntime::GCC:
176 case ObjCRuntime::ObjFW:
177 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
180 case ObjCRuntime::FragileMacOSX:
181 case ObjCRuntime::MacOSX:
182 case ObjCRuntime::iOS:
183 case ObjCRuntime::WatchOS:
184 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
187 llvm_unreachable("bad runtime kind");
190 void CodeGenModule::createOpenCLRuntime() {
191 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
194 void CodeGenModule::createOpenMPRuntime() {
195 // Select a specialized code generation class based on the target, if any.
196 // If it does not exist use the default implementation.
197 switch (getTriple().getArch()) {
198 case llvm::Triple::nvptx:
199 case llvm::Triple::nvptx64:
200 assert(getLangOpts().OpenMPIsDevice &&
201 "OpenMP NVPTX is only prepared to deal with device code.");
202 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
205 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
210 void CodeGenModule::createCUDARuntime() {
211 CUDARuntime.reset(CreateNVCUDARuntime(*this));
214 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
215 Replacements[Name] = C;
218 void CodeGenModule::applyReplacements() {
219 for (auto &I : Replacements) {
220 StringRef MangledName = I.first();
221 llvm::Constant *Replacement = I.second;
222 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
225 auto *OldF = cast<llvm::Function>(Entry);
226 auto *NewF = dyn_cast<llvm::Function>(Replacement);
228 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
229 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
231 auto *CE = cast<llvm::ConstantExpr>(Replacement);
232 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233 CE->getOpcode() == llvm::Instruction::GetElementPtr);
234 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
238 // Replace old with new, but keep the old order.
239 OldF->replaceAllUsesWith(Replacement);
241 NewF->removeFromParent();
242 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
245 OldF->eraseFromParent();
249 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
250 GlobalValReplacements.push_back(std::make_pair(GV, C));
253 void CodeGenModule::applyGlobalValReplacements() {
254 for (auto &I : GlobalValReplacements) {
255 llvm::GlobalValue *GV = I.first;
256 llvm::Constant *C = I.second;
258 GV->replaceAllUsesWith(C);
259 GV->eraseFromParent();
263 // This is only used in aliases that we created and we know they have a
265 static const llvm::GlobalObject *getAliasedGlobal(
266 const llvm::GlobalIndirectSymbol &GIS) {
267 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268 const llvm::Constant *C = &GIS;
270 C = C->stripPointerCasts();
271 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
273 // stripPointerCasts will not walk over weak aliases.
274 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
277 if (!Visited.insert(GIS2).second)
279 C = GIS2->getIndirectSymbol();
283 void CodeGenModule::checkAliases() {
284 // Check if the constructed aliases are well formed. It is really unfortunate
285 // that we have to do this in CodeGen, but we only construct mangled names
286 // and aliases during codegen.
288 DiagnosticsEngine &Diags = getDiags();
289 for (const GlobalDecl &GD : Aliases) {
290 const auto *D = cast<ValueDecl>(GD.getDecl());
291 SourceLocation Location;
292 bool IsIFunc = D->hasAttr<IFuncAttr>();
293 if (const Attr *A = D->getDefiningAttr())
294 Location = A->getLocation();
296 llvm_unreachable("Not an alias or ifunc?");
297 StringRef MangledName = getMangledName(GD);
298 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
299 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
300 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
303 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
304 } else if (GV->isDeclaration()) {
306 Diags.Report(Location, diag::err_alias_to_undefined)
307 << IsIFunc << IsIFunc;
308 } else if (IsIFunc) {
309 // Check resolver function type.
310 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311 GV->getType()->getPointerElementType());
313 if (!FTy->getReturnType()->isPointerTy())
314 Diags.Report(Location, diag::err_ifunc_resolver_return);
315 if (FTy->getNumParams())
316 Diags.Report(Location, diag::err_ifunc_resolver_params);
319 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
320 llvm::GlobalValue *AliaseeGV;
321 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
322 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
324 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
326 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
327 StringRef AliasSection = SA->getName();
328 if (AliasSection != AliaseeGV->getSection())
329 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
330 << AliasSection << IsIFunc << IsIFunc;
333 // We have to handle alias to weak aliases in here. LLVM itself disallows
334 // this since the object semantics would not match the IL one. For
335 // compatibility with gcc we implement it by just pointing the alias
336 // to its aliasee's aliasee. We also warn, since the user is probably
337 // expecting the link to be weak.
338 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
339 if (GA->isInterposable()) {
340 Diags.Report(Location, diag::warn_alias_to_weak_alias)
341 << GV->getName() << GA->getName() << IsIFunc;
342 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
343 GA->getIndirectSymbol(), Alias->getType());
344 Alias->setIndirectSymbol(Aliasee);
351 for (const GlobalDecl &GD : Aliases) {
352 StringRef MangledName = getMangledName(GD);
353 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
354 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
355 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356 Alias->eraseFromParent();
360 void CodeGenModule::clear() {
361 DeferredDeclsToEmit.clear();
363 OpenMPRuntime->clear();
366 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
367 StringRef MainFile) {
368 if (!hasDiagnostics())
370 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
371 if (MainFile.empty())
372 MainFile = "<stdin>";
373 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
376 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
379 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
383 void CodeGenModule::Release() {
385 applyGlobalValReplacements();
388 EmitCXXGlobalInitFunc();
389 EmitCXXGlobalDtorFunc();
390 EmitCXXThreadLocalInitFunc();
392 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
393 AddGlobalCtor(ObjCInitFunction);
394 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
396 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
397 AddGlobalCtor(CudaCtorFunction);
398 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
399 AddGlobalDtor(CudaDtorFunction);
402 if (llvm::Function *OpenMPRegistrationFunction =
403 OpenMPRuntime->emitRegistrationFunction()) {
404 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
405 OpenMPRegistrationFunction : nullptr;
406 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
409 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
410 if (PGOStats.hasDiagnostics())
411 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
413 EmitCtorList(GlobalCtors, "llvm.global_ctors");
414 EmitCtorList(GlobalDtors, "llvm.global_dtors");
415 EmitGlobalAnnotations();
416 EmitStaticExternCAliases();
417 EmitDeferredUnusedCoverageMappings();
419 CoverageMapping->emit();
420 if (CodeGenOpts.SanitizeCfiCrossDso) {
421 CodeGenFunction(*this).EmitCfiCheckFail();
422 CodeGenFunction(*this).EmitCfiCheckStub();
424 emitAtAvailableLinkGuard();
429 if (CodeGenOpts.Autolink &&
430 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
431 EmitModuleLinkOptions();
434 // Record mregparm value now so it is visible through rest of codegen.
435 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
436 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
437 CodeGenOpts.NumRegisterParameters);
439 if (CodeGenOpts.DwarfVersion) {
440 // We actually want the latest version when there are conflicts.
441 // We can change from Warning to Latest if such mode is supported.
442 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
443 CodeGenOpts.DwarfVersion);
445 if (CodeGenOpts.EmitCodeView) {
446 // Indicate that we want CodeView in the metadata.
447 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
449 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
450 // We don't support LTO with 2 with different StrictVTablePointers
451 // FIXME: we could support it by stripping all the information introduced
452 // by StrictVTablePointers.
454 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
456 llvm::Metadata *Ops[2] = {
457 llvm::MDString::get(VMContext, "StrictVTablePointers"),
458 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
459 llvm::Type::getInt32Ty(VMContext), 1))};
461 getModule().addModuleFlag(llvm::Module::Require,
462 "StrictVTablePointersRequirement",
463 llvm::MDNode::get(VMContext, Ops));
466 // We support a single version in the linked module. The LLVM
467 // parser will drop debug info with a different version number
468 // (and warn about it, too).
469 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
470 llvm::DEBUG_METADATA_VERSION);
472 // Width of wchar_t in bytes
473 uint64_t WCharWidth =
474 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
475 assert(LangOpts.ShortWChar ||
476 llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) ==
477 Target.getWCharWidth() / 8 &&
478 "LLVM wchar_t size out of sync");
480 // We need to record the widths of enums and wchar_t, so that we can generate
481 // the correct build attributes in the ARM backend. wchar_size is also used by
482 // TargetLibraryInfo.
483 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
485 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
486 if ( Arch == llvm::Triple::arm
487 || Arch == llvm::Triple::armeb
488 || Arch == llvm::Triple::thumb
489 || Arch == llvm::Triple::thumbeb) {
490 // The minimum width of an enum in bytes
491 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
492 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
495 if (CodeGenOpts.SanitizeCfiCrossDso) {
496 // Indicate that we want cross-DSO control flow integrity checks.
497 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
500 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
501 // Indicate whether __nvvm_reflect should be configured to flush denormal
502 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
504 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
505 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
508 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
509 assert(PLevel < 3 && "Invalid PIC Level");
510 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
511 if (Context.getLangOpts().PIE)
512 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
515 SimplifyPersonality();
517 if (getCodeGenOpts().EmitDeclMetadata)
520 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
524 DebugInfo->finalize();
526 EmitVersionIdentMetadata();
528 EmitTargetMetadata();
531 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
532 // Make sure that this type is translated.
533 Types.UpdateCompletedType(TD);
536 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
537 // Make sure that this type is translated.
538 Types.RefreshTypeCacheForClass(RD);
541 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
544 return TBAA->getTBAAInfo(QTy);
547 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
550 return TBAA->getTBAAInfoForVTablePtr();
553 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
556 return TBAA->getTBAAStructInfo(QTy);
559 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
560 llvm::MDNode *AccessN,
564 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
567 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
568 /// and struct-path aware TBAA, the tag has the same format:
569 /// base type, access type and offset.
570 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
571 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
572 llvm::MDNode *TBAAInfo,
573 bool ConvertTypeToTag) {
574 if (ConvertTypeToTag && TBAA)
575 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
576 TBAA->getTBAAScalarTagInfo(TBAAInfo));
578 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
581 void CodeGenModule::DecorateInstructionWithInvariantGroup(
582 llvm::Instruction *I, const CXXRecordDecl *RD) {
583 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
584 llvm::MDNode::get(getLLVMContext(), {}));
587 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
588 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
589 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
592 /// ErrorUnsupported - Print out an error that codegen doesn't support the
593 /// specified stmt yet.
594 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
595 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
596 "cannot compile this %0 yet");
597 std::string Msg = Type;
598 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
599 << Msg << S->getSourceRange();
602 /// ErrorUnsupported - Print out an error that codegen doesn't support the
603 /// specified decl yet.
604 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
605 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
606 "cannot compile this %0 yet");
607 std::string Msg = Type;
608 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
611 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
612 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
615 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
616 const NamedDecl *D) const {
617 // Internal definitions always have default visibility.
618 if (GV->hasLocalLinkage()) {
619 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
623 // Set visibility for definitions.
624 LinkageInfo LV = D->getLinkageAndVisibility();
625 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
626 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
629 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
630 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
631 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
632 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
633 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
634 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
637 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
638 CodeGenOptions::TLSModel M) {
640 case CodeGenOptions::GeneralDynamicTLSModel:
641 return llvm::GlobalVariable::GeneralDynamicTLSModel;
642 case CodeGenOptions::LocalDynamicTLSModel:
643 return llvm::GlobalVariable::LocalDynamicTLSModel;
644 case CodeGenOptions::InitialExecTLSModel:
645 return llvm::GlobalVariable::InitialExecTLSModel;
646 case CodeGenOptions::LocalExecTLSModel:
647 return llvm::GlobalVariable::LocalExecTLSModel;
649 llvm_unreachable("Invalid TLS model!");
652 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
653 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
655 llvm::GlobalValue::ThreadLocalMode TLM;
656 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
658 // Override the TLS model if it is explicitly specified.
659 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
660 TLM = GetLLVMTLSModel(Attr->getModel());
663 GV->setThreadLocalMode(TLM);
666 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
667 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
669 // Some ABIs don't have constructor variants. Make sure that base and
670 // complete constructors get mangled the same.
671 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
672 if (!getTarget().getCXXABI().hasConstructorVariants()) {
673 CXXCtorType OrigCtorType = GD.getCtorType();
674 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
675 if (OrigCtorType == Ctor_Base)
676 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
680 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
681 if (!FoundStr.empty())
684 const auto *ND = cast<NamedDecl>(GD.getDecl());
685 SmallString<256> Buffer;
687 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
688 llvm::raw_svector_ostream Out(Buffer);
689 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
690 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
691 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
692 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
694 getCXXABI().getMangleContext().mangleName(ND, Out);
697 IdentifierInfo *II = ND->getIdentifier();
698 assert(II && "Attempt to mangle unnamed decl.");
699 const auto *FD = dyn_cast<FunctionDecl>(ND);
702 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
703 llvm::raw_svector_ostream Out(Buffer);
704 Out << "__regcall3__" << II->getName();
711 // Keep the first result in the case of a mangling collision.
712 auto Result = Manglings.insert(std::make_pair(Str, GD));
713 return FoundStr = Result.first->first();
716 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
717 const BlockDecl *BD) {
718 MangleContext &MangleCtx = getCXXABI().getMangleContext();
719 const Decl *D = GD.getDecl();
721 SmallString<256> Buffer;
722 llvm::raw_svector_ostream Out(Buffer);
724 MangleCtx.mangleGlobalBlock(BD,
725 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
726 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
727 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
728 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
729 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
731 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
733 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
734 return Result.first->first();
737 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
738 return getModule().getNamedValue(Name);
741 /// AddGlobalCtor - Add a function to the list that will be called before
743 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
744 llvm::Constant *AssociatedData) {
745 // FIXME: Type coercion of void()* types.
746 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
749 /// AddGlobalDtor - Add a function to the list that will be called
750 /// when the module is unloaded.
751 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
752 // FIXME: Type coercion of void()* types.
753 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
756 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
757 if (Fns.empty()) return;
759 // Ctor function type is void()*.
760 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
761 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
763 // Get the type of a ctor entry, { i32, void ()*, i8* }.
764 llvm::StructType *CtorStructTy = llvm::StructType::get(
765 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
767 // Construct the constructor and destructor arrays.
768 ConstantInitBuilder builder(*this);
769 auto ctors = builder.beginArray(CtorStructTy);
770 for (const auto &I : Fns) {
771 auto ctor = ctors.beginStruct(CtorStructTy);
772 ctor.addInt(Int32Ty, I.Priority);
773 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
774 if (I.AssociatedData)
775 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
777 ctor.addNullPointer(VoidPtrTy);
778 ctor.finishAndAddTo(ctors);
782 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
784 llvm::GlobalValue::AppendingLinkage);
786 // The LTO linker doesn't seem to like it when we set an alignment
787 // on appending variables. Take it off as a workaround.
788 list->setAlignment(0);
793 llvm::GlobalValue::LinkageTypes
794 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
795 const auto *D = cast<FunctionDecl>(GD.getDecl());
797 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
799 if (isa<CXXDestructorDecl>(D) &&
800 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
802 // Destructor variants in the Microsoft C++ ABI are always internal or
803 // linkonce_odr thunks emitted on an as-needed basis.
804 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
805 : llvm::GlobalValue::LinkOnceODRLinkage;
808 if (isa<CXXConstructorDecl>(D) &&
809 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
810 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
811 // Our approach to inheriting constructors is fundamentally different from
812 // that used by the MS ABI, so keep our inheriting constructor thunks
813 // internal rather than trying to pick an unambiguous mangling for them.
814 return llvm::GlobalValue::InternalLinkage;
817 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
820 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
821 const auto *FD = cast<FunctionDecl>(GD.getDecl());
823 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
824 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
825 // Don't dllexport/import destructor thunks.
826 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
831 if (FD->hasAttr<DLLImportAttr>())
832 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
833 else if (FD->hasAttr<DLLExportAttr>())
834 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
836 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
839 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
840 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
841 if (!MDS) return nullptr;
843 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
846 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
848 setNonAliasAttributes(D, F);
851 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
852 const CGFunctionInfo &Info,
854 unsigned CallingConv;
855 llvm::AttributeList PAL;
856 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
857 F->setAttributes(PAL);
858 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
861 /// Determines whether the language options require us to model
862 /// unwind exceptions. We treat -fexceptions as mandating this
863 /// except under the fragile ObjC ABI with only ObjC exceptions
864 /// enabled. This means, for example, that C with -fexceptions
866 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
867 // If exceptions are completely disabled, obviously this is false.
868 if (!LangOpts.Exceptions) return false;
870 // If C++ exceptions are enabled, this is true.
871 if (LangOpts.CXXExceptions) return true;
873 // If ObjC exceptions are enabled, this depends on the ABI.
874 if (LangOpts.ObjCExceptions) {
875 return LangOpts.ObjCRuntime.hasUnwindExceptions();
881 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
885 if (CodeGenOpts.UnwindTables)
886 B.addAttribute(llvm::Attribute::UWTable);
888 if (!hasUnwindExceptions(LangOpts))
889 B.addAttribute(llvm::Attribute::NoUnwind);
891 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
892 B.addAttribute(llvm::Attribute::StackProtect);
893 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
894 B.addAttribute(llvm::Attribute::StackProtectStrong);
895 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
896 B.addAttribute(llvm::Attribute::StackProtectReq);
899 // If we don't have a declaration to control inlining, the function isn't
900 // explicitly marked as alwaysinline for semantic reasons, and inlining is
901 // disabled, mark the function as noinline.
902 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
903 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
904 B.addAttribute(llvm::Attribute::NoInline);
906 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
910 // Track whether we need to add the optnone LLVM attribute,
911 // starting with the default for this optimization level.
912 bool ShouldAddOptNone =
913 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
914 // We can't add optnone in the following cases, it won't pass the verifier.
915 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
916 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
917 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
919 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
920 B.addAttribute(llvm::Attribute::OptimizeNone);
922 // OptimizeNone implies noinline; we should not be inlining such functions.
923 B.addAttribute(llvm::Attribute::NoInline);
924 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
925 "OptimizeNone and AlwaysInline on same function!");
927 // We still need to handle naked functions even though optnone subsumes
928 // much of their semantics.
929 if (D->hasAttr<NakedAttr>())
930 B.addAttribute(llvm::Attribute::Naked);
932 // OptimizeNone wins over OptimizeForSize and MinSize.
933 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
934 F->removeFnAttr(llvm::Attribute::MinSize);
935 } else if (D->hasAttr<NakedAttr>()) {
936 // Naked implies noinline: we should not be inlining such functions.
937 B.addAttribute(llvm::Attribute::Naked);
938 B.addAttribute(llvm::Attribute::NoInline);
939 } else if (D->hasAttr<NoDuplicateAttr>()) {
940 B.addAttribute(llvm::Attribute::NoDuplicate);
941 } else if (D->hasAttr<NoInlineAttr>()) {
942 B.addAttribute(llvm::Attribute::NoInline);
943 } else if (D->hasAttr<AlwaysInlineAttr>() &&
944 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
945 // (noinline wins over always_inline, and we can't specify both in IR)
946 B.addAttribute(llvm::Attribute::AlwaysInline);
947 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
948 // If we're not inlining, then force everything that isn't always_inline to
949 // carry an explicit noinline attribute.
950 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
951 B.addAttribute(llvm::Attribute::NoInline);
953 // Otherwise, propagate the inline hint attribute and potentially use its
954 // absence to mark things as noinline.
955 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
956 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
957 return Redecl->isInlineSpecified();
959 B.addAttribute(llvm::Attribute::InlineHint);
960 } else if (CodeGenOpts.getInlining() ==
961 CodeGenOptions::OnlyHintInlining &&
963 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
964 B.addAttribute(llvm::Attribute::NoInline);
969 // Add other optimization related attributes if we are optimizing this
971 if (!D->hasAttr<OptimizeNoneAttr>()) {
972 if (D->hasAttr<ColdAttr>()) {
973 if (!ShouldAddOptNone)
974 B.addAttribute(llvm::Attribute::OptimizeForSize);
975 B.addAttribute(llvm::Attribute::Cold);
978 if (D->hasAttr<MinSizeAttr>())
979 B.addAttribute(llvm::Attribute::MinSize);
982 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
984 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
986 F->setAlignment(alignment);
988 // Some C++ ABIs require 2-byte alignment for member functions, in order to
989 // reserve a bit for differentiating between virtual and non-virtual member
990 // functions. If the current target's C++ ABI requires this and this is a
991 // member function, set its alignment accordingly.
992 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
993 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
997 // In the cross-dso CFI mode, we want !type attributes on definitions only.
998 if (CodeGenOpts.SanitizeCfiCrossDso)
999 if (auto *FD = dyn_cast<FunctionDecl>(D))
1000 CreateFunctionTypeMetadata(FD, F);
1003 void CodeGenModule::SetCommonAttributes(const Decl *D,
1004 llvm::GlobalValue *GV) {
1005 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
1006 setGlobalVisibility(GV, ND);
1008 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1010 if (D && D->hasAttr<UsedAttr>())
1014 void CodeGenModule::setAliasAttributes(const Decl *D,
1015 llvm::GlobalValue *GV) {
1016 SetCommonAttributes(D, GV);
1018 // Process the dllexport attribute based on whether the original definition
1019 // (not necessarily the aliasee) was exported.
1020 if (D->hasAttr<DLLExportAttr>())
1021 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1024 void CodeGenModule::setNonAliasAttributes(const Decl *D,
1025 llvm::GlobalObject *GO) {
1026 SetCommonAttributes(D, GO);
1029 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1030 GO->setSection(SA->getName());
1032 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1035 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1037 const CGFunctionInfo &FI) {
1038 SetLLVMFunctionAttributes(D, FI, F);
1039 SetLLVMFunctionAttributesForDefinition(D, F);
1041 F->setLinkage(llvm::Function::InternalLinkage);
1043 setNonAliasAttributes(D, F);
1046 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1047 const NamedDecl *ND) {
1048 // Set linkage and visibility in case we never see a definition.
1049 LinkageInfo LV = ND->getLinkageAndVisibility();
1050 if (LV.getLinkage() != ExternalLinkage) {
1051 // Don't set internal linkage on declarations.
1053 if (ND->hasAttr<DLLImportAttr>()) {
1054 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1055 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1056 } else if (ND->hasAttr<DLLExportAttr>()) {
1057 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1058 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1059 // "extern_weak" is overloaded in LLVM; we probably should have
1060 // separate linkage types for this.
1061 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1064 // Set visibility on a declaration only if it's explicit.
1065 if (LV.isVisibilityExplicit())
1066 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1070 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1071 llvm::Function *F) {
1072 // Only if we are checking indirect calls.
1073 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1076 // Non-static class methods are handled via vtable pointer checks elsewhere.
1077 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1080 // Additionally, if building with cross-DSO support...
1081 if (CodeGenOpts.SanitizeCfiCrossDso) {
1082 // Skip available_externally functions. They won't be codegen'ed in the
1083 // current module anyway.
1084 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1088 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1089 F->addTypeMetadata(0, MD);
1091 // Emit a hash-based bit set entry for cross-DSO calls.
1092 if (CodeGenOpts.SanitizeCfiCrossDso)
1093 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1094 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1097 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1098 bool IsIncompleteFunction,
1100 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1101 // If this is an intrinsic function, set the function's attributes
1102 // to the intrinsic's attributes.
1103 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1107 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1109 if (!IsIncompleteFunction)
1110 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1112 // Add the Returned attribute for "this", except for iOS 5 and earlier
1113 // where substantial code, including the libstdc++ dylib, was compiled with
1114 // GCC and does not actually return "this".
1115 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1116 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1117 assert(!F->arg_empty() &&
1118 F->arg_begin()->getType()
1119 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1120 "unexpected this return");
1121 F->addAttribute(1, llvm::Attribute::Returned);
1124 // Only a few attributes are set on declarations; these may later be
1125 // overridden by a definition.
1127 setLinkageAndVisibilityForGV(F, FD);
1129 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1130 F->setSection(SA->getName());
1132 if (FD->isReplaceableGlobalAllocationFunction()) {
1133 // A replaceable global allocation function does not act like a builtin by
1134 // default, only if it is invoked by a new-expression or delete-expression.
1135 F->addAttribute(llvm::AttributeList::FunctionIndex,
1136 llvm::Attribute::NoBuiltin);
1138 // A sane operator new returns a non-aliasing pointer.
1139 // FIXME: Also add NonNull attribute to the return value
1140 // for the non-nothrow forms?
1141 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1142 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1143 (Kind == OO_New || Kind == OO_Array_New))
1144 F->addAttribute(llvm::AttributeList::ReturnIndex,
1145 llvm::Attribute::NoAlias);
1148 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1149 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1150 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1151 if (MD->isVirtual())
1152 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1154 // Don't emit entries for function declarations in the cross-DSO mode. This
1155 // is handled with better precision by the receiving DSO.
1156 if (!CodeGenOpts.SanitizeCfiCrossDso)
1157 CreateFunctionTypeMetadata(FD, F);
1160 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1161 assert(!GV->isDeclaration() &&
1162 "Only globals with definition can force usage.");
1163 LLVMUsed.emplace_back(GV);
1166 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1167 assert(!GV->isDeclaration() &&
1168 "Only globals with definition can force usage.");
1169 LLVMCompilerUsed.emplace_back(GV);
1172 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1173 std::vector<llvm::WeakTrackingVH> &List) {
1174 // Don't create llvm.used if there is no need.
1178 // Convert List to what ConstantArray needs.
1179 SmallVector<llvm::Constant*, 8> UsedArray;
1180 UsedArray.resize(List.size());
1181 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1183 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1184 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1187 if (UsedArray.empty())
1189 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1191 auto *GV = new llvm::GlobalVariable(
1192 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1193 llvm::ConstantArray::get(ATy, UsedArray), Name);
1195 GV->setSection("llvm.metadata");
1198 void CodeGenModule::emitLLVMUsed() {
1199 emitUsed(*this, "llvm.used", LLVMUsed);
1200 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1203 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1204 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1205 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1208 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1209 llvm::SmallString<32> Opt;
1210 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1211 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1212 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1215 void CodeGenModule::AddDependentLib(StringRef Lib) {
1216 llvm::SmallString<24> Opt;
1217 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1218 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1219 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1222 /// \brief Add link options implied by the given module, including modules
1223 /// it depends on, using a postorder walk.
1224 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1225 SmallVectorImpl<llvm::Metadata *> &Metadata,
1226 llvm::SmallPtrSet<Module *, 16> &Visited) {
1227 // Import this module's parent.
1228 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1229 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1232 // Import this module's dependencies.
1233 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1234 if (Visited.insert(Mod->Imports[I - 1]).second)
1235 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1238 // Add linker options to link against the libraries/frameworks
1239 // described by this module.
1240 llvm::LLVMContext &Context = CGM.getLLVMContext();
1241 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1242 // Link against a framework. Frameworks are currently Darwin only, so we
1243 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1244 if (Mod->LinkLibraries[I-1].IsFramework) {
1245 llvm::Metadata *Args[2] = {
1246 llvm::MDString::get(Context, "-framework"),
1247 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1249 Metadata.push_back(llvm::MDNode::get(Context, Args));
1253 // Link against a library.
1254 llvm::SmallString<24> Opt;
1255 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1256 Mod->LinkLibraries[I-1].Library, Opt);
1257 auto *OptString = llvm::MDString::get(Context, Opt);
1258 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1262 void CodeGenModule::EmitModuleLinkOptions() {
1263 // Collect the set of all of the modules we want to visit to emit link
1264 // options, which is essentially the imported modules and all of their
1265 // non-explicit child modules.
1266 llvm::SetVector<clang::Module *> LinkModules;
1267 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1268 SmallVector<clang::Module *, 16> Stack;
1270 // Seed the stack with imported modules.
1271 for (Module *M : ImportedModules) {
1272 // Do not add any link flags when an implementation TU of a module imports
1273 // a header of that same module.
1274 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1275 !getLangOpts().isCompilingModule())
1277 if (Visited.insert(M).second)
1281 // Find all of the modules to import, making a little effort to prune
1282 // non-leaf modules.
1283 while (!Stack.empty()) {
1284 clang::Module *Mod = Stack.pop_back_val();
1286 bool AnyChildren = false;
1288 // Visit the submodules of this module.
1289 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1290 SubEnd = Mod->submodule_end();
1291 Sub != SubEnd; ++Sub) {
1292 // Skip explicit children; they need to be explicitly imported to be
1294 if ((*Sub)->IsExplicit)
1297 if (Visited.insert(*Sub).second) {
1298 Stack.push_back(*Sub);
1303 // We didn't find any children, so add this module to the list of
1304 // modules to link against.
1306 LinkModules.insert(Mod);
1310 // Add link options for all of the imported modules in reverse topological
1311 // order. We don't do anything to try to order import link flags with respect
1312 // to linker options inserted by things like #pragma comment().
1313 SmallVector<llvm::Metadata *, 16> MetadataArgs;
1315 for (Module *M : LinkModules)
1316 if (Visited.insert(M).second)
1317 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1318 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1319 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1321 // Add the linker options metadata flag.
1322 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1323 llvm::MDNode::get(getLLVMContext(),
1324 LinkerOptionsMetadata));
1327 void CodeGenModule::EmitDeferred() {
1328 // Emit code for any potentially referenced deferred decls. Since a
1329 // previously unused static decl may become used during the generation of code
1330 // for a static function, iterate until no changes are made.
1332 if (!DeferredVTables.empty()) {
1333 EmitDeferredVTables();
1335 // Emitting a vtable doesn't directly cause more vtables to
1336 // become deferred, although it can cause functions to be
1337 // emitted that then need those vtables.
1338 assert(DeferredVTables.empty());
1341 // Stop if we're out of both deferred vtables and deferred declarations.
1342 if (DeferredDeclsToEmit.empty())
1345 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1346 // work, it will not interfere with this.
1347 std::vector<GlobalDecl> CurDeclsToEmit;
1348 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1350 for (GlobalDecl &D : CurDeclsToEmit) {
1351 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1352 // to get GlobalValue with exactly the type we need, not something that
1353 // might had been created for another decl with the same mangled name but
1355 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1356 GetAddrOfGlobal(D, ForDefinition));
1358 // In case of different address spaces, we may still get a cast, even with
1359 // IsForDefinition equal to true. Query mangled names table to get
1362 GV = GetGlobalValue(getMangledName(D));
1364 // Make sure GetGlobalValue returned non-null.
1367 // Check to see if we've already emitted this. This is necessary
1368 // for a couple of reasons: first, decls can end up in the
1369 // deferred-decls queue multiple times, and second, decls can end
1370 // up with definitions in unusual ways (e.g. by an extern inline
1371 // function acquiring a strong function redefinition). Just
1372 // ignore these cases.
1373 if (!GV->isDeclaration())
1376 // Otherwise, emit the definition and move on to the next one.
1377 EmitGlobalDefinition(D, GV);
1379 // If we found out that we need to emit more decls, do that recursively.
1380 // This has the advantage that the decls are emitted in a DFS and related
1381 // ones are close together, which is convenient for testing.
1382 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1384 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1389 void CodeGenModule::EmitGlobalAnnotations() {
1390 if (Annotations.empty())
1393 // Create a new global variable for the ConstantStruct in the Module.
1394 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1395 Annotations[0]->getType(), Annotations.size()), Annotations);
1396 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1397 llvm::GlobalValue::AppendingLinkage,
1398 Array, "llvm.global.annotations");
1399 gv->setSection(AnnotationSection);
1402 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1403 llvm::Constant *&AStr = AnnotationStrings[Str];
1407 // Not found yet, create a new global.
1408 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1410 new llvm::GlobalVariable(getModule(), s->getType(), true,
1411 llvm::GlobalValue::PrivateLinkage, s, ".str");
1412 gv->setSection(AnnotationSection);
1413 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1418 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1419 SourceManager &SM = getContext().getSourceManager();
1420 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1422 return EmitAnnotationString(PLoc.getFilename());
1423 return EmitAnnotationString(SM.getBufferName(Loc));
1426 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1427 SourceManager &SM = getContext().getSourceManager();
1428 PresumedLoc PLoc = SM.getPresumedLoc(L);
1429 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1430 SM.getExpansionLineNumber(L);
1431 return llvm::ConstantInt::get(Int32Ty, LineNo);
1434 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1435 const AnnotateAttr *AA,
1437 // Get the globals for file name, annotation, and the line number.
1438 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1439 *UnitGV = EmitAnnotationUnit(L),
1440 *LineNoCst = EmitAnnotationLineNo(L);
1442 // Create the ConstantStruct for the global annotation.
1443 llvm::Constant *Fields[4] = {
1444 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1445 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1446 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1449 return llvm::ConstantStruct::getAnon(Fields);
1452 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1453 llvm::GlobalValue *GV) {
1454 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1455 // Get the struct elements for these annotations.
1456 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1457 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1460 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1461 SourceLocation Loc) const {
1462 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1463 // Blacklist by function name.
1464 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1466 // Blacklist by location.
1468 return SanitizerBL.isBlacklistedLocation(Loc);
1469 // If location is unknown, this may be a compiler-generated function. Assume
1470 // it's located in the main file.
1471 auto &SM = Context.getSourceManager();
1472 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1473 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1478 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1479 SourceLocation Loc, QualType Ty,
1480 StringRef Category) const {
1481 // For now globals can be blacklisted only in ASan and KASan.
1482 if (!LangOpts.Sanitize.hasOneOf(
1483 SanitizerKind::Address | SanitizerKind::KernelAddress))
1485 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1486 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1488 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1490 // Check global type.
1492 // Drill down the array types: if global variable of a fixed type is
1493 // blacklisted, we also don't instrument arrays of them.
1494 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1495 Ty = AT->getElementType();
1496 Ty = Ty.getCanonicalType().getUnqualifiedType();
1497 // We allow to blacklist only record types (classes, structs etc.)
1498 if (Ty->isRecordType()) {
1499 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1500 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1507 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1508 StringRef Category) const {
1509 if (!LangOpts.XRayInstrument)
1511 const auto &XRayFilter = getContext().getXRayFilter();
1512 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1513 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1515 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1516 if (Attr == ImbueAttr::NONE)
1517 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1519 case ImbueAttr::NONE:
1521 case ImbueAttr::ALWAYS:
1522 Fn->addFnAttr("function-instrument", "xray-always");
1524 case ImbueAttr::ALWAYS_ARG1:
1525 Fn->addFnAttr("function-instrument", "xray-always");
1526 Fn->addFnAttr("xray-log-args", "1");
1528 case ImbueAttr::NEVER:
1529 Fn->addFnAttr("function-instrument", "xray-never");
1535 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1536 // Never defer when EmitAllDecls is specified.
1537 if (LangOpts.EmitAllDecls)
1540 return getContext().DeclMustBeEmitted(Global);
1543 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1544 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1545 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1546 // Implicit template instantiations may change linkage if they are later
1547 // explicitly instantiated, so they should not be emitted eagerly.
1549 if (const auto *VD = dyn_cast<VarDecl>(Global))
1550 if (Context.getInlineVariableDefinitionKind(VD) ==
1551 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1552 // A definition of an inline constexpr static data member may change
1553 // linkage later if it's redeclared outside the class.
1555 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1556 // codegen for global variables, because they may be marked as threadprivate.
1557 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1558 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1564 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1565 const CXXUuidofExpr* E) {
1566 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1568 StringRef Uuid = E->getUuidStr();
1569 std::string Name = "_GUID_" + Uuid.lower();
1570 std::replace(Name.begin(), Name.end(), '-', '_');
1572 // The UUID descriptor should be pointer aligned.
1573 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1575 // Look for an existing global.
1576 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1577 return ConstantAddress(GV, Alignment);
1579 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1580 assert(Init && "failed to initialize as constant");
1582 auto *GV = new llvm::GlobalVariable(
1583 getModule(), Init->getType(),
1584 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1585 if (supportsCOMDAT())
1586 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1587 return ConstantAddress(GV, Alignment);
1590 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1591 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1592 assert(AA && "No alias?");
1594 CharUnits Alignment = getContext().getDeclAlign(VD);
1595 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1597 // See if there is already something with the target's name in the module.
1598 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1600 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1601 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1602 return ConstantAddress(Ptr, Alignment);
1605 llvm::Constant *Aliasee;
1606 if (isa<llvm::FunctionType>(DeclTy))
1607 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1608 GlobalDecl(cast<FunctionDecl>(VD)),
1609 /*ForVTable=*/false);
1611 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1612 llvm::PointerType::getUnqual(DeclTy),
1615 auto *F = cast<llvm::GlobalValue>(Aliasee);
1616 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1617 WeakRefReferences.insert(F);
1619 return ConstantAddress(Aliasee, Alignment);
1622 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1623 const auto *Global = cast<ValueDecl>(GD.getDecl());
1625 // Weak references don't produce any output by themselves.
1626 if (Global->hasAttr<WeakRefAttr>())
1629 // If this is an alias definition (which otherwise looks like a declaration)
1631 if (Global->hasAttr<AliasAttr>())
1632 return EmitAliasDefinition(GD);
1634 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1635 if (Global->hasAttr<IFuncAttr>())
1636 return emitIFuncDefinition(GD);
1638 // If this is CUDA, be selective about which declarations we emit.
1639 if (LangOpts.CUDA) {
1640 if (LangOpts.CUDAIsDevice) {
1641 if (!Global->hasAttr<CUDADeviceAttr>() &&
1642 !Global->hasAttr<CUDAGlobalAttr>() &&
1643 !Global->hasAttr<CUDAConstantAttr>() &&
1644 !Global->hasAttr<CUDASharedAttr>())
1647 // We need to emit host-side 'shadows' for all global
1648 // device-side variables because the CUDA runtime needs their
1649 // size and host-side address in order to provide access to
1650 // their device-side incarnations.
1652 // So device-only functions are the only things we skip.
1653 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1654 Global->hasAttr<CUDADeviceAttr>())
1657 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1658 "Expected Variable or Function");
1662 if (LangOpts.OpenMP) {
1663 // If this is OpenMP device, check if it is legal to emit this global
1665 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1667 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1668 if (MustBeEmitted(Global))
1669 EmitOMPDeclareReduction(DRD);
1674 // Ignore declarations, they will be emitted on their first use.
1675 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1676 // Forward declarations are emitted lazily on first use.
1677 if (!FD->doesThisDeclarationHaveABody()) {
1678 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1681 StringRef MangledName = getMangledName(GD);
1683 // Compute the function info and LLVM type.
1684 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1685 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1687 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1688 /*DontDefer=*/false);
1692 const auto *VD = cast<VarDecl>(Global);
1693 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1694 // We need to emit device-side global CUDA variables even if a
1695 // variable does not have a definition -- we still need to define
1696 // host-side shadow for it.
1697 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1698 !VD->hasDefinition() &&
1699 (VD->hasAttr<CUDAConstantAttr>() ||
1700 VD->hasAttr<CUDADeviceAttr>());
1701 if (!MustEmitForCuda &&
1702 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1703 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1704 // If this declaration may have caused an inline variable definition to
1705 // change linkage, make sure that it's emitted.
1706 if (Context.getInlineVariableDefinitionKind(VD) ==
1707 ASTContext::InlineVariableDefinitionKind::Strong)
1708 GetAddrOfGlobalVar(VD);
1713 // Defer code generation to first use when possible, e.g. if this is an inline
1714 // function. If the global must always be emitted, do it eagerly if possible
1715 // to benefit from cache locality.
1716 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1717 // Emit the definition if it can't be deferred.
1718 EmitGlobalDefinition(GD);
1722 // If we're deferring emission of a C++ variable with an
1723 // initializer, remember the order in which it appeared in the file.
1724 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1725 cast<VarDecl>(Global)->hasInit()) {
1726 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1727 CXXGlobalInits.push_back(nullptr);
1730 StringRef MangledName = getMangledName(GD);
1731 if (GetGlobalValue(MangledName) != nullptr) {
1732 // The value has already been used and should therefore be emitted.
1733 addDeferredDeclToEmit(GD);
1734 } else if (MustBeEmitted(Global)) {
1735 // The value must be emitted, but cannot be emitted eagerly.
1736 assert(!MayBeEmittedEagerly(Global));
1737 addDeferredDeclToEmit(GD);
1739 // Otherwise, remember that we saw a deferred decl with this name. The
1740 // first use of the mangled name will cause it to move into
1741 // DeferredDeclsToEmit.
1742 DeferredDecls[MangledName] = GD;
1746 // Check if T is a class type with a destructor that's not dllimport.
1747 static bool HasNonDllImportDtor(QualType T) {
1748 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1749 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1750 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1757 struct FunctionIsDirectlyRecursive :
1758 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1759 const StringRef Name;
1760 const Builtin::Context &BI;
1762 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1763 Name(N), BI(C), Result(false) {
1765 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1767 bool TraverseCallExpr(CallExpr *E) {
1768 const FunctionDecl *FD = E->getDirectCallee();
1771 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1772 if (Attr && Name == Attr->getLabel()) {
1776 unsigned BuiltinID = FD->getBuiltinID();
1777 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1779 StringRef BuiltinName = BI.getName(BuiltinID);
1780 if (BuiltinName.startswith("__builtin_") &&
1781 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1789 // Make sure we're not referencing non-imported vars or functions.
1790 struct DLLImportFunctionVisitor
1791 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1792 bool SafeToInline = true;
1794 bool shouldVisitImplicitCode() const { return true; }
1796 bool VisitVarDecl(VarDecl *VD) {
1797 if (VD->getTLSKind()) {
1798 // A thread-local variable cannot be imported.
1799 SafeToInline = false;
1800 return SafeToInline;
1803 // A variable definition might imply a destructor call.
1804 if (VD->isThisDeclarationADefinition())
1805 SafeToInline = !HasNonDllImportDtor(VD->getType());
1807 return SafeToInline;
1810 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1811 if (const auto *D = E->getTemporary()->getDestructor())
1812 SafeToInline = D->hasAttr<DLLImportAttr>();
1813 return SafeToInline;
1816 bool VisitDeclRefExpr(DeclRefExpr *E) {
1817 ValueDecl *VD = E->getDecl();
1818 if (isa<FunctionDecl>(VD))
1819 SafeToInline = VD->hasAttr<DLLImportAttr>();
1820 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1821 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1822 return SafeToInline;
1825 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1826 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1827 return SafeToInline;
1830 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1831 CXXMethodDecl *M = E->getMethodDecl();
1833 // Call through a pointer to member function. This is safe to inline.
1834 SafeToInline = true;
1836 SafeToInline = M->hasAttr<DLLImportAttr>();
1838 return SafeToInline;
1841 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1842 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1843 return SafeToInline;
1846 bool VisitCXXNewExpr(CXXNewExpr *E) {
1847 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1848 return SafeToInline;
1853 // isTriviallyRecursive - Check if this function calls another
1854 // decl that, because of the asm attribute or the other decl being a builtin,
1855 // ends up pointing to itself.
1857 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1859 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1860 // asm labels are a special kind of mangling we have to support.
1861 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1864 Name = Attr->getLabel();
1866 Name = FD->getName();
1869 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1870 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1871 return Walker.Result;
1874 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1875 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1877 const auto *F = cast<FunctionDecl>(GD.getDecl());
1878 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1881 if (F->hasAttr<DLLImportAttr>()) {
1882 // Check whether it would be safe to inline this dllimport function.
1883 DLLImportFunctionVisitor Visitor;
1884 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1885 if (!Visitor.SafeToInline)
1888 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1889 // Implicit destructor invocations aren't captured in the AST, so the
1890 // check above can't see them. Check for them manually here.
1891 for (const Decl *Member : Dtor->getParent()->decls())
1892 if (isa<FieldDecl>(Member))
1893 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1895 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1896 if (HasNonDllImportDtor(B.getType()))
1901 // PR9614. Avoid cases where the source code is lying to us. An available
1902 // externally function should have an equivalent function somewhere else,
1903 // but a function that calls itself is clearly not equivalent to the real
1905 // This happens in glibc's btowc and in some configure checks.
1906 return !isTriviallyRecursive(F);
1909 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1910 const auto *D = cast<ValueDecl>(GD.getDecl());
1912 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1913 Context.getSourceManager(),
1914 "Generating code for declaration");
1916 if (isa<FunctionDecl>(D)) {
1917 // At -O0, don't generate IR for functions with available_externally
1919 if (!shouldEmitFunction(GD))
1922 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1923 // Make sure to emit the definition(s) before we emit the thunks.
1924 // This is necessary for the generation of certain thunks.
1925 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1926 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1927 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1928 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1930 EmitGlobalFunctionDefinition(GD, GV);
1932 if (Method->isVirtual())
1933 getVTables().EmitThunks(GD);
1938 return EmitGlobalFunctionDefinition(GD, GV);
1941 if (const auto *VD = dyn_cast<VarDecl>(D))
1942 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1944 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1947 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1948 llvm::Function *NewFn);
1950 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1951 /// module, create and return an llvm Function with the specified type. If there
1952 /// is something in the module with the specified name, return it potentially
1953 /// bitcasted to the right type.
1955 /// If D is non-null, it specifies a decl that correspond to this. This is used
1956 /// to set the attributes on the function when it is first created.
1957 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
1958 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
1959 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
1960 ForDefinition_t IsForDefinition) {
1961 const Decl *D = GD.getDecl();
1963 // Lookup the entry, lazily creating it if necessary.
1964 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1966 if (WeakRefReferences.erase(Entry)) {
1967 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1968 if (FD && !FD->hasAttr<WeakAttr>())
1969 Entry->setLinkage(llvm::Function::ExternalLinkage);
1972 // Handle dropped DLL attributes.
1973 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1974 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1976 // If there are two attempts to define the same mangled name, issue an
1978 if (IsForDefinition && !Entry->isDeclaration()) {
1980 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1981 // to make sure that we issue an error only once.
1982 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1983 (GD.getCanonicalDecl().getDecl() !=
1984 OtherGD.getCanonicalDecl().getDecl()) &&
1985 DiagnosedConflictingDefinitions.insert(GD).second) {
1986 getDiags().Report(D->getLocation(),
1987 diag::err_duplicate_mangled_name);
1988 getDiags().Report(OtherGD.getDecl()->getLocation(),
1989 diag::note_previous_definition);
1993 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1994 (Entry->getType()->getElementType() == Ty)) {
1998 // Make sure the result is of the correct type.
1999 // (If function is requested for a definition, we always need to create a new
2000 // function, not just return a bitcast.)
2001 if (!IsForDefinition)
2002 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2005 // This function doesn't have a complete type (for example, the return
2006 // type is an incomplete struct). Use a fake type instead, and make
2007 // sure not to try to set attributes.
2008 bool IsIncompleteFunction = false;
2010 llvm::FunctionType *FTy;
2011 if (isa<llvm::FunctionType>(Ty)) {
2012 FTy = cast<llvm::FunctionType>(Ty);
2014 FTy = llvm::FunctionType::get(VoidTy, false);
2015 IsIncompleteFunction = true;
2019 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2020 Entry ? StringRef() : MangledName, &getModule());
2022 // If we already created a function with the same mangled name (but different
2023 // type) before, take its name and add it to the list of functions to be
2024 // replaced with F at the end of CodeGen.
2026 // This happens if there is a prototype for a function (e.g. "int f()") and
2027 // then a definition of a different type (e.g. "int f(int x)").
2031 // This might be an implementation of a function without a prototype, in
2032 // which case, try to do special replacement of calls which match the new
2033 // prototype. The really key thing here is that we also potentially drop
2034 // arguments from the call site so as to make a direct call, which makes the
2035 // inliner happier and suppresses a number of optimizer warnings (!) about
2036 // dropping arguments.
2037 if (!Entry->use_empty()) {
2038 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2039 Entry->removeDeadConstantUsers();
2042 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2043 F, Entry->getType()->getElementType()->getPointerTo());
2044 addGlobalValReplacement(Entry, BC);
2047 assert(F->getName() == MangledName && "name was uniqued!");
2049 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2050 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2051 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2052 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2056 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2057 // each other bottoming out with the base dtor. Therefore we emit non-base
2058 // dtors on usage, even if there is no dtor definition in the TU.
2059 if (D && isa<CXXDestructorDecl>(D) &&
2060 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2062 addDeferredDeclToEmit(GD);
2064 // This is the first use or definition of a mangled name. If there is a
2065 // deferred decl with this name, remember that we need to emit it at the end
2067 auto DDI = DeferredDecls.find(MangledName);
2068 if (DDI != DeferredDecls.end()) {
2069 // Move the potentially referenced deferred decl to the
2070 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2071 // don't need it anymore).
2072 addDeferredDeclToEmit(DDI->second);
2073 DeferredDecls.erase(DDI);
2075 // Otherwise, there are cases we have to worry about where we're
2076 // using a declaration for which we must emit a definition but where
2077 // we might not find a top-level definition:
2078 // - member functions defined inline in their classes
2079 // - friend functions defined inline in some class
2080 // - special member functions with implicit definitions
2081 // If we ever change our AST traversal to walk into class methods,
2082 // this will be unnecessary.
2084 // We also don't emit a definition for a function if it's going to be an
2085 // entry in a vtable, unless it's already marked as used.
2086 } else if (getLangOpts().CPlusPlus && D) {
2087 // Look for a declaration that's lexically in a record.
2088 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2089 FD = FD->getPreviousDecl()) {
2090 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2091 if (FD->doesThisDeclarationHaveABody()) {
2092 addDeferredDeclToEmit(GD.getWithDecl(FD));
2100 // Make sure the result is of the requested type.
2101 if (!IsIncompleteFunction) {
2102 assert(F->getType()->getElementType() == Ty);
2106 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2107 return llvm::ConstantExpr::getBitCast(F, PTy);
2110 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2111 /// non-null, then this function will use the specified type if it has to
2112 /// create it (this occurs when we see a definition of the function).
2113 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2117 ForDefinition_t IsForDefinition) {
2118 // If there was no specific requested type, just convert it now.
2120 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2121 auto CanonTy = Context.getCanonicalType(FD->getType());
2122 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2125 StringRef MangledName = getMangledName(GD);
2126 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2127 /*IsThunk=*/false, llvm::AttributeList(),
2131 static const FunctionDecl *
2132 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2133 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2134 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2136 IdentifierInfo &CII = C.Idents.get(Name);
2137 for (const auto &Result : DC->lookup(&CII))
2138 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2141 if (!C.getLangOpts().CPlusPlus)
2144 // Demangle the premangled name from getTerminateFn()
2145 IdentifierInfo &CXXII =
2146 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2147 ? C.Idents.get("terminate")
2148 : C.Idents.get(Name);
2150 for (const auto &N : {"__cxxabiv1", "std"}) {
2151 IdentifierInfo &NS = C.Idents.get(N);
2152 for (const auto &Result : DC->lookup(&NS)) {
2153 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2154 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2155 for (const auto &Result : LSD->lookup(&NS))
2156 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2160 for (const auto &Result : ND->lookup(&CXXII))
2161 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2169 /// CreateRuntimeFunction - Create a new runtime function with the specified
2172 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2173 llvm::AttributeList ExtraAttrs,
2176 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2177 /*DontDefer=*/false, /*IsThunk=*/false,
2180 if (auto *F = dyn_cast<llvm::Function>(C)) {
2182 F->setCallingConv(getRuntimeCC());
2184 if (!Local && getTriple().isOSBinFormatCOFF() &&
2185 !getCodeGenOpts().LTOVisibilityPublicStd) {
2186 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2187 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2188 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2189 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2198 /// CreateBuiltinFunction - Create a new builtin function with the specified
2201 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2202 llvm::AttributeList ExtraAttrs) {
2204 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2205 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2206 if (auto *F = dyn_cast<llvm::Function>(C))
2208 F->setCallingConv(getBuiltinCC());
2212 /// isTypeConstant - Determine whether an object of this type can be emitted
2215 /// If ExcludeCtor is true, the duration when the object's constructor runs
2216 /// will not be considered. The caller will need to verify that the object is
2217 /// not written to during its construction.
2218 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2219 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2222 if (Context.getLangOpts().CPlusPlus) {
2223 if (const CXXRecordDecl *Record
2224 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2225 return ExcludeCtor && !Record->hasMutableFields() &&
2226 Record->hasTrivialDestructor();
2232 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2233 /// create and return an llvm GlobalVariable with the specified type. If there
2234 /// is something in the module with the specified name, return it potentially
2235 /// bitcasted to the right type.
2237 /// If D is non-null, it specifies a decl that correspond to this. This is used
2238 /// to set the attributes on the global when it is first created.
2240 /// If IsForDefinition is true, it is guranteed that an actual global with
2241 /// type Ty will be returned, not conversion of a variable with the same
2242 /// mangled name but some other type.
2244 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2245 llvm::PointerType *Ty,
2247 ForDefinition_t IsForDefinition) {
2248 // Lookup the entry, lazily creating it if necessary.
2249 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2251 if (WeakRefReferences.erase(Entry)) {
2252 if (D && !D->hasAttr<WeakAttr>())
2253 Entry->setLinkage(llvm::Function::ExternalLinkage);
2256 // Handle dropped DLL attributes.
2257 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2258 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2260 if (Entry->getType() == Ty)
2263 // If there are two attempts to define the same mangled name, issue an
2265 if (IsForDefinition && !Entry->isDeclaration()) {
2267 const VarDecl *OtherD;
2269 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2270 // to make sure that we issue an error only once.
2271 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2272 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2273 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2274 OtherD->hasInit() &&
2275 DiagnosedConflictingDefinitions.insert(D).second) {
2276 getDiags().Report(D->getLocation(),
2277 diag::err_duplicate_mangled_name);
2278 getDiags().Report(OtherGD.getDecl()->getLocation(),
2279 diag::note_previous_definition);
2283 // Make sure the result is of the correct type.
2284 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2285 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2287 // (If global is requested for a definition, we always need to create a new
2288 // global, not just return a bitcast.)
2289 if (!IsForDefinition)
2290 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2293 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2294 auto *GV = new llvm::GlobalVariable(
2295 getModule(), Ty->getElementType(), false,
2296 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2297 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2299 // If we already created a global with the same mangled name (but different
2300 // type) before, take its name and remove it from its parent.
2302 GV->takeName(Entry);
2304 if (!Entry->use_empty()) {
2305 llvm::Constant *NewPtrForOldDecl =
2306 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2307 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2310 Entry->eraseFromParent();
2313 // This is the first use or definition of a mangled name. If there is a
2314 // deferred decl with this name, remember that we need to emit it at the end
2316 auto DDI = DeferredDecls.find(MangledName);
2317 if (DDI != DeferredDecls.end()) {
2318 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2319 // list, and remove it from DeferredDecls (since we don't need it anymore).
2320 addDeferredDeclToEmit(DDI->second);
2321 DeferredDecls.erase(DDI);
2324 // Handle things which are present even on external declarations.
2326 // FIXME: This code is overly simple and should be merged with other global
2328 GV->setConstant(isTypeConstant(D->getType(), false));
2330 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2332 setLinkageAndVisibilityForGV(GV, D);
2334 if (D->getTLSKind()) {
2335 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2336 CXXThreadLocals.push_back(D);
2340 // If required by the ABI, treat declarations of static data members with
2341 // inline initializers as definitions.
2342 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2343 EmitGlobalVarDefinition(D);
2346 // Handle XCore specific ABI requirements.
2347 if (getTriple().getArch() == llvm::Triple::xcore &&
2348 D->getLanguageLinkage() == CLanguageLinkage &&
2349 D->getType().isConstant(Context) &&
2350 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2351 GV->setSection(".cp.rodata");
2354 if (AddrSpace != Ty->getAddressSpace())
2355 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2361 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2362 ForDefinition_t IsForDefinition) {
2363 const Decl *D = GD.getDecl();
2364 if (isa<CXXConstructorDecl>(D))
2365 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2366 getFromCtorType(GD.getCtorType()),
2367 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2368 /*DontDefer=*/false, IsForDefinition);
2369 else if (isa<CXXDestructorDecl>(D))
2370 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2371 getFromDtorType(GD.getDtorType()),
2372 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2373 /*DontDefer=*/false, IsForDefinition);
2374 else if (isa<CXXMethodDecl>(D)) {
2375 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2376 cast<CXXMethodDecl>(D));
2377 auto Ty = getTypes().GetFunctionType(*FInfo);
2378 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2380 } else if (isa<FunctionDecl>(D)) {
2381 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2382 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2383 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2386 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2390 llvm::GlobalVariable *
2391 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2393 llvm::GlobalValue::LinkageTypes Linkage) {
2394 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2395 llvm::GlobalVariable *OldGV = nullptr;
2398 // Check if the variable has the right type.
2399 if (GV->getType()->getElementType() == Ty)
2402 // Because C++ name mangling, the only way we can end up with an already
2403 // existing global with the same name is if it has been declared extern "C".
2404 assert(GV->isDeclaration() && "Declaration has wrong type!");
2408 // Create a new variable.
2409 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2410 Linkage, nullptr, Name);
2413 // Replace occurrences of the old variable if needed.
2414 GV->takeName(OldGV);
2416 if (!OldGV->use_empty()) {
2417 llvm::Constant *NewPtrForOldDecl =
2418 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2419 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2422 OldGV->eraseFromParent();
2425 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2426 !GV->hasAvailableExternallyLinkage())
2427 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2432 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2433 /// given global variable. If Ty is non-null and if the global doesn't exist,
2434 /// then it will be created with the specified type instead of whatever the
2435 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2436 /// that an actual global with type Ty will be returned, not conversion of a
2437 /// variable with the same mangled name but some other type.
2438 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2440 ForDefinition_t IsForDefinition) {
2441 assert(D->hasGlobalStorage() && "Not a global variable");
2442 QualType ASTTy = D->getType();
2444 Ty = getTypes().ConvertTypeForMem(ASTTy);
2446 llvm::PointerType *PTy =
2447 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2449 StringRef MangledName = getMangledName(D);
2450 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2453 /// CreateRuntimeVariable - Create a new runtime global variable with the
2454 /// specified type and name.
2456 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2458 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2461 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2462 assert(!D->getInit() && "Cannot emit definite definitions here!");
2464 StringRef MangledName = getMangledName(D);
2465 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2467 // We already have a definition, not declaration, with the same mangled name.
2468 // Emitting of declaration is not required (and actually overwrites emitted
2470 if (GV && !GV->isDeclaration())
2473 // If we have not seen a reference to this variable yet, place it into the
2474 // deferred declarations table to be emitted if needed later.
2475 if (!MustBeEmitted(D) && !GV) {
2476 DeferredDecls[MangledName] = D;
2480 // The tentative definition is the only definition.
2481 EmitGlobalVarDefinition(D);
2484 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2485 return Context.toCharUnitsFromBits(
2486 getDataLayout().getTypeStoreSizeInBits(Ty));
2489 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2490 unsigned AddrSpace) {
2491 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2492 if (D->hasAttr<CUDAConstantAttr>())
2493 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2494 else if (D->hasAttr<CUDASharedAttr>())
2495 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2497 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2503 template<typename SomeDecl>
2504 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2505 llvm::GlobalValue *GV) {
2506 if (!getLangOpts().CPlusPlus)
2509 // Must have 'used' attribute, or else inline assembly can't rely on
2510 // the name existing.
2511 if (!D->template hasAttr<UsedAttr>())
2514 // Must have internal linkage and an ordinary name.
2515 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2518 // Must be in an extern "C" context. Entities declared directly within
2519 // a record are not extern "C" even if the record is in such a context.
2520 const SomeDecl *First = D->getFirstDecl();
2521 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2524 // OK, this is an internal linkage entity inside an extern "C" linkage
2525 // specification. Make a note of that so we can give it the "expected"
2526 // mangled name if nothing else is using that name.
2527 std::pair<StaticExternCMap::iterator, bool> R =
2528 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2530 // If we have multiple internal linkage entities with the same name
2531 // in extern "C" regions, none of them gets that name.
2533 R.first->second = nullptr;
2536 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2537 if (!CGM.supportsCOMDAT())
2540 if (D.hasAttr<SelectAnyAttr>())
2544 if (auto *VD = dyn_cast<VarDecl>(&D))
2545 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2547 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2551 case GVA_AvailableExternally:
2552 case GVA_StrongExternal:
2554 case GVA_DiscardableODR:
2558 llvm_unreachable("No such linkage");
2561 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2562 llvm::GlobalObject &GO) {
2563 if (!shouldBeInCOMDAT(*this, D))
2565 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2568 /// Pass IsTentative as true if you want to create a tentative definition.
2569 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2571 // OpenCL global variables of sampler type are translated to function calls,
2572 // therefore no need to be translated.
2573 QualType ASTTy = D->getType();
2574 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2577 llvm::Constant *Init = nullptr;
2578 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2579 bool NeedsGlobalCtor = false;
2580 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2582 const VarDecl *InitDecl;
2583 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2585 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2586 // as part of their declaration." Sema has already checked for
2587 // error cases, so we just need to set Init to UndefValue.
2588 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2589 D->hasAttr<CUDASharedAttr>())
2590 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2591 else if (!InitExpr) {
2592 // This is a tentative definition; tentative definitions are
2593 // implicitly initialized with { 0 }.
2595 // Note that tentative definitions are only emitted at the end of
2596 // a translation unit, so they should never have incomplete
2597 // type. In addition, EmitTentativeDefinition makes sure that we
2598 // never attempt to emit a tentative definition if a real one
2599 // exists. A use may still exists, however, so we still may need
2601 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2602 Init = EmitNullConstant(D->getType());
2604 initializedGlobalDecl = GlobalDecl(D);
2605 Init = EmitConstantInit(*InitDecl);
2608 QualType T = InitExpr->getType();
2609 if (D->getType()->isReferenceType())
2612 if (getLangOpts().CPlusPlus) {
2613 Init = EmitNullConstant(T);
2614 NeedsGlobalCtor = true;
2616 ErrorUnsupported(D, "static initializer");
2617 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2620 // We don't need an initializer, so remove the entry for the delayed
2621 // initializer position (just in case this entry was delayed) if we
2622 // also don't need to register a destructor.
2623 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2624 DelayedCXXInitPosition.erase(D);
2628 llvm::Type* InitType = Init->getType();
2629 llvm::Constant *Entry =
2630 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2632 // Strip off a bitcast if we got one back.
2633 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2634 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2635 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2636 // All zero index gep.
2637 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2638 Entry = CE->getOperand(0);
2641 // Entry is now either a Function or GlobalVariable.
2642 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2644 // We have a definition after a declaration with the wrong type.
2645 // We must make a new GlobalVariable* and update everything that used OldGV
2646 // (a declaration or tentative definition) with the new GlobalVariable*
2647 // (which will be a definition).
2649 // This happens if there is a prototype for a global (e.g.
2650 // "extern int x[];") and then a definition of a different type (e.g.
2651 // "int x[10];"). This also happens when an initializer has a different type
2652 // from the type of the global (this happens with unions).
2654 GV->getType()->getElementType() != InitType ||
2655 GV->getType()->getAddressSpace() !=
2656 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2658 // Move the old entry aside so that we'll create a new one.
2659 Entry->setName(StringRef());
2661 // Make a new global with the correct type, this is now guaranteed to work.
2662 GV = cast<llvm::GlobalVariable>(
2663 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2665 // Replace all uses of the old global with the new global
2666 llvm::Constant *NewPtrForOldDecl =
2667 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2668 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2670 // Erase the old global, since it is no longer used.
2671 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2674 MaybeHandleStaticInExternC(D, GV);
2676 if (D->hasAttr<AnnotateAttr>())
2677 AddGlobalAnnotations(D, GV);
2679 // Set the llvm linkage type as appropriate.
2680 llvm::GlobalValue::LinkageTypes Linkage =
2681 getLLVMLinkageVarDefinition(D, GV->isConstant());
2683 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2684 // the device. [...]"
2685 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2686 // __device__, declares a variable that: [...]
2687 // Is accessible from all the threads within the grid and from the host
2688 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2689 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2690 if (GV && LangOpts.CUDA) {
2691 if (LangOpts.CUDAIsDevice) {
2692 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2693 GV->setExternallyInitialized(true);
2695 // Host-side shadows of external declarations of device-side
2696 // global variables become internal definitions. These have to
2697 // be internal in order to prevent name conflicts with global
2698 // host variables with the same name in a different TUs.
2699 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2700 Linkage = llvm::GlobalValue::InternalLinkage;
2702 // Shadow variables and their properties must be registered
2703 // with CUDA runtime.
2705 if (!D->hasDefinition())
2706 Flags |= CGCUDARuntime::ExternDeviceVar;
2707 if (D->hasAttr<CUDAConstantAttr>())
2708 Flags |= CGCUDARuntime::ConstantDeviceVar;
2709 getCUDARuntime().registerDeviceVar(*GV, Flags);
2710 } else if (D->hasAttr<CUDASharedAttr>())
2711 // __shared__ variables are odd. Shadows do get created, but
2712 // they are not registered with the CUDA runtime, so they
2713 // can't really be used to access their device-side
2714 // counterparts. It's not clear yet whether it's nvcc's bug or
2715 // a feature, but we've got to do the same for compatibility.
2716 Linkage = llvm::GlobalValue::InternalLinkage;
2719 GV->setInitializer(Init);
2721 // If it is safe to mark the global 'constant', do so now.
2722 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2723 isTypeConstant(D->getType(), true));
2725 // If it is in a read-only section, mark it 'constant'.
2726 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2727 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2728 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2729 GV->setConstant(true);
2732 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2735 // On Darwin, if the normal linkage of a C++ thread_local variable is
2736 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2737 // copies within a linkage unit; otherwise, the backing variable has
2738 // internal linkage and all accesses should just be calls to the
2739 // Itanium-specified entry point, which has the normal linkage of the
2740 // variable. This is to preserve the ability to change the implementation
2741 // behind the scenes.
2742 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2743 Context.getTargetInfo().getTriple().isOSDarwin() &&
2744 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2745 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2746 Linkage = llvm::GlobalValue::InternalLinkage;
2748 GV->setLinkage(Linkage);
2749 if (D->hasAttr<DLLImportAttr>())
2750 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2751 else if (D->hasAttr<DLLExportAttr>())
2752 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2754 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2756 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2757 // common vars aren't constant even if declared const.
2758 GV->setConstant(false);
2759 // Tentative definition of global variables may be initialized with
2760 // non-zero null pointers. In this case they should have weak linkage
2761 // since common linkage must have zero initializer and must not have
2762 // explicit section therefore cannot have non-zero initial value.
2763 if (!GV->getInitializer()->isNullValue())
2764 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2767 setNonAliasAttributes(D, GV);
2769 if (D->getTLSKind() && !GV->isThreadLocal()) {
2770 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2771 CXXThreadLocals.push_back(D);
2775 maybeSetTrivialComdat(*D, *GV);
2777 // Emit the initializer function if necessary.
2778 if (NeedsGlobalCtor || NeedsGlobalDtor)
2779 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2781 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2783 // Emit global variable debug information.
2784 if (CGDebugInfo *DI = getModuleDebugInfo())
2785 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2786 DI->EmitGlobalVariable(GV, D);
2789 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2790 CodeGenModule &CGM, const VarDecl *D,
2792 // Don't give variables common linkage if -fno-common was specified unless it
2793 // was overridden by a NoCommon attribute.
2794 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2798 // A declaration of an identifier for an object that has file scope without
2799 // an initializer, and without a storage-class specifier or with the
2800 // storage-class specifier static, constitutes a tentative definition.
2801 if (D->getInit() || D->hasExternalStorage())
2804 // A variable cannot be both common and exist in a section.
2805 if (D->hasAttr<SectionAttr>())
2808 // Thread local vars aren't considered common linkage.
2809 if (D->getTLSKind())
2812 // Tentative definitions marked with WeakImportAttr are true definitions.
2813 if (D->hasAttr<WeakImportAttr>())
2816 // A variable cannot be both common and exist in a comdat.
2817 if (shouldBeInCOMDAT(CGM, *D))
2820 // Declarations with a required alignment do not have common linkage in MSVC
2822 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2823 if (D->hasAttr<AlignedAttr>())
2825 QualType VarType = D->getType();
2826 if (Context.isAlignmentRequired(VarType))
2829 if (const auto *RT = VarType->getAs<RecordType>()) {
2830 const RecordDecl *RD = RT->getDecl();
2831 for (const FieldDecl *FD : RD->fields()) {
2832 if (FD->isBitField())
2834 if (FD->hasAttr<AlignedAttr>())
2836 if (Context.isAlignmentRequired(FD->getType()))
2845 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2846 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2847 if (Linkage == GVA_Internal)
2848 return llvm::Function::InternalLinkage;
2850 if (D->hasAttr<WeakAttr>()) {
2851 if (IsConstantVariable)
2852 return llvm::GlobalVariable::WeakODRLinkage;
2854 return llvm::GlobalVariable::WeakAnyLinkage;
2857 // We are guaranteed to have a strong definition somewhere else,
2858 // so we can use available_externally linkage.
2859 if (Linkage == GVA_AvailableExternally)
2860 return llvm::GlobalValue::AvailableExternallyLinkage;
2862 // Note that Apple's kernel linker doesn't support symbol
2863 // coalescing, so we need to avoid linkonce and weak linkages there.
2864 // Normally, this means we just map to internal, but for explicit
2865 // instantiations we'll map to external.
2867 // In C++, the compiler has to emit a definition in every translation unit
2868 // that references the function. We should use linkonce_odr because
2869 // a) if all references in this translation unit are optimized away, we
2870 // don't need to codegen it. b) if the function persists, it needs to be
2871 // merged with other definitions. c) C++ has the ODR, so we know the
2872 // definition is dependable.
2873 if (Linkage == GVA_DiscardableODR)
2874 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2875 : llvm::Function::InternalLinkage;
2877 // An explicit instantiation of a template has weak linkage, since
2878 // explicit instantiations can occur in multiple translation units
2879 // and must all be equivalent. However, we are not allowed to
2880 // throw away these explicit instantiations.
2882 // We don't currently support CUDA device code spread out across multiple TUs,
2883 // so say that CUDA templates are either external (for kernels) or internal.
2884 // This lets llvm perform aggressive inter-procedural optimizations.
2885 if (Linkage == GVA_StrongODR) {
2886 if (Context.getLangOpts().AppleKext)
2887 return llvm::Function::ExternalLinkage;
2888 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2889 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2890 : llvm::Function::InternalLinkage;
2891 return llvm::Function::WeakODRLinkage;
2894 // C++ doesn't have tentative definitions and thus cannot have common
2896 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2897 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2898 CodeGenOpts.NoCommon))
2899 return llvm::GlobalVariable::CommonLinkage;
2901 // selectany symbols are externally visible, so use weak instead of
2902 // linkonce. MSVC optimizes away references to const selectany globals, so
2903 // all definitions should be the same and ODR linkage should be used.
2904 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2905 if (D->hasAttr<SelectAnyAttr>())
2906 return llvm::GlobalVariable::WeakODRLinkage;
2908 // Otherwise, we have strong external linkage.
2909 assert(Linkage == GVA_StrongExternal);
2910 return llvm::GlobalVariable::ExternalLinkage;
2913 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2914 const VarDecl *VD, bool IsConstant) {
2915 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2916 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2919 /// Replace the uses of a function that was declared with a non-proto type.
2920 /// We want to silently drop extra arguments from call sites
2921 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2922 llvm::Function *newFn) {
2924 if (old->use_empty()) return;
2926 llvm::Type *newRetTy = newFn->getReturnType();
2927 SmallVector<llvm::Value*, 4> newArgs;
2928 SmallVector<llvm::OperandBundleDef, 1> newBundles;
2930 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2932 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2933 llvm::User *user = use->getUser();
2935 // Recognize and replace uses of bitcasts. Most calls to
2936 // unprototyped functions will use bitcasts.
2937 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2938 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2939 replaceUsesOfNonProtoConstant(bitcast, newFn);
2943 // Recognize calls to the function.
2944 llvm::CallSite callSite(user);
2945 if (!callSite) continue;
2946 if (!callSite.isCallee(&*use)) continue;
2948 // If the return types don't match exactly, then we can't
2949 // transform this call unless it's dead.
2950 if (callSite->getType() != newRetTy && !callSite->use_empty())
2953 // Get the call site's attribute list.
2954 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
2955 llvm::AttributeList oldAttrs = callSite.getAttributes();
2957 // If the function was passed too few arguments, don't transform.
2958 unsigned newNumArgs = newFn->arg_size();
2959 if (callSite.arg_size() < newNumArgs) continue;
2961 // If extra arguments were passed, we silently drop them.
2962 // If any of the types mismatch, we don't transform.
2964 bool dontTransform = false;
2965 for (llvm::Argument &A : newFn->args()) {
2966 if (callSite.getArgument(argNo)->getType() != A.getType()) {
2967 dontTransform = true;
2971 // Add any parameter attributes.
2972 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
2978 // Okay, we can transform this. Create the new call instruction and copy
2979 // over the required information.
2980 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2982 // Copy over any operand bundles.
2983 callSite.getOperandBundlesAsDefs(newBundles);
2985 llvm::CallSite newCall;
2986 if (callSite.isCall()) {
2987 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2988 callSite.getInstruction());
2990 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2991 newCall = llvm::InvokeInst::Create(newFn,
2992 oldInvoke->getNormalDest(),
2993 oldInvoke->getUnwindDest(),
2994 newArgs, newBundles, "",
2995 callSite.getInstruction());
2997 newArgs.clear(); // for the next iteration
2999 if (!newCall->getType()->isVoidTy())
3000 newCall->takeName(callSite.getInstruction());
3001 newCall.setAttributes(llvm::AttributeList::get(
3002 newFn->getContext(), oldAttrs.getFnAttributes(),
3003 oldAttrs.getRetAttributes(), newArgAttrs));
3004 newCall.setCallingConv(callSite.getCallingConv());
3006 // Finally, remove the old call, replacing any uses with the new one.
3007 if (!callSite->use_empty())
3008 callSite->replaceAllUsesWith(newCall.getInstruction());
3010 // Copy debug location attached to CI.
3011 if (callSite->getDebugLoc())
3012 newCall->setDebugLoc(callSite->getDebugLoc());
3014 callSite->eraseFromParent();
3018 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3019 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3020 /// existing call uses of the old function in the module, this adjusts them to
3021 /// call the new function directly.
3023 /// This is not just a cleanup: the always_inline pass requires direct calls to
3024 /// functions to be able to inline them. If there is a bitcast in the way, it
3025 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3027 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3028 llvm::Function *NewFn) {
3029 // If we're redefining a global as a function, don't transform it.
3030 if (!isa<llvm::Function>(Old)) return;
3032 replaceUsesOfNonProtoConstant(Old, NewFn);
3035 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3036 auto DK = VD->isThisDeclarationADefinition();
3037 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3040 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3041 // If we have a definition, this might be a deferred decl. If the
3042 // instantiation is explicit, make sure we emit it at the end.
3043 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3044 GetAddrOfGlobalVar(VD);
3046 EmitTopLevelDecl(VD);
3049 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3050 llvm::GlobalValue *GV) {
3051 const auto *D = cast<FunctionDecl>(GD.getDecl());
3053 // Compute the function info and LLVM type.
3054 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3055 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3057 // Get or create the prototype for the function.
3058 if (!GV || (GV->getType()->getElementType() != Ty))
3059 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3064 if (!GV->isDeclaration())
3067 // We need to set linkage and visibility on the function before
3068 // generating code for it because various parts of IR generation
3069 // want to propagate this information down (e.g. to local static
3071 auto *Fn = cast<llvm::Function>(GV);
3072 setFunctionLinkage(GD, Fn);
3073 setFunctionDLLStorageClass(GD, Fn);
3075 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3076 setGlobalVisibility(Fn, D);
3078 MaybeHandleStaticInExternC(D, Fn);
3080 maybeSetTrivialComdat(*D, *Fn);
3082 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3084 setFunctionDefinitionAttributes(D, Fn);
3085 SetLLVMFunctionAttributesForDefinition(D, Fn);
3087 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3088 AddGlobalCtor(Fn, CA->getPriority());
3089 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3090 AddGlobalDtor(Fn, DA->getPriority());
3091 if (D->hasAttr<AnnotateAttr>())
3092 AddGlobalAnnotations(D, Fn);
3095 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3096 const auto *D = cast<ValueDecl>(GD.getDecl());
3097 const AliasAttr *AA = D->getAttr<AliasAttr>();
3098 assert(AA && "Not an alias?");
3100 StringRef MangledName = getMangledName(GD);
3102 if (AA->getAliasee() == MangledName) {
3103 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3107 // If there is a definition in the module, then it wins over the alias.
3108 // This is dubious, but allow it to be safe. Just ignore the alias.
3109 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3110 if (Entry && !Entry->isDeclaration())
3113 Aliases.push_back(GD);
3115 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3117 // Create a reference to the named value. This ensures that it is emitted
3118 // if a deferred decl.
3119 llvm::Constant *Aliasee;
3120 if (isa<llvm::FunctionType>(DeclTy))
3121 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3122 /*ForVTable=*/false);
3124 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3125 llvm::PointerType::getUnqual(DeclTy),
3128 // Create the new alias itself, but don't set a name yet.
3129 auto *GA = llvm::GlobalAlias::create(
3130 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3133 if (GA->getAliasee() == Entry) {
3134 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3138 assert(Entry->isDeclaration());
3140 // If there is a declaration in the module, then we had an extern followed
3141 // by the alias, as in:
3142 // extern int test6();
3144 // int test6() __attribute__((alias("test7")));
3146 // Remove it and replace uses of it with the alias.
3147 GA->takeName(Entry);
3149 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3151 Entry->eraseFromParent();
3153 GA->setName(MangledName);
3156 // Set attributes which are particular to an alias; this is a
3157 // specialization of the attributes which may be set on a global
3158 // variable/function.
3159 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3160 D->isWeakImported()) {
3161 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3164 if (const auto *VD = dyn_cast<VarDecl>(D))
3165 if (VD->getTLSKind())
3166 setTLSMode(GA, *VD);
3168 setAliasAttributes(D, GA);
3171 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3172 const auto *D = cast<ValueDecl>(GD.getDecl());
3173 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3174 assert(IFA && "Not an ifunc?");
3176 StringRef MangledName = getMangledName(GD);
3178 if (IFA->getResolver() == MangledName) {
3179 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3183 // Report an error if some definition overrides ifunc.
3184 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3185 if (Entry && !Entry->isDeclaration()) {
3187 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3188 DiagnosedConflictingDefinitions.insert(GD).second) {
3189 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3190 Diags.Report(OtherGD.getDecl()->getLocation(),
3191 diag::note_previous_definition);
3196 Aliases.push_back(GD);
3198 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3199 llvm::Constant *Resolver =
3200 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3201 /*ForVTable=*/false);
3202 llvm::GlobalIFunc *GIF =
3203 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3204 "", Resolver, &getModule());
3206 if (GIF->getResolver() == Entry) {
3207 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3210 assert(Entry->isDeclaration());
3212 // If there is a declaration in the module, then we had an extern followed
3213 // by the ifunc, as in:
3214 // extern int test();
3216 // int test() __attribute__((ifunc("resolver")));
3218 // Remove it and replace uses of it with the ifunc.
3219 GIF->takeName(Entry);
3221 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3223 Entry->eraseFromParent();
3225 GIF->setName(MangledName);
3227 SetCommonAttributes(D, GIF);
3230 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3231 ArrayRef<llvm::Type*> Tys) {
3232 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3236 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3237 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3238 const StringLiteral *Literal, bool TargetIsLSB,
3239 bool &IsUTF16, unsigned &StringLength) {
3240 StringRef String = Literal->getString();
3241 unsigned NumBytes = String.size();
3243 // Check for simple case.
3244 if (!Literal->containsNonAsciiOrNull()) {
3245 StringLength = NumBytes;
3246 return *Map.insert(std::make_pair(String, nullptr)).first;
3249 // Otherwise, convert the UTF8 literals into a string of shorts.
3252 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3253 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3254 llvm::UTF16 *ToPtr = &ToBuf[0];
3256 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3257 ToPtr + NumBytes, llvm::strictConversion);
3259 // ConvertUTF8toUTF16 returns the length in ToPtr.
3260 StringLength = ToPtr - &ToBuf[0];
3262 // Add an explicit null.
3264 return *Map.insert(std::make_pair(
3265 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3266 (StringLength + 1) * 2),
3271 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3272 unsigned StringLength = 0;
3273 bool isUTF16 = false;
3274 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3275 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3276 getDataLayout().isLittleEndian(), isUTF16,
3279 if (auto *C = Entry.second)
3280 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3282 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3283 llvm::Constant *Zeros[] = { Zero, Zero };
3285 // If we don't already have it, get __CFConstantStringClassReference.
3286 if (!CFConstantStringClassRef) {
3287 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3288 Ty = llvm::ArrayType::get(Ty, 0);
3289 llvm::Constant *GV =
3290 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3292 if (getTriple().isOSBinFormatCOFF()) {
3293 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3294 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3295 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3296 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3298 const VarDecl *VD = nullptr;
3299 for (const auto &Result : DC->lookup(&II))
3300 if ((VD = dyn_cast<VarDecl>(Result)))
3303 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3304 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3305 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3307 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3308 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3312 // Decay array -> ptr
3313 CFConstantStringClassRef =
3314 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3317 QualType CFTy = getContext().getCFConstantStringType();
3319 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3321 ConstantInitBuilder Builder(*this);
3322 auto Fields = Builder.beginStruct(STy);
3325 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3328 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3331 llvm::Constant *C = nullptr;
3333 auto Arr = llvm::makeArrayRef(
3334 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3335 Entry.first().size() / 2);
3336 C = llvm::ConstantDataArray::get(VMContext, Arr);
3338 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3341 // Note: -fwritable-strings doesn't make the backing store strings of
3342 // CFStrings writable. (See <rdar://problem/10657500>)
3344 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3345 llvm::GlobalValue::PrivateLinkage, C, ".str");
3346 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3347 // Don't enforce the target's minimum global alignment, since the only use
3348 // of the string is via this class initializer.
3349 CharUnits Align = isUTF16
3350 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3351 : getContext().getTypeAlignInChars(getContext().CharTy);
3352 GV->setAlignment(Align.getQuantity());
3354 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3355 // Without it LLVM can merge the string with a non unnamed_addr one during
3356 // LTO. Doing that changes the section it ends in, which surprises ld64.
3357 if (getTriple().isOSBinFormatMachO())
3358 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3359 : "__TEXT,__cstring,cstring_literals");
3362 llvm::Constant *Str =
3363 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3366 // Cast the UTF16 string to the correct type.
3367 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3371 auto Ty = getTypes().ConvertType(getContext().LongTy);
3372 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3374 CharUnits Alignment = getPointerAlign();
3377 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3378 /*isConstant=*/false,
3379 llvm::GlobalVariable::PrivateLinkage);
3380 switch (getTriple().getObjectFormat()) {
3381 case llvm::Triple::UnknownObjectFormat:
3382 llvm_unreachable("unknown file format");
3383 case llvm::Triple::COFF:
3384 case llvm::Triple::ELF:
3385 case llvm::Triple::Wasm:
3386 GV->setSection("cfstring");
3388 case llvm::Triple::MachO:
3389 GV->setSection("__DATA,__cfstring");
3394 return ConstantAddress(GV, Alignment);
3397 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3398 if (ObjCFastEnumerationStateType.isNull()) {
3399 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3400 D->startDefinition();
3402 QualType FieldTypes[] = {
3403 Context.UnsignedLongTy,
3404 Context.getPointerType(Context.getObjCIdType()),
3405 Context.getPointerType(Context.UnsignedLongTy),
3406 Context.getConstantArrayType(Context.UnsignedLongTy,
3407 llvm::APInt(32, 5), ArrayType::Normal, 0)
3410 for (size_t i = 0; i < 4; ++i) {
3411 FieldDecl *Field = FieldDecl::Create(Context,
3414 SourceLocation(), nullptr,
3415 FieldTypes[i], /*TInfo=*/nullptr,
3416 /*BitWidth=*/nullptr,
3419 Field->setAccess(AS_public);
3423 D->completeDefinition();
3424 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3427 return ObjCFastEnumerationStateType;
3431 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3432 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3434 // Don't emit it as the address of the string, emit the string data itself
3435 // as an inline array.
3436 if (E->getCharByteWidth() == 1) {
3437 SmallString<64> Str(E->getString());
3439 // Resize the string to the right size, which is indicated by its type.
3440 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3441 Str.resize(CAT->getSize().getZExtValue());
3442 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3445 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3446 llvm::Type *ElemTy = AType->getElementType();
3447 unsigned NumElements = AType->getNumElements();
3449 // Wide strings have either 2-byte or 4-byte elements.
3450 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3451 SmallVector<uint16_t, 32> Elements;
3452 Elements.reserve(NumElements);
3454 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3455 Elements.push_back(E->getCodeUnit(i));
3456 Elements.resize(NumElements);
3457 return llvm::ConstantDataArray::get(VMContext, Elements);
3460 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3461 SmallVector<uint32_t, 32> Elements;
3462 Elements.reserve(NumElements);
3464 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3465 Elements.push_back(E->getCodeUnit(i));
3466 Elements.resize(NumElements);
3467 return llvm::ConstantDataArray::get(VMContext, Elements);
3470 static llvm::GlobalVariable *
3471 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3472 CodeGenModule &CGM, StringRef GlobalName,
3473 CharUnits Alignment) {
3474 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3475 unsigned AddrSpace = 0;
3476 if (CGM.getLangOpts().OpenCL)
3477 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3479 llvm::Module &M = CGM.getModule();
3480 // Create a global variable for this string
3481 auto *GV = new llvm::GlobalVariable(
3482 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3483 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3484 GV->setAlignment(Alignment.getQuantity());
3485 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3486 if (GV->isWeakForLinker()) {
3487 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3488 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3494 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3495 /// constant array for the given string literal.
3497 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3499 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3501 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3502 llvm::GlobalVariable **Entry = nullptr;
3503 if (!LangOpts.WritableStrings) {
3504 Entry = &ConstantStringMap[C];
3505 if (auto GV = *Entry) {
3506 if (Alignment.getQuantity() > GV->getAlignment())
3507 GV->setAlignment(Alignment.getQuantity());
3508 return ConstantAddress(GV, Alignment);
3512 SmallString<256> MangledNameBuffer;
3513 StringRef GlobalVariableName;
3514 llvm::GlobalValue::LinkageTypes LT;
3516 // Mangle the string literal if the ABI allows for it. However, we cannot
3517 // do this if we are compiling with ASan or -fwritable-strings because they
3518 // rely on strings having normal linkage.
3519 if (!LangOpts.WritableStrings &&
3520 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3521 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3522 llvm::raw_svector_ostream Out(MangledNameBuffer);
3523 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3525 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3526 GlobalVariableName = MangledNameBuffer;
3528 LT = llvm::GlobalValue::PrivateLinkage;
3529 GlobalVariableName = Name;
3532 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3536 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3538 return ConstantAddress(GV, Alignment);
3541 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3542 /// array for the given ObjCEncodeExpr node.
3544 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3546 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3548 return GetAddrOfConstantCString(Str);
3551 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3552 /// the literal and a terminating '\0' character.
3553 /// The result has pointer to array type.
3554 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3555 const std::string &Str, const char *GlobalName) {
3556 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3557 CharUnits Alignment =
3558 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3561 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3563 // Don't share any string literals if strings aren't constant.
3564 llvm::GlobalVariable **Entry = nullptr;
3565 if (!LangOpts.WritableStrings) {
3566 Entry = &ConstantStringMap[C];
3567 if (auto GV = *Entry) {
3568 if (Alignment.getQuantity() > GV->getAlignment())
3569 GV->setAlignment(Alignment.getQuantity());
3570 return ConstantAddress(GV, Alignment);
3574 // Get the default prefix if a name wasn't specified.
3576 GlobalName = ".str";
3577 // Create a global variable for this.
3578 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3579 GlobalName, Alignment);
3582 return ConstantAddress(GV, Alignment);
3585 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3586 const MaterializeTemporaryExpr *E, const Expr *Init) {
3587 assert((E->getStorageDuration() == SD_Static ||
3588 E->getStorageDuration() == SD_Thread) && "not a global temporary");
3589 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3591 // If we're not materializing a subobject of the temporary, keep the
3592 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3593 QualType MaterializedType = Init->getType();
3594 if (Init == E->GetTemporaryExpr())
3595 MaterializedType = E->getType();
3597 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3599 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3600 return ConstantAddress(Slot, Align);
3602 // FIXME: If an externally-visible declaration extends multiple temporaries,
3603 // we need to give each temporary the same name in every translation unit (and
3604 // we also need to make the temporaries externally-visible).
3605 SmallString<256> Name;
3606 llvm::raw_svector_ostream Out(Name);
3607 getCXXABI().getMangleContext().mangleReferenceTemporary(
3608 VD, E->getManglingNumber(), Out);
3610 APValue *Value = nullptr;
3611 if (E->getStorageDuration() == SD_Static) {
3612 // We might have a cached constant initializer for this temporary. Note
3613 // that this might have a different value from the value computed by
3614 // evaluating the initializer if the surrounding constant expression
3615 // modifies the temporary.
3616 Value = getContext().getMaterializedTemporaryValue(E, false);
3617 if (Value && Value->isUninit())
3621 // Try evaluating it now, it might have a constant initializer.
3622 Expr::EvalResult EvalResult;
3623 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3624 !EvalResult.hasSideEffects())
3625 Value = &EvalResult.Val;
3627 llvm::Constant *InitialValue = nullptr;
3628 bool Constant = false;
3631 // The temporary has a constant initializer, use it.
3632 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3633 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3634 Type = InitialValue->getType();
3636 // No initializer, the initialization will be provided when we
3637 // initialize the declaration which performed lifetime extension.
3638 Type = getTypes().ConvertTypeForMem(MaterializedType);
3641 // Create a global variable for this lifetime-extended temporary.
3642 llvm::GlobalValue::LinkageTypes Linkage =
3643 getLLVMLinkageVarDefinition(VD, Constant);
3644 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3645 const VarDecl *InitVD;
3646 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3647 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3648 // Temporaries defined inside a class get linkonce_odr linkage because the
3649 // class can be defined in multipe translation units.
3650 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3652 // There is no need for this temporary to have external linkage if the
3653 // VarDecl has external linkage.
3654 Linkage = llvm::GlobalVariable::InternalLinkage;
3657 unsigned AddrSpace = GetGlobalVarAddressSpace(
3658 VD, getContext().getTargetAddressSpace(MaterializedType));
3659 auto *GV = new llvm::GlobalVariable(
3660 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3661 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3663 setGlobalVisibility(GV, VD);
3664 GV->setAlignment(Align.getQuantity());
3665 if (supportsCOMDAT() && GV->isWeakForLinker())
3666 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3667 if (VD->getTLSKind())
3668 setTLSMode(GV, *VD);
3669 MaterializedGlobalTemporaryMap[E] = GV;
3670 return ConstantAddress(GV, Align);
3673 /// EmitObjCPropertyImplementations - Emit information for synthesized
3674 /// properties for an implementation.
3675 void CodeGenModule::EmitObjCPropertyImplementations(const
3676 ObjCImplementationDecl *D) {
3677 for (const auto *PID : D->property_impls()) {
3678 // Dynamic is just for type-checking.
3679 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3680 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3682 // Determine which methods need to be implemented, some may have
3683 // been overridden. Note that ::isPropertyAccessor is not the method
3684 // we want, that just indicates if the decl came from a
3685 // property. What we want to know is if the method is defined in
3686 // this implementation.
3687 if (!D->getInstanceMethod(PD->getGetterName()))
3688 CodeGenFunction(*this).GenerateObjCGetter(
3689 const_cast<ObjCImplementationDecl *>(D), PID);
3690 if (!PD->isReadOnly() &&
3691 !D->getInstanceMethod(PD->getSetterName()))
3692 CodeGenFunction(*this).GenerateObjCSetter(
3693 const_cast<ObjCImplementationDecl *>(D), PID);
3698 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3699 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3700 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3701 ivar; ivar = ivar->getNextIvar())
3702 if (ivar->getType().isDestructedType())
3708 static bool AllTrivialInitializers(CodeGenModule &CGM,
3709 ObjCImplementationDecl *D) {
3710 CodeGenFunction CGF(CGM);
3711 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3712 E = D->init_end(); B != E; ++B) {
3713 CXXCtorInitializer *CtorInitExp = *B;
3714 Expr *Init = CtorInitExp->getInit();
3715 if (!CGF.isTrivialInitializer(Init))
3721 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3722 /// for an implementation.
3723 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3724 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3725 if (needsDestructMethod(D)) {
3726 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3727 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3728 ObjCMethodDecl *DTORMethod =
3729 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3730 cxxSelector, getContext().VoidTy, nullptr, D,
3731 /*isInstance=*/true, /*isVariadic=*/false,
3732 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3733 /*isDefined=*/false, ObjCMethodDecl::Required);
3734 D->addInstanceMethod(DTORMethod);
3735 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3736 D->setHasDestructors(true);
3739 // If the implementation doesn't have any ivar initializers, we don't need
3740 // a .cxx_construct.
3741 if (D->getNumIvarInitializers() == 0 ||
3742 AllTrivialInitializers(*this, D))
3745 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3746 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3747 // The constructor returns 'self'.
3748 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3752 getContext().getObjCIdType(),
3753 nullptr, D, /*isInstance=*/true,
3754 /*isVariadic=*/false,
3755 /*isPropertyAccessor=*/true,
3756 /*isImplicitlyDeclared=*/true,
3757 /*isDefined=*/false,
3758 ObjCMethodDecl::Required);
3759 D->addInstanceMethod(CTORMethod);
3760 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3761 D->setHasNonZeroConstructors(true);
3764 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3765 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3766 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3767 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3768 ErrorUnsupported(LSD, "linkage spec");
3772 EmitDeclContext(LSD);
3775 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3776 for (auto *I : DC->decls()) {
3777 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3778 // are themselves considered "top-level", so EmitTopLevelDecl on an
3779 // ObjCImplDecl does not recursively visit them. We need to do that in
3780 // case they're nested inside another construct (LinkageSpecDecl /
3781 // ExportDecl) that does stop them from being considered "top-level".
3782 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3783 for (auto *M : OID->methods())
3784 EmitTopLevelDecl(M);
3787 EmitTopLevelDecl(I);
3791 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3792 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3793 // Ignore dependent declarations.
3794 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3797 switch (D->getKind()) {
3798 case Decl::CXXConversion:
3799 case Decl::CXXMethod:
3800 case Decl::Function:
3801 // Skip function templates
3802 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3803 cast<FunctionDecl>(D)->isLateTemplateParsed())
3806 EmitGlobal(cast<FunctionDecl>(D));
3807 // Always provide some coverage mapping
3808 // even for the functions that aren't emitted.
3809 AddDeferredUnusedCoverageMapping(D);
3812 case Decl::CXXDeductionGuide:
3813 // Function-like, but does not result in code emission.
3817 case Decl::Decomposition:
3818 // Skip variable templates
3819 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3821 case Decl::VarTemplateSpecialization:
3822 EmitGlobal(cast<VarDecl>(D));
3823 if (auto *DD = dyn_cast<DecompositionDecl>(D))
3824 for (auto *B : DD->bindings())
3825 if (auto *HD = B->getHoldingVar())
3829 // Indirect fields from global anonymous structs and unions can be
3830 // ignored; only the actual variable requires IR gen support.
3831 case Decl::IndirectField:
3835 case Decl::Namespace:
3836 EmitDeclContext(cast<NamespaceDecl>(D));
3838 case Decl::CXXRecord:
3840 if (auto *ES = D->getASTContext().getExternalSource())
3841 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3842 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3844 // Emit any static data members, they may be definitions.
3845 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3846 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3847 EmitTopLevelDecl(I);
3849 // No code generation needed.
3850 case Decl::UsingShadow:
3851 case Decl::ClassTemplate:
3852 case Decl::VarTemplate:
3853 case Decl::VarTemplatePartialSpecialization:
3854 case Decl::FunctionTemplate:
3855 case Decl::TypeAliasTemplate:
3859 case Decl::Using: // using X; [C++]
3860 if (CGDebugInfo *DI = getModuleDebugInfo())
3861 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3863 case Decl::NamespaceAlias:
3864 if (CGDebugInfo *DI = getModuleDebugInfo())
3865 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3867 case Decl::UsingDirective: // using namespace X; [C++]
3868 if (CGDebugInfo *DI = getModuleDebugInfo())
3869 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3871 case Decl::CXXConstructor:
3872 // Skip function templates
3873 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3874 cast<FunctionDecl>(D)->isLateTemplateParsed())
3877 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3879 case Decl::CXXDestructor:
3880 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3882 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3885 case Decl::StaticAssert:
3889 // Objective-C Decls
3891 // Forward declarations, no (immediate) code generation.
3892 case Decl::ObjCInterface:
3893 case Decl::ObjCCategory:
3896 case Decl::ObjCProtocol: {
3897 auto *Proto = cast<ObjCProtocolDecl>(D);
3898 if (Proto->isThisDeclarationADefinition())
3899 ObjCRuntime->GenerateProtocol(Proto);
3903 case Decl::ObjCCategoryImpl:
3904 // Categories have properties but don't support synthesize so we
3905 // can ignore them here.
3906 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3909 case Decl::ObjCImplementation: {
3910 auto *OMD = cast<ObjCImplementationDecl>(D);
3911 EmitObjCPropertyImplementations(OMD);
3912 EmitObjCIvarInitializations(OMD);
3913 ObjCRuntime->GenerateClass(OMD);
3914 // Emit global variable debug information.
3915 if (CGDebugInfo *DI = getModuleDebugInfo())
3916 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3917 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3918 OMD->getClassInterface()), OMD->getLocation());
3921 case Decl::ObjCMethod: {
3922 auto *OMD = cast<ObjCMethodDecl>(D);
3923 // If this is not a prototype, emit the body.
3925 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3928 case Decl::ObjCCompatibleAlias:
3929 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3932 case Decl::PragmaComment: {
3933 const auto *PCD = cast<PragmaCommentDecl>(D);
3934 switch (PCD->getCommentKind()) {
3936 llvm_unreachable("unexpected pragma comment kind");
3938 AppendLinkerOptions(PCD->getArg());
3941 AddDependentLib(PCD->getArg());
3946 break; // We ignore all of these.
3951 case Decl::PragmaDetectMismatch: {
3952 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3953 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3957 case Decl::LinkageSpec:
3958 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3961 case Decl::FileScopeAsm: {
3962 // File-scope asm is ignored during device-side CUDA compilation.
3963 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3965 // File-scope asm is ignored during device-side OpenMP compilation.
3966 if (LangOpts.OpenMPIsDevice)
3968 auto *AD = cast<FileScopeAsmDecl>(D);
3969 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3973 case Decl::Import: {
3974 auto *Import = cast<ImportDecl>(D);
3976 // If we've already imported this module, we're done.
3977 if (!ImportedModules.insert(Import->getImportedModule()))
3980 // Emit debug information for direct imports.
3981 if (!Import->getImportedOwningModule()) {
3982 if (CGDebugInfo *DI = getModuleDebugInfo())
3983 DI->EmitImportDecl(*Import);
3986 // Find all of the submodules and emit the module initializers.
3987 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3988 SmallVector<clang::Module *, 16> Stack;
3989 Visited.insert(Import->getImportedModule());
3990 Stack.push_back(Import->getImportedModule());
3992 while (!Stack.empty()) {
3993 clang::Module *Mod = Stack.pop_back_val();
3994 if (!EmittedModuleInitializers.insert(Mod).second)
3997 for (auto *D : Context.getModuleInitializers(Mod))
3998 EmitTopLevelDecl(D);
4000 // Visit the submodules of this module.
4001 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4002 SubEnd = Mod->submodule_end();
4003 Sub != SubEnd; ++Sub) {
4004 // Skip explicit children; they need to be explicitly imported to emit
4005 // the initializers.
4006 if ((*Sub)->IsExplicit)
4009 if (Visited.insert(*Sub).second)
4010 Stack.push_back(*Sub);
4017 EmitDeclContext(cast<ExportDecl>(D));
4020 case Decl::OMPThreadPrivate:
4021 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4024 case Decl::ClassTemplateSpecialization: {
4025 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4027 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4028 Spec->hasDefinition())
4029 DebugInfo->completeTemplateDefinition(*Spec);
4033 case Decl::OMPDeclareReduction:
4034 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4038 // Make sure we handled everything we should, every other kind is a
4039 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4040 // function. Need to recode Decl::Kind to do that easily.
4041 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4046 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4047 // Do we need to generate coverage mapping?
4048 if (!CodeGenOpts.CoverageMapping)
4050 switch (D->getKind()) {
4051 case Decl::CXXConversion:
4052 case Decl::CXXMethod:
4053 case Decl::Function:
4054 case Decl::ObjCMethod:
4055 case Decl::CXXConstructor:
4056 case Decl::CXXDestructor: {
4057 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4059 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4060 if (I == DeferredEmptyCoverageMappingDecls.end())
4061 DeferredEmptyCoverageMappingDecls[D] = true;
4069 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4070 // Do we need to generate coverage mapping?
4071 if (!CodeGenOpts.CoverageMapping)
4073 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4074 if (Fn->isTemplateInstantiation())
4075 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4077 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4078 if (I == DeferredEmptyCoverageMappingDecls.end())
4079 DeferredEmptyCoverageMappingDecls[D] = false;
4084 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4085 std::vector<const Decl *> DeferredDecls;
4086 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4089 DeferredDecls.push_back(I.first);
4091 // Sort the declarations by their location to make sure that the tests get a
4092 // predictable order for the coverage mapping for the unused declarations.
4093 if (CodeGenOpts.DumpCoverageMapping)
4094 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4095 [] (const Decl *LHS, const Decl *RHS) {
4096 return LHS->getLocStart() < RHS->getLocStart();
4098 for (const auto *D : DeferredDecls) {
4099 switch (D->getKind()) {
4100 case Decl::CXXConversion:
4101 case Decl::CXXMethod:
4102 case Decl::Function:
4103 case Decl::ObjCMethod: {
4104 CodeGenPGO PGO(*this);
4105 GlobalDecl GD(cast<FunctionDecl>(D));
4106 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4107 getFunctionLinkage(GD));
4110 case Decl::CXXConstructor: {
4111 CodeGenPGO PGO(*this);
4112 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4113 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4114 getFunctionLinkage(GD));
4117 case Decl::CXXDestructor: {
4118 CodeGenPGO PGO(*this);
4119 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4120 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4121 getFunctionLinkage(GD));
4130 /// Turns the given pointer into a constant.
4131 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4133 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4134 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4135 return llvm::ConstantInt::get(i64, PtrInt);
4138 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4139 llvm::NamedMDNode *&GlobalMetadata,
4141 llvm::GlobalValue *Addr) {
4142 if (!GlobalMetadata)
4144 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4146 // TODO: should we report variant information for ctors/dtors?
4147 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4148 llvm::ConstantAsMetadata::get(GetPointerConstant(
4149 CGM.getLLVMContext(), D.getDecl()))};
4150 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4153 /// For each function which is declared within an extern "C" region and marked
4154 /// as 'used', but has internal linkage, create an alias from the unmangled
4155 /// name to the mangled name if possible. People expect to be able to refer
4156 /// to such functions with an unmangled name from inline assembly within the
4157 /// same translation unit.
4158 void CodeGenModule::EmitStaticExternCAliases() {
4159 // Don't do anything if we're generating CUDA device code -- the NVPTX
4160 // assembly target doesn't support aliases.
4161 if (Context.getTargetInfo().getTriple().isNVPTX())
4163 for (auto &I : StaticExternCValues) {
4164 IdentifierInfo *Name = I.first;
4165 llvm::GlobalValue *Val = I.second;
4166 if (Val && !getModule().getNamedValue(Name->getName()))
4167 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4171 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4172 GlobalDecl &Result) const {
4173 auto Res = Manglings.find(MangledName);
4174 if (Res == Manglings.end())
4176 Result = Res->getValue();
4180 /// Emits metadata nodes associating all the global values in the
4181 /// current module with the Decls they came from. This is useful for
4182 /// projects using IR gen as a subroutine.
4184 /// Since there's currently no way to associate an MDNode directly
4185 /// with an llvm::GlobalValue, we create a global named metadata
4186 /// with the name 'clang.global.decl.ptrs'.
4187 void CodeGenModule::EmitDeclMetadata() {
4188 llvm::NamedMDNode *GlobalMetadata = nullptr;
4190 for (auto &I : MangledDeclNames) {
4191 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4192 // Some mangled names don't necessarily have an associated GlobalValue
4193 // in this module, e.g. if we mangled it for DebugInfo.
4195 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4199 /// Emits metadata nodes for all the local variables in the current
4201 void CodeGenFunction::EmitDeclMetadata() {
4202 if (LocalDeclMap.empty()) return;
4204 llvm::LLVMContext &Context = getLLVMContext();
4206 // Find the unique metadata ID for this name.
4207 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4209 llvm::NamedMDNode *GlobalMetadata = nullptr;
4211 for (auto &I : LocalDeclMap) {
4212 const Decl *D = I.first;
4213 llvm::Value *Addr = I.second.getPointer();
4214 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4215 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4216 Alloca->setMetadata(
4217 DeclPtrKind, llvm::MDNode::get(
4218 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4219 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4220 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4221 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4226 void CodeGenModule::EmitVersionIdentMetadata() {
4227 llvm::NamedMDNode *IdentMetadata =
4228 TheModule.getOrInsertNamedMetadata("llvm.ident");
4229 std::string Version = getClangFullVersion();
4230 llvm::LLVMContext &Ctx = TheModule.getContext();
4232 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4233 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4236 void CodeGenModule::EmitTargetMetadata() {
4237 // Warning, new MangledDeclNames may be appended within this loop.
4238 // We rely on MapVector insertions adding new elements to the end
4239 // of the container.
4240 // FIXME: Move this loop into the one target that needs it, and only
4241 // loop over those declarations for which we couldn't emit the target
4242 // metadata when we emitted the declaration.
4243 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4244 auto Val = *(MangledDeclNames.begin() + I);
4245 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4246 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4247 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4251 void CodeGenModule::EmitCoverageFile() {
4252 if (getCodeGenOpts().CoverageDataFile.empty() &&
4253 getCodeGenOpts().CoverageNotesFile.empty())
4256 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4260 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4261 llvm::LLVMContext &Ctx = TheModule.getContext();
4262 auto *CoverageDataFile =
4263 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4264 auto *CoverageNotesFile =
4265 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4266 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4267 llvm::MDNode *CU = CUNode->getOperand(i);
4268 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4269 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4273 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4274 // Sema has checked that all uuid strings are of the form
4275 // "12345678-1234-1234-1234-1234567890ab".
4276 assert(Uuid.size() == 36);
4277 for (unsigned i = 0; i < 36; ++i) {
4278 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4279 else assert(isHexDigit(Uuid[i]));
4282 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4283 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4285 llvm::Constant *Field3[8];
4286 for (unsigned Idx = 0; Idx < 8; ++Idx)
4287 Field3[Idx] = llvm::ConstantInt::get(
4288 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4290 llvm::Constant *Fields[4] = {
4291 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4292 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4293 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4294 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4297 return llvm::ConstantStruct::getAnon(Fields);
4300 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4302 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4303 // FIXME: should we even be calling this method if RTTI is disabled
4304 // and it's not for EH?
4305 if (!ForEH && !getLangOpts().RTTI)
4306 return llvm::Constant::getNullValue(Int8PtrTy);
4308 if (ForEH && Ty->isObjCObjectPointerType() &&
4309 LangOpts.ObjCRuntime.isGNUFamily())
4310 return ObjCRuntime->GetEHType(Ty);
4312 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4315 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4316 for (auto RefExpr : D->varlists()) {
4317 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4319 VD->getAnyInitializer() &&
4320 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4323 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4324 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4325 VD, Addr, RefExpr->getLocStart(), PerformInit))
4326 CXXGlobalInits.push_back(InitFunction);
4330 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4331 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4335 if (isExternallyVisible(T->getLinkage())) {
4336 std::string OutName;
4337 llvm::raw_string_ostream Out(OutName);
4338 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4340 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4342 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4343 llvm::ArrayRef<llvm::Metadata *>());
4349 /// Returns whether this module needs the "all-vtables" type identifier.
4350 bool CodeGenModule::NeedAllVtablesTypeId() const {
4351 // Returns true if at least one of vtable-based CFI checkers is enabled and
4352 // is not in the trapping mode.
4353 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4354 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4355 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4356 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4357 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4358 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4359 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4360 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4363 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4365 const CXXRecordDecl *RD) {
4366 llvm::Metadata *MD =
4367 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4368 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4370 if (CodeGenOpts.SanitizeCfiCrossDso)
4371 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4372 VTable->addTypeMetadata(Offset.getQuantity(),
4373 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4375 if (NeedAllVtablesTypeId()) {
4376 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4377 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4381 // Fills in the supplied string map with the set of target features for the
4382 // passed in function.
4383 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4384 const FunctionDecl *FD) {
4385 StringRef TargetCPU = Target.getTargetOpts().CPU;
4386 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4387 // If we have a TargetAttr build up the feature map based on that.
4388 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4390 // Make a copy of the features as passed on the command line into the
4391 // beginning of the additional features from the function to override.
4392 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4393 Target.getTargetOpts().FeaturesAsWritten.begin(),
4394 Target.getTargetOpts().FeaturesAsWritten.end());
4396 if (ParsedAttr.second != "")
4397 TargetCPU = ParsedAttr.second;
4399 // Now populate the feature map, first with the TargetCPU which is either
4400 // the default or a new one from the target attribute string. Then we'll use
4401 // the passed in features (FeaturesAsWritten) along with the new ones from
4403 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4405 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4406 Target.getTargetOpts().Features);
4410 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4412 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4417 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4418 CodeGenFunction &CGF) {
4419 llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4420 auto SamplerT = getOpenCLRuntime().getSamplerType();
4421 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4422 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4423 "__translate_sampler_initializer"),