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/IR/CallSite.h"
49 #include "llvm/IR/CallingConv.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/ProfileData/InstrProfReader.h"
55 #include "llvm/Support/ConvertUTF.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MD5.h"
59 using namespace clang;
60 using namespace CodeGen;
62 static const char AnnotationSection[] = "llvm.metadata";
64 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
65 switch (CGM.getTarget().getCXXABI().getKind()) {
66 case TargetCXXABI::GenericAArch64:
67 case TargetCXXABI::GenericARM:
68 case TargetCXXABI::iOS:
69 case TargetCXXABI::iOS64:
70 case TargetCXXABI::WatchOS:
71 case TargetCXXABI::GenericMIPS:
72 case TargetCXXABI::GenericItanium:
73 case TargetCXXABI::WebAssembly:
74 return CreateItaniumCXXABI(CGM);
75 case TargetCXXABI::Microsoft:
76 return CreateMicrosoftCXXABI(CGM);
79 llvm_unreachable("invalid C++ ABI kind");
82 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
83 const PreprocessorOptions &PPO,
84 const CodeGenOptions &CGO, llvm::Module &M,
85 DiagnosticsEngine &diags,
86 CoverageSourceInfo *CoverageInfo)
87 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
88 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
89 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
90 VMContext(M.getContext()), Types(*this), VTables(*this),
91 SanitizerMD(new SanitizerMetadata(*this)) {
93 // Initialize the type cache.
94 llvm::LLVMContext &LLVMContext = M.getContext();
95 VoidTy = llvm::Type::getVoidTy(LLVMContext);
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100 FloatTy = llvm::Type::getFloatTy(LLVMContext);
101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103 PointerAlignInBytes =
104 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
106 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
108 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
109 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
110 IntPtrTy = llvm::IntegerType::get(LLVMContext,
111 C.getTargetInfo().getMaxPointerWidth());
112 Int8PtrTy = Int8Ty->getPointerTo(0);
113 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
114 AllocaInt8PtrTy = Int8Ty->getPointerTo(
115 M.getDataLayout().getAllocaAddrSpace());
117 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
118 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
123 createOpenCLRuntime();
125 createOpenMPRuntime();
129 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
130 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
131 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
132 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
133 getCXXABI().getMangleContext()));
135 // If debug info or coverage generation is enabled, create the CGDebugInfo
137 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
138 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
139 DebugInfo.reset(new CGDebugInfo(*this));
141 Block.GlobalUniqueCount = 0;
143 if (C.getLangOpts().ObjC1)
144 ObjCData.reset(new ObjCEntrypoints());
146 if (CodeGenOpts.hasProfileClangUse()) {
147 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
148 CodeGenOpts.ProfileInstrumentUsePath);
149 if (auto E = ReaderOrErr.takeError()) {
150 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
151 "Could not read profile %0: %1");
152 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
153 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
157 PGOReader = std::move(ReaderOrErr.get());
160 // If coverage mapping generation is enabled, create the
161 // CoverageMappingModuleGen object.
162 if (CodeGenOpts.CoverageMapping)
163 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
166 CodeGenModule::~CodeGenModule() {}
168 void CodeGenModule::createObjCRuntime() {
169 // This is just isGNUFamily(), but we want to force implementors of
170 // new ABIs to decide how best to do this.
171 switch (LangOpts.ObjCRuntime.getKind()) {
172 case ObjCRuntime::GNUstep:
173 case ObjCRuntime::GCC:
174 case ObjCRuntime::ObjFW:
175 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
178 case ObjCRuntime::FragileMacOSX:
179 case ObjCRuntime::MacOSX:
180 case ObjCRuntime::iOS:
181 case ObjCRuntime::WatchOS:
182 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
185 llvm_unreachable("bad runtime kind");
188 void CodeGenModule::createOpenCLRuntime() {
189 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
192 void CodeGenModule::createOpenMPRuntime() {
193 // Select a specialized code generation class based on the target, if any.
194 // If it does not exist use the default implementation.
195 switch (getTriple().getArch()) {
196 case llvm::Triple::nvptx:
197 case llvm::Triple::nvptx64:
198 assert(getLangOpts().OpenMPIsDevice &&
199 "OpenMP NVPTX is only prepared to deal with device code.");
200 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
203 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
208 void CodeGenModule::createCUDARuntime() {
209 CUDARuntime.reset(CreateNVCUDARuntime(*this));
212 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
213 Replacements[Name] = C;
216 void CodeGenModule::applyReplacements() {
217 for (auto &I : Replacements) {
218 StringRef MangledName = I.first();
219 llvm::Constant *Replacement = I.second;
220 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
223 auto *OldF = cast<llvm::Function>(Entry);
224 auto *NewF = dyn_cast<llvm::Function>(Replacement);
226 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
227 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
229 auto *CE = cast<llvm::ConstantExpr>(Replacement);
230 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
231 CE->getOpcode() == llvm::Instruction::GetElementPtr);
232 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
236 // Replace old with new, but keep the old order.
237 OldF->replaceAllUsesWith(Replacement);
239 NewF->removeFromParent();
240 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
243 OldF->eraseFromParent();
247 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
248 GlobalValReplacements.push_back(std::make_pair(GV, C));
251 void CodeGenModule::applyGlobalValReplacements() {
252 for (auto &I : GlobalValReplacements) {
253 llvm::GlobalValue *GV = I.first;
254 llvm::Constant *C = I.second;
256 GV->replaceAllUsesWith(C);
257 GV->eraseFromParent();
261 // This is only used in aliases that we created and we know they have a
263 static const llvm::GlobalObject *getAliasedGlobal(
264 const llvm::GlobalIndirectSymbol &GIS) {
265 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
266 const llvm::Constant *C = &GIS;
268 C = C->stripPointerCasts();
269 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
271 // stripPointerCasts will not walk over weak aliases.
272 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
275 if (!Visited.insert(GIS2).second)
277 C = GIS2->getIndirectSymbol();
281 void CodeGenModule::checkAliases() {
282 // Check if the constructed aliases are well formed. It is really unfortunate
283 // that we have to do this in CodeGen, but we only construct mangled names
284 // and aliases during codegen.
286 DiagnosticsEngine &Diags = getDiags();
287 for (const GlobalDecl &GD : Aliases) {
288 const auto *D = cast<ValueDecl>(GD.getDecl());
289 SourceLocation Location;
290 bool IsIFunc = D->hasAttr<IFuncAttr>();
291 if (const Attr *A = D->getDefiningAttr())
292 Location = A->getLocation();
294 llvm_unreachable("Not an alias or ifunc?");
295 StringRef MangledName = getMangledName(GD);
296 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
297 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
298 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
301 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
302 } else if (GV->isDeclaration()) {
304 Diags.Report(Location, diag::err_alias_to_undefined)
305 << IsIFunc << IsIFunc;
306 } else if (IsIFunc) {
307 // Check resolver function type.
308 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
309 GV->getType()->getPointerElementType());
311 if (!FTy->getReturnType()->isPointerTy())
312 Diags.Report(Location, diag::err_ifunc_resolver_return);
313 if (FTy->getNumParams())
314 Diags.Report(Location, diag::err_ifunc_resolver_params);
317 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
318 llvm::GlobalValue *AliaseeGV;
319 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
320 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
322 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
324 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
325 StringRef AliasSection = SA->getName();
326 if (AliasSection != AliaseeGV->getSection())
327 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
328 << AliasSection << IsIFunc << IsIFunc;
331 // We have to handle alias to weak aliases in here. LLVM itself disallows
332 // this since the object semantics would not match the IL one. For
333 // compatibility with gcc we implement it by just pointing the alias
334 // to its aliasee's aliasee. We also warn, since the user is probably
335 // expecting the link to be weak.
336 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
337 if (GA->isInterposable()) {
338 Diags.Report(Location, diag::warn_alias_to_weak_alias)
339 << GV->getName() << GA->getName() << IsIFunc;
340 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
341 GA->getIndirectSymbol(), Alias->getType());
342 Alias->setIndirectSymbol(Aliasee);
349 for (const GlobalDecl &GD : Aliases) {
350 StringRef MangledName = getMangledName(GD);
351 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
352 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
353 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
354 Alias->eraseFromParent();
358 void CodeGenModule::clear() {
359 DeferredDeclsToEmit.clear();
361 OpenMPRuntime->clear();
364 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
365 StringRef MainFile) {
366 if (!hasDiagnostics())
368 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
369 if (MainFile.empty())
370 MainFile = "<stdin>";
371 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
373 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
377 void CodeGenModule::Release() {
379 applyGlobalValReplacements();
382 EmitCXXGlobalInitFunc();
383 EmitCXXGlobalDtorFunc();
384 EmitCXXThreadLocalInitFunc();
386 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
387 AddGlobalCtor(ObjCInitFunction);
388 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
390 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
391 AddGlobalCtor(CudaCtorFunction);
392 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
393 AddGlobalDtor(CudaDtorFunction);
396 if (llvm::Function *OpenMPRegistrationFunction =
397 OpenMPRuntime->emitRegistrationFunction())
398 AddGlobalCtor(OpenMPRegistrationFunction, 0);
400 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
401 if (PGOStats.hasDiagnostics())
402 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
404 EmitCtorList(GlobalCtors, "llvm.global_ctors");
405 EmitCtorList(GlobalDtors, "llvm.global_dtors");
406 EmitGlobalAnnotations();
407 EmitStaticExternCAliases();
408 EmitDeferredUnusedCoverageMappings();
410 CoverageMapping->emit();
411 if (CodeGenOpts.SanitizeCfiCrossDso) {
412 CodeGenFunction(*this).EmitCfiCheckFail();
413 CodeGenFunction(*this).EmitCfiCheckStub();
415 emitAtAvailableLinkGuard();
420 if (CodeGenOpts.Autolink &&
421 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
422 EmitModuleLinkOptions();
425 // Record mregparm value now so it is visible through rest of codegen.
426 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
427 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
428 CodeGenOpts.NumRegisterParameters);
430 if (CodeGenOpts.DwarfVersion) {
431 // We actually want the latest version when there are conflicts.
432 // We can change from Warning to Latest if such mode is supported.
433 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
434 CodeGenOpts.DwarfVersion);
436 if (CodeGenOpts.EmitCodeView) {
437 // Indicate that we want CodeView in the metadata.
438 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
440 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
441 // We don't support LTO with 2 with different StrictVTablePointers
442 // FIXME: we could support it by stripping all the information introduced
443 // by StrictVTablePointers.
445 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
447 llvm::Metadata *Ops[2] = {
448 llvm::MDString::get(VMContext, "StrictVTablePointers"),
449 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
450 llvm::Type::getInt32Ty(VMContext), 1))};
452 getModule().addModuleFlag(llvm::Module::Require,
453 "StrictVTablePointersRequirement",
454 llvm::MDNode::get(VMContext, Ops));
457 // We support a single version in the linked module. The LLVM
458 // parser will drop debug info with a different version number
459 // (and warn about it, too).
460 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
461 llvm::DEBUG_METADATA_VERSION);
463 // We need to record the widths of enums and wchar_t, so that we can generate
464 // the correct build attributes in the ARM backend.
465 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
466 if ( Arch == llvm::Triple::arm
467 || Arch == llvm::Triple::armeb
468 || Arch == llvm::Triple::thumb
469 || Arch == llvm::Triple::thumbeb) {
470 // Width of wchar_t in bytes
471 uint64_t WCharWidth =
472 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
473 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
475 // The minimum width of an enum in bytes
476 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
477 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
480 if (CodeGenOpts.SanitizeCfiCrossDso) {
481 // Indicate that we want cross-DSO control flow integrity checks.
482 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
485 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
486 // Indicate whether __nvvm_reflect should be configured to flush denormal
487 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
489 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
490 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
493 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
494 assert(PLevel < 3 && "Invalid PIC Level");
495 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
496 if (Context.getLangOpts().PIE)
497 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
500 SimplifyPersonality();
502 if (getCodeGenOpts().EmitDeclMetadata)
505 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
509 DebugInfo->finalize();
511 EmitVersionIdentMetadata();
513 EmitTargetMetadata();
516 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
517 // Make sure that this type is translated.
518 Types.UpdateCompletedType(TD);
521 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
522 // Make sure that this type is translated.
523 Types.RefreshTypeCacheForClass(RD);
526 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
529 return TBAA->getTBAAInfo(QTy);
532 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
535 return TBAA->getTBAAInfoForVTablePtr();
538 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
541 return TBAA->getTBAAStructInfo(QTy);
544 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
545 llvm::MDNode *AccessN,
549 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
552 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
553 /// and struct-path aware TBAA, the tag has the same format:
554 /// base type, access type and offset.
555 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
556 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
557 llvm::MDNode *TBAAInfo,
558 bool ConvertTypeToTag) {
559 if (ConvertTypeToTag && TBAA)
560 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
561 TBAA->getTBAAScalarTagInfo(TBAAInfo));
563 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
566 void CodeGenModule::DecorateInstructionWithInvariantGroup(
567 llvm::Instruction *I, const CXXRecordDecl *RD) {
568 llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
569 auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
570 // Check if we have to wrap MDString in MDNode.
572 MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
573 I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
576 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
577 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
578 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
581 /// ErrorUnsupported - Print out an error that codegen doesn't support the
582 /// specified stmt yet.
583 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
584 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
585 "cannot compile this %0 yet");
586 std::string Msg = Type;
587 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
588 << Msg << S->getSourceRange();
591 /// ErrorUnsupported - Print out an error that codegen doesn't support the
592 /// specified decl yet.
593 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
594 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
595 "cannot compile this %0 yet");
596 std::string Msg = Type;
597 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
600 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
601 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
604 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
605 const NamedDecl *D) const {
606 // Internal definitions always have default visibility.
607 if (GV->hasLocalLinkage()) {
608 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
612 // Set visibility for definitions.
613 LinkageInfo LV = D->getLinkageAndVisibility();
614 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
615 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
618 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
619 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
620 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
621 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
622 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
623 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
626 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
627 CodeGenOptions::TLSModel M) {
629 case CodeGenOptions::GeneralDynamicTLSModel:
630 return llvm::GlobalVariable::GeneralDynamicTLSModel;
631 case CodeGenOptions::LocalDynamicTLSModel:
632 return llvm::GlobalVariable::LocalDynamicTLSModel;
633 case CodeGenOptions::InitialExecTLSModel:
634 return llvm::GlobalVariable::InitialExecTLSModel;
635 case CodeGenOptions::LocalExecTLSModel:
636 return llvm::GlobalVariable::LocalExecTLSModel;
638 llvm_unreachable("Invalid TLS model!");
641 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
642 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
644 llvm::GlobalValue::ThreadLocalMode TLM;
645 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
647 // Override the TLS model if it is explicitly specified.
648 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
649 TLM = GetLLVMTLSModel(Attr->getModel());
652 GV->setThreadLocalMode(TLM);
655 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
656 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
658 // Some ABIs don't have constructor variants. Make sure that base and
659 // complete constructors get mangled the same.
660 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
661 if (!getTarget().getCXXABI().hasConstructorVariants()) {
662 CXXCtorType OrigCtorType = GD.getCtorType();
663 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
664 if (OrigCtorType == Ctor_Base)
665 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
669 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
670 if (!FoundStr.empty())
673 const auto *ND = cast<NamedDecl>(GD.getDecl());
674 SmallString<256> Buffer;
676 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
677 llvm::raw_svector_ostream Out(Buffer);
678 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
679 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
680 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
681 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
683 getCXXABI().getMangleContext().mangleName(ND, Out);
686 IdentifierInfo *II = ND->getIdentifier();
687 assert(II && "Attempt to mangle unnamed decl.");
688 const auto *FD = dyn_cast<FunctionDecl>(ND);
691 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
692 llvm::raw_svector_ostream Out(Buffer);
693 Out << "__regcall3__" << II->getName();
700 // Keep the first result in the case of a mangling collision.
701 auto Result = Manglings.insert(std::make_pair(Str, GD));
702 return FoundStr = Result.first->first();
705 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
706 const BlockDecl *BD) {
707 MangleContext &MangleCtx = getCXXABI().getMangleContext();
708 const Decl *D = GD.getDecl();
710 SmallString<256> Buffer;
711 llvm::raw_svector_ostream Out(Buffer);
713 MangleCtx.mangleGlobalBlock(BD,
714 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
715 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
716 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
717 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
718 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
720 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
722 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
723 return Result.first->first();
726 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
727 return getModule().getNamedValue(Name);
730 /// AddGlobalCtor - Add a function to the list that will be called before
732 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
733 llvm::Constant *AssociatedData) {
734 // FIXME: Type coercion of void()* types.
735 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
738 /// AddGlobalDtor - Add a function to the list that will be called
739 /// when the module is unloaded.
740 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
741 // FIXME: Type coercion of void()* types.
742 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
745 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
746 if (Fns.empty()) return;
748 // Ctor function type is void()*.
749 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
750 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
752 // Get the type of a ctor entry, { i32, void ()*, i8* }.
753 llvm::StructType *CtorStructTy = llvm::StructType::get(
754 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
756 // Construct the constructor and destructor arrays.
757 ConstantInitBuilder builder(*this);
758 auto ctors = builder.beginArray(CtorStructTy);
759 for (const auto &I : Fns) {
760 auto ctor = ctors.beginStruct(CtorStructTy);
761 ctor.addInt(Int32Ty, I.Priority);
762 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
763 if (I.AssociatedData)
764 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
766 ctor.addNullPointer(VoidPtrTy);
767 ctor.finishAndAddTo(ctors);
771 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
773 llvm::GlobalValue::AppendingLinkage);
775 // The LTO linker doesn't seem to like it when we set an alignment
776 // on appending variables. Take it off as a workaround.
777 list->setAlignment(0);
782 llvm::GlobalValue::LinkageTypes
783 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
784 const auto *D = cast<FunctionDecl>(GD.getDecl());
786 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
788 if (isa<CXXDestructorDecl>(D) &&
789 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
791 // Destructor variants in the Microsoft C++ ABI are always internal or
792 // linkonce_odr thunks emitted on an as-needed basis.
793 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
794 : llvm::GlobalValue::LinkOnceODRLinkage;
797 if (isa<CXXConstructorDecl>(D) &&
798 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
799 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
800 // Our approach to inheriting constructors is fundamentally different from
801 // that used by the MS ABI, so keep our inheriting constructor thunks
802 // internal rather than trying to pick an unambiguous mangling for them.
803 return llvm::GlobalValue::InternalLinkage;
806 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
809 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
810 const auto *FD = cast<FunctionDecl>(GD.getDecl());
812 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
813 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
814 // Don't dllexport/import destructor thunks.
815 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
820 if (FD->hasAttr<DLLImportAttr>())
821 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
822 else if (FD->hasAttr<DLLExportAttr>())
823 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
825 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
828 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
829 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
830 if (!MDS) return nullptr;
832 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
835 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
837 setNonAliasAttributes(D, F);
840 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
841 const CGFunctionInfo &Info,
843 unsigned CallingConv;
844 llvm::AttributeList PAL;
845 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
846 F->setAttributes(PAL);
847 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
850 /// Determines whether the language options require us to model
851 /// unwind exceptions. We treat -fexceptions as mandating this
852 /// except under the fragile ObjC ABI with only ObjC exceptions
853 /// enabled. This means, for example, that C with -fexceptions
855 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
856 // If exceptions are completely disabled, obviously this is false.
857 if (!LangOpts.Exceptions) return false;
859 // If C++ exceptions are enabled, this is true.
860 if (LangOpts.CXXExceptions) return true;
862 // If ObjC exceptions are enabled, this depends on the ABI.
863 if (LangOpts.ObjCExceptions) {
864 return LangOpts.ObjCRuntime.hasUnwindExceptions();
870 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
874 if (CodeGenOpts.UnwindTables)
875 B.addAttribute(llvm::Attribute::UWTable);
877 if (!hasUnwindExceptions(LangOpts))
878 B.addAttribute(llvm::Attribute::NoUnwind);
880 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
881 B.addAttribute(llvm::Attribute::StackProtect);
882 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
883 B.addAttribute(llvm::Attribute::StackProtectStrong);
884 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
885 B.addAttribute(llvm::Attribute::StackProtectReq);
888 // If we don't have a declaration to control inlining, the function isn't
889 // explicitly marked as alwaysinline for semantic reasons, and inlining is
890 // disabled, mark the function as noinline.
891 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
892 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
893 B.addAttribute(llvm::Attribute::NoInline);
896 llvm::AttributeList::FunctionIndex,
897 llvm::AttributeList::get(F->getContext(),
898 llvm::AttributeList::FunctionIndex, B));
902 if (D->hasAttr<OptimizeNoneAttr>()) {
903 B.addAttribute(llvm::Attribute::OptimizeNone);
905 // OptimizeNone implies noinline; we should not be inlining such functions.
906 B.addAttribute(llvm::Attribute::NoInline);
907 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
908 "OptimizeNone and AlwaysInline on same function!");
910 // We still need to handle naked functions even though optnone subsumes
911 // much of their semantics.
912 if (D->hasAttr<NakedAttr>())
913 B.addAttribute(llvm::Attribute::Naked);
915 // OptimizeNone wins over OptimizeForSize and MinSize.
916 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
917 F->removeFnAttr(llvm::Attribute::MinSize);
918 } else if (D->hasAttr<NakedAttr>()) {
919 // Naked implies noinline: we should not be inlining such functions.
920 B.addAttribute(llvm::Attribute::Naked);
921 B.addAttribute(llvm::Attribute::NoInline);
922 } else if (D->hasAttr<NoDuplicateAttr>()) {
923 B.addAttribute(llvm::Attribute::NoDuplicate);
924 } else if (D->hasAttr<NoInlineAttr>()) {
925 B.addAttribute(llvm::Attribute::NoInline);
926 } else if (D->hasAttr<AlwaysInlineAttr>() &&
927 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
928 // (noinline wins over always_inline, and we can't specify both in IR)
929 B.addAttribute(llvm::Attribute::AlwaysInline);
930 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
931 // If we're not inlining, then force everything that isn't always_inline to
932 // carry an explicit noinline attribute.
933 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
934 B.addAttribute(llvm::Attribute::NoInline);
936 // Otherwise, propagate the inline hint attribute and potentially use its
937 // absence to mark things as noinline.
938 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
939 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
940 return Redecl->isInlineSpecified();
942 B.addAttribute(llvm::Attribute::InlineHint);
943 } else if (CodeGenOpts.getInlining() ==
944 CodeGenOptions::OnlyHintInlining &&
946 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
947 B.addAttribute(llvm::Attribute::NoInline);
952 // Add other optimization related attributes if we are optimizing this
954 if (!D->hasAttr<OptimizeNoneAttr>()) {
955 if (D->hasAttr<ColdAttr>()) {
956 B.addAttribute(llvm::Attribute::OptimizeForSize);
957 B.addAttribute(llvm::Attribute::Cold);
960 if (D->hasAttr<MinSizeAttr>())
961 B.addAttribute(llvm::Attribute::MinSize);
964 F->addAttributes(llvm::AttributeList::FunctionIndex,
965 llvm::AttributeList::get(
966 F->getContext(), llvm::AttributeList::FunctionIndex, B));
968 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
970 F->setAlignment(alignment);
972 // Some C++ ABIs require 2-byte alignment for member functions, in order to
973 // reserve a bit for differentiating between virtual and non-virtual member
974 // functions. If the current target's C++ ABI requires this and this is a
975 // member function, set its alignment accordingly.
976 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
977 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
981 // In the cross-dso CFI mode, we want !type attributes on definitions only.
982 if (CodeGenOpts.SanitizeCfiCrossDso)
983 if (auto *FD = dyn_cast<FunctionDecl>(D))
984 CreateFunctionTypeMetadata(FD, F);
987 void CodeGenModule::SetCommonAttributes(const Decl *D,
988 llvm::GlobalValue *GV) {
989 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
990 setGlobalVisibility(GV, ND);
992 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
994 if (D && D->hasAttr<UsedAttr>())
998 void CodeGenModule::setAliasAttributes(const Decl *D,
999 llvm::GlobalValue *GV) {
1000 SetCommonAttributes(D, GV);
1002 // Process the dllexport attribute based on whether the original definition
1003 // (not necessarily the aliasee) was exported.
1004 if (D->hasAttr<DLLExportAttr>())
1005 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1008 void CodeGenModule::setNonAliasAttributes(const Decl *D,
1009 llvm::GlobalObject *GO) {
1010 SetCommonAttributes(D, GO);
1013 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1014 GO->setSection(SA->getName());
1016 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1019 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1021 const CGFunctionInfo &FI) {
1022 SetLLVMFunctionAttributes(D, FI, F);
1023 SetLLVMFunctionAttributesForDefinition(D, F);
1025 F->setLinkage(llvm::Function::InternalLinkage);
1027 setNonAliasAttributes(D, F);
1030 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1031 const NamedDecl *ND) {
1032 // Set linkage and visibility in case we never see a definition.
1033 LinkageInfo LV = ND->getLinkageAndVisibility();
1034 if (LV.getLinkage() != ExternalLinkage) {
1035 // Don't set internal linkage on declarations.
1037 if (ND->hasAttr<DLLImportAttr>()) {
1038 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1039 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1040 } else if (ND->hasAttr<DLLExportAttr>()) {
1041 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1042 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1043 // "extern_weak" is overloaded in LLVM; we probably should have
1044 // separate linkage types for this.
1045 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1048 // Set visibility on a declaration only if it's explicit.
1049 if (LV.isVisibilityExplicit())
1050 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1054 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1055 llvm::Function *F) {
1056 // Only if we are checking indirect calls.
1057 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1060 // Non-static class methods are handled via vtable pointer checks elsewhere.
1061 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1064 // Additionally, if building with cross-DSO support...
1065 if (CodeGenOpts.SanitizeCfiCrossDso) {
1066 // Skip available_externally functions. They won't be codegen'ed in the
1067 // current module anyway.
1068 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1072 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1073 F->addTypeMetadata(0, MD);
1075 // Emit a hash-based bit set entry for cross-DSO calls.
1076 if (CodeGenOpts.SanitizeCfiCrossDso)
1077 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1078 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1081 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1082 bool IsIncompleteFunction,
1084 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1085 // If this is an intrinsic function, set the function's attributes
1086 // to the intrinsic's attributes.
1087 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1091 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1093 if (!IsIncompleteFunction)
1094 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1096 // Add the Returned attribute for "this", except for iOS 5 and earlier
1097 // where substantial code, including the libstdc++ dylib, was compiled with
1098 // GCC and does not actually return "this".
1099 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1100 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1101 assert(!F->arg_empty() &&
1102 F->arg_begin()->getType()
1103 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1104 "unexpected this return");
1105 F->addAttribute(1, llvm::Attribute::Returned);
1108 // Only a few attributes are set on declarations; these may later be
1109 // overridden by a definition.
1111 setLinkageAndVisibilityForGV(F, FD);
1113 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1114 F->setSection(SA->getName());
1116 if (FD->isReplaceableGlobalAllocationFunction()) {
1117 // A replaceable global allocation function does not act like a builtin by
1118 // default, only if it is invoked by a new-expression or delete-expression.
1119 F->addAttribute(llvm::AttributeList::FunctionIndex,
1120 llvm::Attribute::NoBuiltin);
1122 // A sane operator new returns a non-aliasing pointer.
1123 // FIXME: Also add NonNull attribute to the return value
1124 // for the non-nothrow forms?
1125 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1126 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1127 (Kind == OO_New || Kind == OO_Array_New))
1128 F->addAttribute(llvm::AttributeList::ReturnIndex,
1129 llvm::Attribute::NoAlias);
1132 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1133 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1134 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1135 if (MD->isVirtual())
1136 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1138 // Don't emit entries for function declarations in the cross-DSO mode. This
1139 // is handled with better precision by the receiving DSO.
1140 if (!CodeGenOpts.SanitizeCfiCrossDso)
1141 CreateFunctionTypeMetadata(FD, F);
1144 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1145 assert(!GV->isDeclaration() &&
1146 "Only globals with definition can force usage.");
1147 LLVMUsed.emplace_back(GV);
1150 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1151 assert(!GV->isDeclaration() &&
1152 "Only globals with definition can force usage.");
1153 LLVMCompilerUsed.emplace_back(GV);
1156 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1157 std::vector<llvm::WeakVH> &List) {
1158 // Don't create llvm.used if there is no need.
1162 // Convert List to what ConstantArray needs.
1163 SmallVector<llvm::Constant*, 8> UsedArray;
1164 UsedArray.resize(List.size());
1165 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1167 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1168 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1171 if (UsedArray.empty())
1173 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1175 auto *GV = new llvm::GlobalVariable(
1176 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1177 llvm::ConstantArray::get(ATy, UsedArray), Name);
1179 GV->setSection("llvm.metadata");
1182 void CodeGenModule::emitLLVMUsed() {
1183 emitUsed(*this, "llvm.used", LLVMUsed);
1184 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1187 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1188 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1189 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1192 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1193 llvm::SmallString<32> Opt;
1194 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1195 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1196 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1199 void CodeGenModule::AddDependentLib(StringRef Lib) {
1200 llvm::SmallString<24> Opt;
1201 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1202 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1203 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1206 /// \brief Add link options implied by the given module, including modules
1207 /// it depends on, using a postorder walk.
1208 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1209 SmallVectorImpl<llvm::Metadata *> &Metadata,
1210 llvm::SmallPtrSet<Module *, 16> &Visited) {
1211 // Import this module's parent.
1212 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1213 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1216 // Import this module's dependencies.
1217 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1218 if (Visited.insert(Mod->Imports[I - 1]).second)
1219 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1222 // Add linker options to link against the libraries/frameworks
1223 // described by this module.
1224 llvm::LLVMContext &Context = CGM.getLLVMContext();
1225 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1226 // Link against a framework. Frameworks are currently Darwin only, so we
1227 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1228 if (Mod->LinkLibraries[I-1].IsFramework) {
1229 llvm::Metadata *Args[2] = {
1230 llvm::MDString::get(Context, "-framework"),
1231 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1233 Metadata.push_back(llvm::MDNode::get(Context, Args));
1237 // Link against a library.
1238 llvm::SmallString<24> Opt;
1239 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1240 Mod->LinkLibraries[I-1].Library, Opt);
1241 auto *OptString = llvm::MDString::get(Context, Opt);
1242 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1246 void CodeGenModule::EmitModuleLinkOptions() {
1247 // Collect the set of all of the modules we want to visit to emit link
1248 // options, which is essentially the imported modules and all of their
1249 // non-explicit child modules.
1250 llvm::SetVector<clang::Module *> LinkModules;
1251 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1252 SmallVector<clang::Module *, 16> Stack;
1254 // Seed the stack with imported modules.
1255 for (Module *M : ImportedModules) {
1256 // Do not add any link flags when an implementation TU of a module imports
1257 // a header of that same module.
1258 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1259 !getLangOpts().isCompilingModule())
1261 if (Visited.insert(M).second)
1265 // Find all of the modules to import, making a little effort to prune
1266 // non-leaf modules.
1267 while (!Stack.empty()) {
1268 clang::Module *Mod = Stack.pop_back_val();
1270 bool AnyChildren = false;
1272 // Visit the submodules of this module.
1273 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1274 SubEnd = Mod->submodule_end();
1275 Sub != SubEnd; ++Sub) {
1276 // Skip explicit children; they need to be explicitly imported to be
1278 if ((*Sub)->IsExplicit)
1281 if (Visited.insert(*Sub).second) {
1282 Stack.push_back(*Sub);
1287 // We didn't find any children, so add this module to the list of
1288 // modules to link against.
1290 LinkModules.insert(Mod);
1294 // Add link options for all of the imported modules in reverse topological
1295 // order. We don't do anything to try to order import link flags with respect
1296 // to linker options inserted by things like #pragma comment().
1297 SmallVector<llvm::Metadata *, 16> MetadataArgs;
1299 for (Module *M : LinkModules)
1300 if (Visited.insert(M).second)
1301 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1302 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1303 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1305 // Add the linker options metadata flag.
1306 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1307 llvm::MDNode::get(getLLVMContext(),
1308 LinkerOptionsMetadata));
1311 void CodeGenModule::EmitDeferred() {
1312 // Emit code for any potentially referenced deferred decls. Since a
1313 // previously unused static decl may become used during the generation of code
1314 // for a static function, iterate until no changes are made.
1316 if (!DeferredVTables.empty()) {
1317 EmitDeferredVTables();
1319 // Emitting a vtable doesn't directly cause more vtables to
1320 // become deferred, although it can cause functions to be
1321 // emitted that then need those vtables.
1322 assert(DeferredVTables.empty());
1325 // Stop if we're out of both deferred vtables and deferred declarations.
1326 if (DeferredDeclsToEmit.empty())
1329 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1330 // work, it will not interfere with this.
1331 std::vector<DeferredGlobal> CurDeclsToEmit;
1332 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1334 for (DeferredGlobal &G : CurDeclsToEmit) {
1335 GlobalDecl D = G.GD;
1338 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1339 // to get GlobalValue with exactly the type we need, not something that
1340 // might had been created for another decl with the same mangled name but
1342 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1343 GetAddrOfGlobal(D, ForDefinition));
1345 // In case of different address spaces, we may still get a cast, even with
1346 // IsForDefinition equal to true. Query mangled names table to get
1349 GV = GetGlobalValue(getMangledName(D));
1351 // Make sure GetGlobalValue returned non-null.
1354 // Check to see if we've already emitted this. This is necessary
1355 // for a couple of reasons: first, decls can end up in the
1356 // deferred-decls queue multiple times, and second, decls can end
1357 // up with definitions in unusual ways (e.g. by an extern inline
1358 // function acquiring a strong function redefinition). Just
1359 // ignore these cases.
1360 if (!GV->isDeclaration())
1363 // Otherwise, emit the definition and move on to the next one.
1364 EmitGlobalDefinition(D, GV);
1366 // If we found out that we need to emit more decls, do that recursively.
1367 // This has the advantage that the decls are emitted in a DFS and related
1368 // ones are close together, which is convenient for testing.
1369 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1371 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1376 void CodeGenModule::EmitGlobalAnnotations() {
1377 if (Annotations.empty())
1380 // Create a new global variable for the ConstantStruct in the Module.
1381 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1382 Annotations[0]->getType(), Annotations.size()), Annotations);
1383 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1384 llvm::GlobalValue::AppendingLinkage,
1385 Array, "llvm.global.annotations");
1386 gv->setSection(AnnotationSection);
1389 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1390 llvm::Constant *&AStr = AnnotationStrings[Str];
1394 // Not found yet, create a new global.
1395 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1397 new llvm::GlobalVariable(getModule(), s->getType(), true,
1398 llvm::GlobalValue::PrivateLinkage, s, ".str");
1399 gv->setSection(AnnotationSection);
1400 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1405 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1406 SourceManager &SM = getContext().getSourceManager();
1407 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1409 return EmitAnnotationString(PLoc.getFilename());
1410 return EmitAnnotationString(SM.getBufferName(Loc));
1413 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1414 SourceManager &SM = getContext().getSourceManager();
1415 PresumedLoc PLoc = SM.getPresumedLoc(L);
1416 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1417 SM.getExpansionLineNumber(L);
1418 return llvm::ConstantInt::get(Int32Ty, LineNo);
1421 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1422 const AnnotateAttr *AA,
1424 // Get the globals for file name, annotation, and the line number.
1425 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1426 *UnitGV = EmitAnnotationUnit(L),
1427 *LineNoCst = EmitAnnotationLineNo(L);
1429 // Create the ConstantStruct for the global annotation.
1430 llvm::Constant *Fields[4] = {
1431 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1432 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1433 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1436 return llvm::ConstantStruct::getAnon(Fields);
1439 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1440 llvm::GlobalValue *GV) {
1441 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1442 // Get the struct elements for these annotations.
1443 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1444 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1447 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1448 SourceLocation Loc) const {
1449 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1450 // Blacklist by function name.
1451 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1453 // Blacklist by location.
1455 return SanitizerBL.isBlacklistedLocation(Loc);
1456 // If location is unknown, this may be a compiler-generated function. Assume
1457 // it's located in the main file.
1458 auto &SM = Context.getSourceManager();
1459 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1460 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1465 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1466 SourceLocation Loc, QualType Ty,
1467 StringRef Category) const {
1468 // For now globals can be blacklisted only in ASan and KASan.
1469 if (!LangOpts.Sanitize.hasOneOf(
1470 SanitizerKind::Address | SanitizerKind::KernelAddress))
1472 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1473 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1475 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1477 // Check global type.
1479 // Drill down the array types: if global variable of a fixed type is
1480 // blacklisted, we also don't instrument arrays of them.
1481 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1482 Ty = AT->getElementType();
1483 Ty = Ty.getCanonicalType().getUnqualifiedType();
1484 // We allow to blacklist only record types (classes, structs etc.)
1485 if (Ty->isRecordType()) {
1486 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1487 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1494 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1495 StringRef Category) const {
1496 if (!LangOpts.XRayInstrument)
1498 const auto &XRayFilter = getContext().getXRayFilter();
1499 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1500 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1502 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1503 if (Attr == ImbueAttr::NONE)
1504 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1506 case ImbueAttr::NONE:
1508 case ImbueAttr::ALWAYS:
1509 Fn->addFnAttr("function-instrument", "xray-always");
1511 case ImbueAttr::NEVER:
1512 Fn->addFnAttr("function-instrument", "xray-never");
1518 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1519 // Never defer when EmitAllDecls is specified.
1520 if (LangOpts.EmitAllDecls)
1523 return getContext().DeclMustBeEmitted(Global);
1526 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1527 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1528 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1529 // Implicit template instantiations may change linkage if they are later
1530 // explicitly instantiated, so they should not be emitted eagerly.
1532 if (const auto *VD = dyn_cast<VarDecl>(Global))
1533 if (Context.getInlineVariableDefinitionKind(VD) ==
1534 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1535 // A definition of an inline constexpr static data member may change
1536 // linkage later if it's redeclared outside the class.
1538 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1539 // codegen for global variables, because they may be marked as threadprivate.
1540 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1541 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1547 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1548 const CXXUuidofExpr* E) {
1549 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1551 StringRef Uuid = E->getUuidStr();
1552 std::string Name = "_GUID_" + Uuid.lower();
1553 std::replace(Name.begin(), Name.end(), '-', '_');
1555 // The UUID descriptor should be pointer aligned.
1556 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1558 // Look for an existing global.
1559 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1560 return ConstantAddress(GV, Alignment);
1562 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1563 assert(Init && "failed to initialize as constant");
1565 auto *GV = new llvm::GlobalVariable(
1566 getModule(), Init->getType(),
1567 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1568 if (supportsCOMDAT())
1569 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1570 return ConstantAddress(GV, Alignment);
1573 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1574 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1575 assert(AA && "No alias?");
1577 CharUnits Alignment = getContext().getDeclAlign(VD);
1578 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1580 // See if there is already something with the target's name in the module.
1581 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1583 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1584 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1585 return ConstantAddress(Ptr, Alignment);
1588 llvm::Constant *Aliasee;
1589 if (isa<llvm::FunctionType>(DeclTy))
1590 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1591 GlobalDecl(cast<FunctionDecl>(VD)),
1592 /*ForVTable=*/false);
1594 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1595 llvm::PointerType::getUnqual(DeclTy),
1598 auto *F = cast<llvm::GlobalValue>(Aliasee);
1599 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1600 WeakRefReferences.insert(F);
1602 return ConstantAddress(Aliasee, Alignment);
1605 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1606 const auto *Global = cast<ValueDecl>(GD.getDecl());
1608 // Weak references don't produce any output by themselves.
1609 if (Global->hasAttr<WeakRefAttr>())
1612 // If this is an alias definition (which otherwise looks like a declaration)
1614 if (Global->hasAttr<AliasAttr>())
1615 return EmitAliasDefinition(GD);
1617 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1618 if (Global->hasAttr<IFuncAttr>())
1619 return emitIFuncDefinition(GD);
1621 // If this is CUDA, be selective about which declarations we emit.
1622 if (LangOpts.CUDA) {
1623 if (LangOpts.CUDAIsDevice) {
1624 if (!Global->hasAttr<CUDADeviceAttr>() &&
1625 !Global->hasAttr<CUDAGlobalAttr>() &&
1626 !Global->hasAttr<CUDAConstantAttr>() &&
1627 !Global->hasAttr<CUDASharedAttr>())
1630 // We need to emit host-side 'shadows' for all global
1631 // device-side variables because the CUDA runtime needs their
1632 // size and host-side address in order to provide access to
1633 // their device-side incarnations.
1635 // So device-only functions are the only things we skip.
1636 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1637 Global->hasAttr<CUDADeviceAttr>())
1640 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1641 "Expected Variable or Function");
1645 if (LangOpts.OpenMP) {
1646 // If this is OpenMP device, check if it is legal to emit this global
1648 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1650 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1651 if (MustBeEmitted(Global))
1652 EmitOMPDeclareReduction(DRD);
1657 // Ignore declarations, they will be emitted on their first use.
1658 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1659 // Forward declarations are emitted lazily on first use.
1660 if (!FD->doesThisDeclarationHaveABody()) {
1661 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1664 StringRef MangledName = getMangledName(GD);
1666 // Compute the function info and LLVM type.
1667 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1668 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1670 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1671 /*DontDefer=*/false);
1675 const auto *VD = cast<VarDecl>(Global);
1676 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1677 // We need to emit device-side global CUDA variables even if a
1678 // variable does not have a definition -- we still need to define
1679 // host-side shadow for it.
1680 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1681 !VD->hasDefinition() &&
1682 (VD->hasAttr<CUDAConstantAttr>() ||
1683 VD->hasAttr<CUDADeviceAttr>());
1684 if (!MustEmitForCuda &&
1685 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1686 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1687 // If this declaration may have caused an inline variable definition to
1688 // change linkage, make sure that it's emitted.
1689 if (Context.getInlineVariableDefinitionKind(VD) ==
1690 ASTContext::InlineVariableDefinitionKind::Strong)
1691 GetAddrOfGlobalVar(VD);
1696 // Defer code generation to first use when possible, e.g. if this is an inline
1697 // function. If the global must always be emitted, do it eagerly if possible
1698 // to benefit from cache locality.
1699 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1700 // Emit the definition if it can't be deferred.
1701 EmitGlobalDefinition(GD);
1705 // If we're deferring emission of a C++ variable with an
1706 // initializer, remember the order in which it appeared in the file.
1707 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1708 cast<VarDecl>(Global)->hasInit()) {
1709 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1710 CXXGlobalInits.push_back(nullptr);
1713 StringRef MangledName = getMangledName(GD);
1714 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1715 // The value has already been used and should therefore be emitted.
1716 addDeferredDeclToEmit(GV, GD);
1717 } else if (MustBeEmitted(Global)) {
1718 // The value must be emitted, but cannot be emitted eagerly.
1719 assert(!MayBeEmittedEagerly(Global));
1720 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1722 // Otherwise, remember that we saw a deferred decl with this name. The
1723 // first use of the mangled name will cause it to move into
1724 // DeferredDeclsToEmit.
1725 DeferredDecls[MangledName] = GD;
1729 // Check if T is a class type with a destructor that's not dllimport.
1730 static bool HasNonDllImportDtor(QualType T) {
1731 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1732 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1733 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1740 struct FunctionIsDirectlyRecursive :
1741 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1742 const StringRef Name;
1743 const Builtin::Context &BI;
1745 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1746 Name(N), BI(C), Result(false) {
1748 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1750 bool TraverseCallExpr(CallExpr *E) {
1751 const FunctionDecl *FD = E->getDirectCallee();
1754 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1755 if (Attr && Name == Attr->getLabel()) {
1759 unsigned BuiltinID = FD->getBuiltinID();
1760 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1762 StringRef BuiltinName = BI.getName(BuiltinID);
1763 if (BuiltinName.startswith("__builtin_") &&
1764 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1772 // Make sure we're not referencing non-imported vars or functions.
1773 struct DLLImportFunctionVisitor
1774 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1775 bool SafeToInline = true;
1777 bool shouldVisitImplicitCode() const { return true; }
1779 bool VisitVarDecl(VarDecl *VD) {
1780 if (VD->getTLSKind()) {
1781 // A thread-local variable cannot be imported.
1782 SafeToInline = false;
1783 return SafeToInline;
1786 // A variable definition might imply a destructor call.
1787 if (VD->isThisDeclarationADefinition())
1788 SafeToInline = !HasNonDllImportDtor(VD->getType());
1790 return SafeToInline;
1793 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1794 if (const auto *D = E->getTemporary()->getDestructor())
1795 SafeToInline = D->hasAttr<DLLImportAttr>();
1796 return SafeToInline;
1799 bool VisitDeclRefExpr(DeclRefExpr *E) {
1800 ValueDecl *VD = E->getDecl();
1801 if (isa<FunctionDecl>(VD))
1802 SafeToInline = VD->hasAttr<DLLImportAttr>();
1803 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1804 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1805 return SafeToInline;
1808 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1809 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1810 return SafeToInline;
1813 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1814 CXXMethodDecl *M = E->getMethodDecl();
1816 // Call through a pointer to member function. This is safe to inline.
1817 SafeToInline = true;
1819 SafeToInline = M->hasAttr<DLLImportAttr>();
1821 return SafeToInline;
1824 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1825 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1826 return SafeToInline;
1829 bool VisitCXXNewExpr(CXXNewExpr *E) {
1830 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1831 return SafeToInline;
1836 // isTriviallyRecursive - Check if this function calls another
1837 // decl that, because of the asm attribute or the other decl being a builtin,
1838 // ends up pointing to itself.
1840 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1842 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1843 // asm labels are a special kind of mangling we have to support.
1844 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1847 Name = Attr->getLabel();
1849 Name = FD->getName();
1852 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1853 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1854 return Walker.Result;
1857 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1858 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1860 const auto *F = cast<FunctionDecl>(GD.getDecl());
1861 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1864 if (F->hasAttr<DLLImportAttr>()) {
1865 // Check whether it would be safe to inline this dllimport function.
1866 DLLImportFunctionVisitor Visitor;
1867 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1868 if (!Visitor.SafeToInline)
1871 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1872 // Implicit destructor invocations aren't captured in the AST, so the
1873 // check above can't see them. Check for them manually here.
1874 for (const Decl *Member : Dtor->getParent()->decls())
1875 if (isa<FieldDecl>(Member))
1876 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1878 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1879 if (HasNonDllImportDtor(B.getType()))
1884 // PR9614. Avoid cases where the source code is lying to us. An available
1885 // externally function should have an equivalent function somewhere else,
1886 // but a function that calls itself is clearly not equivalent to the real
1888 // This happens in glibc's btowc and in some configure checks.
1889 return !isTriviallyRecursive(F);
1892 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1893 const auto *D = cast<ValueDecl>(GD.getDecl());
1895 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1896 Context.getSourceManager(),
1897 "Generating code for declaration");
1899 if (isa<FunctionDecl>(D)) {
1900 // At -O0, don't generate IR for functions with available_externally
1902 if (!shouldEmitFunction(GD))
1905 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1906 // Make sure to emit the definition(s) before we emit the thunks.
1907 // This is necessary for the generation of certain thunks.
1908 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1909 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1910 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1911 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1913 EmitGlobalFunctionDefinition(GD, GV);
1915 if (Method->isVirtual())
1916 getVTables().EmitThunks(GD);
1921 return EmitGlobalFunctionDefinition(GD, GV);
1924 if (const auto *VD = dyn_cast<VarDecl>(D))
1925 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1927 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1930 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1931 llvm::Function *NewFn);
1933 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1934 /// module, create and return an llvm Function with the specified type. If there
1935 /// is something in the module with the specified name, return it potentially
1936 /// bitcasted to the right type.
1938 /// If D is non-null, it specifies a decl that correspond to this. This is used
1939 /// to set the attributes on the function when it is first created.
1940 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
1941 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
1942 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
1943 ForDefinition_t IsForDefinition) {
1944 const Decl *D = GD.getDecl();
1946 // Lookup the entry, lazily creating it if necessary.
1947 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1949 if (WeakRefReferences.erase(Entry)) {
1950 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1951 if (FD && !FD->hasAttr<WeakAttr>())
1952 Entry->setLinkage(llvm::Function::ExternalLinkage);
1955 // Handle dropped DLL attributes.
1956 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1957 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1959 // If there are two attempts to define the same mangled name, issue an
1961 if (IsForDefinition && !Entry->isDeclaration()) {
1963 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1964 // to make sure that we issue an error only once.
1965 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1966 (GD.getCanonicalDecl().getDecl() !=
1967 OtherGD.getCanonicalDecl().getDecl()) &&
1968 DiagnosedConflictingDefinitions.insert(GD).second) {
1969 getDiags().Report(D->getLocation(),
1970 diag::err_duplicate_mangled_name);
1971 getDiags().Report(OtherGD.getDecl()->getLocation(),
1972 diag::note_previous_definition);
1976 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1977 (Entry->getType()->getElementType() == Ty)) {
1981 // Make sure the result is of the correct type.
1982 // (If function is requested for a definition, we always need to create a new
1983 // function, not just return a bitcast.)
1984 if (!IsForDefinition)
1985 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1988 // This function doesn't have a complete type (for example, the return
1989 // type is an incomplete struct). Use a fake type instead, and make
1990 // sure not to try to set attributes.
1991 bool IsIncompleteFunction = false;
1993 llvm::FunctionType *FTy;
1994 if (isa<llvm::FunctionType>(Ty)) {
1995 FTy = cast<llvm::FunctionType>(Ty);
1997 FTy = llvm::FunctionType::get(VoidTy, false);
1998 IsIncompleteFunction = true;
2002 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2003 Entry ? StringRef() : MangledName, &getModule());
2005 // If we already created a function with the same mangled name (but different
2006 // type) before, take its name and add it to the list of functions to be
2007 // replaced with F at the end of CodeGen.
2009 // This happens if there is a prototype for a function (e.g. "int f()") and
2010 // then a definition of a different type (e.g. "int f(int x)").
2014 // This might be an implementation of a function without a prototype, in
2015 // which case, try to do special replacement of calls which match the new
2016 // prototype. The really key thing here is that we also potentially drop
2017 // arguments from the call site so as to make a direct call, which makes the
2018 // inliner happier and suppresses a number of optimizer warnings (!) about
2019 // dropping arguments.
2020 if (!Entry->use_empty()) {
2021 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2022 Entry->removeDeadConstantUsers();
2025 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2026 F, Entry->getType()->getElementType()->getPointerTo());
2027 addGlobalValReplacement(Entry, BC);
2030 assert(F->getName() == MangledName && "name was uniqued!");
2032 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2033 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2034 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2035 F->addAttributes(llvm::AttributeList::FunctionIndex,
2036 llvm::AttributeList::get(
2037 VMContext, llvm::AttributeList::FunctionIndex, B));
2041 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2042 // each other bottoming out with the base dtor. Therefore we emit non-base
2043 // dtors on usage, even if there is no dtor definition in the TU.
2044 if (D && isa<CXXDestructorDecl>(D) &&
2045 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2047 addDeferredDeclToEmit(F, GD);
2049 // This is the first use or definition of a mangled name. If there is a
2050 // deferred decl with this name, remember that we need to emit it at the end
2052 auto DDI = DeferredDecls.find(MangledName);
2053 if (DDI != DeferredDecls.end()) {
2054 // Move the potentially referenced deferred decl to the
2055 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2056 // don't need it anymore).
2057 addDeferredDeclToEmit(F, DDI->second);
2058 DeferredDecls.erase(DDI);
2060 // Otherwise, there are cases we have to worry about where we're
2061 // using a declaration for which we must emit a definition but where
2062 // we might not find a top-level definition:
2063 // - member functions defined inline in their classes
2064 // - friend functions defined inline in some class
2065 // - special member functions with implicit definitions
2066 // If we ever change our AST traversal to walk into class methods,
2067 // this will be unnecessary.
2069 // We also don't emit a definition for a function if it's going to be an
2070 // entry in a vtable, unless it's already marked as used.
2071 } else if (getLangOpts().CPlusPlus && D) {
2072 // Look for a declaration that's lexically in a record.
2073 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2074 FD = FD->getPreviousDecl()) {
2075 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2076 if (FD->doesThisDeclarationHaveABody()) {
2077 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
2085 // Make sure the result is of the requested type.
2086 if (!IsIncompleteFunction) {
2087 assert(F->getType()->getElementType() == Ty);
2091 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2092 return llvm::ConstantExpr::getBitCast(F, PTy);
2095 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2096 /// non-null, then this function will use the specified type if it has to
2097 /// create it (this occurs when we see a definition of the function).
2098 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2102 ForDefinition_t IsForDefinition) {
2103 // If there was no specific requested type, just convert it now.
2105 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2106 auto CanonTy = Context.getCanonicalType(FD->getType());
2107 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2110 StringRef MangledName = getMangledName(GD);
2111 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2112 /*IsThunk=*/false, llvm::AttributeList(),
2116 static const FunctionDecl *
2117 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2118 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2119 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2121 IdentifierInfo &CII = C.Idents.get(Name);
2122 for (const auto &Result : DC->lookup(&CII))
2123 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2126 if (!C.getLangOpts().CPlusPlus)
2129 // Demangle the premangled name from getTerminateFn()
2130 IdentifierInfo &CXXII =
2131 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2132 ? C.Idents.get("terminate")
2133 : C.Idents.get(Name);
2135 for (const auto &N : {"__cxxabiv1", "std"}) {
2136 IdentifierInfo &NS = C.Idents.get(N);
2137 for (const auto &Result : DC->lookup(&NS)) {
2138 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2139 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2140 for (const auto &Result : LSD->lookup(&NS))
2141 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2145 for (const auto &Result : ND->lookup(&CXXII))
2146 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2154 /// CreateRuntimeFunction - Create a new runtime function with the specified
2157 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2158 llvm::AttributeList ExtraAttrs,
2161 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2162 /*DontDefer=*/false, /*IsThunk=*/false,
2165 if (auto *F = dyn_cast<llvm::Function>(C)) {
2167 F->setCallingConv(getRuntimeCC());
2169 if (!Local && getTriple().isOSBinFormatCOFF() &&
2170 !getCodeGenOpts().LTOVisibilityPublicStd) {
2171 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2172 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2173 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2174 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2183 /// CreateBuiltinFunction - Create a new builtin function with the specified
2186 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2187 llvm::AttributeList ExtraAttrs) {
2189 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2190 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2191 if (auto *F = dyn_cast<llvm::Function>(C))
2193 F->setCallingConv(getBuiltinCC());
2197 /// isTypeConstant - Determine whether an object of this type can be emitted
2200 /// If ExcludeCtor is true, the duration when the object's constructor runs
2201 /// will not be considered. The caller will need to verify that the object is
2202 /// not written to during its construction.
2203 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2204 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2207 if (Context.getLangOpts().CPlusPlus) {
2208 if (const CXXRecordDecl *Record
2209 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2210 return ExcludeCtor && !Record->hasMutableFields() &&
2211 Record->hasTrivialDestructor();
2217 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2218 /// create and return an llvm GlobalVariable with the specified type. If there
2219 /// is something in the module with the specified name, return it potentially
2220 /// bitcasted to the right type.
2222 /// If D is non-null, it specifies a decl that correspond to this. This is used
2223 /// to set the attributes on the global when it is first created.
2225 /// If IsForDefinition is true, it is guranteed that an actual global with
2226 /// type Ty will be returned, not conversion of a variable with the same
2227 /// mangled name but some other type.
2229 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2230 llvm::PointerType *Ty,
2232 ForDefinition_t IsForDefinition) {
2233 // Lookup the entry, lazily creating it if necessary.
2234 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2236 if (WeakRefReferences.erase(Entry)) {
2237 if (D && !D->hasAttr<WeakAttr>())
2238 Entry->setLinkage(llvm::Function::ExternalLinkage);
2241 // Handle dropped DLL attributes.
2242 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2243 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2245 if (Entry->getType() == Ty)
2248 // If there are two attempts to define the same mangled name, issue an
2250 if (IsForDefinition && !Entry->isDeclaration()) {
2252 const VarDecl *OtherD;
2254 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2255 // to make sure that we issue an error only once.
2256 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2257 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2258 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2259 OtherD->hasInit() &&
2260 DiagnosedConflictingDefinitions.insert(D).second) {
2261 getDiags().Report(D->getLocation(),
2262 diag::err_duplicate_mangled_name);
2263 getDiags().Report(OtherGD.getDecl()->getLocation(),
2264 diag::note_previous_definition);
2268 // Make sure the result is of the correct type.
2269 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2270 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2272 // (If global is requested for a definition, we always need to create a new
2273 // global, not just return a bitcast.)
2274 if (!IsForDefinition)
2275 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2278 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2279 auto *GV = new llvm::GlobalVariable(
2280 getModule(), Ty->getElementType(), false,
2281 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2282 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2284 // If we already created a global with the same mangled name (but different
2285 // type) before, take its name and remove it from its parent.
2287 GV->takeName(Entry);
2289 if (!Entry->use_empty()) {
2290 llvm::Constant *NewPtrForOldDecl =
2291 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2292 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2295 Entry->eraseFromParent();
2298 // This is the first use or definition of a mangled name. If there is a
2299 // deferred decl with this name, remember that we need to emit it at the end
2301 auto DDI = DeferredDecls.find(MangledName);
2302 if (DDI != DeferredDecls.end()) {
2303 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2304 // list, and remove it from DeferredDecls (since we don't need it anymore).
2305 addDeferredDeclToEmit(GV, DDI->second);
2306 DeferredDecls.erase(DDI);
2309 // Handle things which are present even on external declarations.
2311 // FIXME: This code is overly simple and should be merged with other global
2313 GV->setConstant(isTypeConstant(D->getType(), false));
2315 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2317 setLinkageAndVisibilityForGV(GV, D);
2319 if (D->getTLSKind()) {
2320 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2321 CXXThreadLocals.push_back(D);
2325 // If required by the ABI, treat declarations of static data members with
2326 // inline initializers as definitions.
2327 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2328 EmitGlobalVarDefinition(D);
2331 // Handle XCore specific ABI requirements.
2332 if (getTriple().getArch() == llvm::Triple::xcore &&
2333 D->getLanguageLinkage() == CLanguageLinkage &&
2334 D->getType().isConstant(Context) &&
2335 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2336 GV->setSection(".cp.rodata");
2339 if (AddrSpace != Ty->getAddressSpace())
2340 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2346 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2347 ForDefinition_t IsForDefinition) {
2348 const Decl *D = GD.getDecl();
2349 if (isa<CXXConstructorDecl>(D))
2350 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2351 getFromCtorType(GD.getCtorType()),
2352 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2353 /*DontDefer=*/false, IsForDefinition);
2354 else if (isa<CXXDestructorDecl>(D))
2355 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2356 getFromDtorType(GD.getDtorType()),
2357 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2358 /*DontDefer=*/false, IsForDefinition);
2359 else if (isa<CXXMethodDecl>(D)) {
2360 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2361 cast<CXXMethodDecl>(D));
2362 auto Ty = getTypes().GetFunctionType(*FInfo);
2363 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2365 } else if (isa<FunctionDecl>(D)) {
2366 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2367 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2368 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2371 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2375 llvm::GlobalVariable *
2376 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2378 llvm::GlobalValue::LinkageTypes Linkage) {
2379 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2380 llvm::GlobalVariable *OldGV = nullptr;
2383 // Check if the variable has the right type.
2384 if (GV->getType()->getElementType() == Ty)
2387 // Because C++ name mangling, the only way we can end up with an already
2388 // existing global with the same name is if it has been declared extern "C".
2389 assert(GV->isDeclaration() && "Declaration has wrong type!");
2393 // Create a new variable.
2394 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2395 Linkage, nullptr, Name);
2398 // Replace occurrences of the old variable if needed.
2399 GV->takeName(OldGV);
2401 if (!OldGV->use_empty()) {
2402 llvm::Constant *NewPtrForOldDecl =
2403 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2404 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2407 OldGV->eraseFromParent();
2410 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2411 !GV->hasAvailableExternallyLinkage())
2412 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2417 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2418 /// given global variable. If Ty is non-null and if the global doesn't exist,
2419 /// then it will be created with the specified type instead of whatever the
2420 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2421 /// that an actual global with type Ty will be returned, not conversion of a
2422 /// variable with the same mangled name but some other type.
2423 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2425 ForDefinition_t IsForDefinition) {
2426 assert(D->hasGlobalStorage() && "Not a global variable");
2427 QualType ASTTy = D->getType();
2429 Ty = getTypes().ConvertTypeForMem(ASTTy);
2431 llvm::PointerType *PTy =
2432 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2434 StringRef MangledName = getMangledName(D);
2435 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2438 /// CreateRuntimeVariable - Create a new runtime global variable with the
2439 /// specified type and name.
2441 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2443 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2446 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2447 assert(!D->getInit() && "Cannot emit definite definitions here!");
2449 StringRef MangledName = getMangledName(D);
2450 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2452 // We already have a definition, not declaration, with the same mangled name.
2453 // Emitting of declaration is not required (and actually overwrites emitted
2455 if (GV && !GV->isDeclaration())
2458 // If we have not seen a reference to this variable yet, place it into the
2459 // deferred declarations table to be emitted if needed later.
2460 if (!MustBeEmitted(D) && !GV) {
2461 DeferredDecls[MangledName] = D;
2465 // The tentative definition is the only definition.
2466 EmitGlobalVarDefinition(D);
2469 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2470 return Context.toCharUnitsFromBits(
2471 getDataLayout().getTypeStoreSizeInBits(Ty));
2474 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2475 unsigned AddrSpace) {
2476 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2477 if (D->hasAttr<CUDAConstantAttr>())
2478 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2479 else if (D->hasAttr<CUDASharedAttr>())
2480 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2482 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2488 template<typename SomeDecl>
2489 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2490 llvm::GlobalValue *GV) {
2491 if (!getLangOpts().CPlusPlus)
2494 // Must have 'used' attribute, or else inline assembly can't rely on
2495 // the name existing.
2496 if (!D->template hasAttr<UsedAttr>())
2499 // Must have internal linkage and an ordinary name.
2500 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2503 // Must be in an extern "C" context. Entities declared directly within
2504 // a record are not extern "C" even if the record is in such a context.
2505 const SomeDecl *First = D->getFirstDecl();
2506 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2509 // OK, this is an internal linkage entity inside an extern "C" linkage
2510 // specification. Make a note of that so we can give it the "expected"
2511 // mangled name if nothing else is using that name.
2512 std::pair<StaticExternCMap::iterator, bool> R =
2513 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2515 // If we have multiple internal linkage entities with the same name
2516 // in extern "C" regions, none of them gets that name.
2518 R.first->second = nullptr;
2521 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2522 if (!CGM.supportsCOMDAT())
2525 if (D.hasAttr<SelectAnyAttr>())
2529 if (auto *VD = dyn_cast<VarDecl>(&D))
2530 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2532 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2536 case GVA_AvailableExternally:
2537 case GVA_StrongExternal:
2539 case GVA_DiscardableODR:
2543 llvm_unreachable("No such linkage");
2546 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2547 llvm::GlobalObject &GO) {
2548 if (!shouldBeInCOMDAT(*this, D))
2550 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2553 /// Pass IsTentative as true if you want to create a tentative definition.
2554 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2556 // OpenCL global variables of sampler type are translated to function calls,
2557 // therefore no need to be translated.
2558 QualType ASTTy = D->getType();
2559 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2562 llvm::Constant *Init = nullptr;
2563 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2564 bool NeedsGlobalCtor = false;
2565 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2567 const VarDecl *InitDecl;
2568 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2570 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2571 // as part of their declaration." Sema has already checked for
2572 // error cases, so we just need to set Init to UndefValue.
2573 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2574 D->hasAttr<CUDASharedAttr>())
2575 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2576 else if (!InitExpr) {
2577 // This is a tentative definition; tentative definitions are
2578 // implicitly initialized with { 0 }.
2580 // Note that tentative definitions are only emitted at the end of
2581 // a translation unit, so they should never have incomplete
2582 // type. In addition, EmitTentativeDefinition makes sure that we
2583 // never attempt to emit a tentative definition if a real one
2584 // exists. A use may still exists, however, so we still may need
2586 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2587 Init = EmitNullConstant(D->getType());
2589 initializedGlobalDecl = GlobalDecl(D);
2590 Init = EmitConstantInit(*InitDecl);
2593 QualType T = InitExpr->getType();
2594 if (D->getType()->isReferenceType())
2597 if (getLangOpts().CPlusPlus) {
2598 Init = EmitNullConstant(T);
2599 NeedsGlobalCtor = true;
2601 ErrorUnsupported(D, "static initializer");
2602 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2605 // We don't need an initializer, so remove the entry for the delayed
2606 // initializer position (just in case this entry was delayed) if we
2607 // also don't need to register a destructor.
2608 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2609 DelayedCXXInitPosition.erase(D);
2613 llvm::Type* InitType = Init->getType();
2614 llvm::Constant *Entry =
2615 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2617 // Strip off a bitcast if we got one back.
2618 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2619 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2620 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2621 // All zero index gep.
2622 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2623 Entry = CE->getOperand(0);
2626 // Entry is now either a Function or GlobalVariable.
2627 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2629 // We have a definition after a declaration with the wrong type.
2630 // We must make a new GlobalVariable* and update everything that used OldGV
2631 // (a declaration or tentative definition) with the new GlobalVariable*
2632 // (which will be a definition).
2634 // This happens if there is a prototype for a global (e.g.
2635 // "extern int x[];") and then a definition of a different type (e.g.
2636 // "int x[10];"). This also happens when an initializer has a different type
2637 // from the type of the global (this happens with unions).
2639 GV->getType()->getElementType() != InitType ||
2640 GV->getType()->getAddressSpace() !=
2641 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2643 // Move the old entry aside so that we'll create a new one.
2644 Entry->setName(StringRef());
2646 // Make a new global with the correct type, this is now guaranteed to work.
2647 GV = cast<llvm::GlobalVariable>(
2648 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2650 // Replace all uses of the old global with the new global
2651 llvm::Constant *NewPtrForOldDecl =
2652 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2653 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2655 // Erase the old global, since it is no longer used.
2656 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2659 MaybeHandleStaticInExternC(D, GV);
2661 if (D->hasAttr<AnnotateAttr>())
2662 AddGlobalAnnotations(D, GV);
2664 // Set the llvm linkage type as appropriate.
2665 llvm::GlobalValue::LinkageTypes Linkage =
2666 getLLVMLinkageVarDefinition(D, GV->isConstant());
2668 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2669 // the device. [...]"
2670 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2671 // __device__, declares a variable that: [...]
2672 // Is accessible from all the threads within the grid and from the host
2673 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2674 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2675 if (GV && LangOpts.CUDA) {
2676 if (LangOpts.CUDAIsDevice) {
2677 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2678 GV->setExternallyInitialized(true);
2680 // Host-side shadows of external declarations of device-side
2681 // global variables become internal definitions. These have to
2682 // be internal in order to prevent name conflicts with global
2683 // host variables with the same name in a different TUs.
2684 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2685 Linkage = llvm::GlobalValue::InternalLinkage;
2687 // Shadow variables and their properties must be registered
2688 // with CUDA runtime.
2690 if (!D->hasDefinition())
2691 Flags |= CGCUDARuntime::ExternDeviceVar;
2692 if (D->hasAttr<CUDAConstantAttr>())
2693 Flags |= CGCUDARuntime::ConstantDeviceVar;
2694 getCUDARuntime().registerDeviceVar(*GV, Flags);
2695 } else if (D->hasAttr<CUDASharedAttr>())
2696 // __shared__ variables are odd. Shadows do get created, but
2697 // they are not registered with the CUDA runtime, so they
2698 // can't really be used to access their device-side
2699 // counterparts. It's not clear yet whether it's nvcc's bug or
2700 // a feature, but we've got to do the same for compatibility.
2701 Linkage = llvm::GlobalValue::InternalLinkage;
2704 GV->setInitializer(Init);
2706 // If it is safe to mark the global 'constant', do so now.
2707 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2708 isTypeConstant(D->getType(), true));
2710 // If it is in a read-only section, mark it 'constant'.
2711 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2712 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2713 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2714 GV->setConstant(true);
2717 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2720 // On Darwin, if the normal linkage of a C++ thread_local variable is
2721 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2722 // copies within a linkage unit; otherwise, the backing variable has
2723 // internal linkage and all accesses should just be calls to the
2724 // Itanium-specified entry point, which has the normal linkage of the
2725 // variable. This is to preserve the ability to change the implementation
2726 // behind the scenes.
2727 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2728 Context.getTargetInfo().getTriple().isOSDarwin() &&
2729 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2730 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2731 Linkage = llvm::GlobalValue::InternalLinkage;
2733 GV->setLinkage(Linkage);
2734 if (D->hasAttr<DLLImportAttr>())
2735 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2736 else if (D->hasAttr<DLLExportAttr>())
2737 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2739 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2741 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2742 // common vars aren't constant even if declared const.
2743 GV->setConstant(false);
2744 // Tentative definition of global variables may be initialized with
2745 // non-zero null pointers. In this case they should have weak linkage
2746 // since common linkage must have zero initializer and must not have
2747 // explicit section therefore cannot have non-zero initial value.
2748 if (!GV->getInitializer()->isNullValue())
2749 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2752 setNonAliasAttributes(D, GV);
2754 if (D->getTLSKind() && !GV->isThreadLocal()) {
2755 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2756 CXXThreadLocals.push_back(D);
2760 maybeSetTrivialComdat(*D, *GV);
2762 // Emit the initializer function if necessary.
2763 if (NeedsGlobalCtor || NeedsGlobalDtor)
2764 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2766 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2768 // Emit global variable debug information.
2769 if (CGDebugInfo *DI = getModuleDebugInfo())
2770 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2771 DI->EmitGlobalVariable(GV, D);
2774 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2775 CodeGenModule &CGM, const VarDecl *D,
2777 // Don't give variables common linkage if -fno-common was specified unless it
2778 // was overridden by a NoCommon attribute.
2779 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2783 // A declaration of an identifier for an object that has file scope without
2784 // an initializer, and without a storage-class specifier or with the
2785 // storage-class specifier static, constitutes a tentative definition.
2786 if (D->getInit() || D->hasExternalStorage())
2789 // A variable cannot be both common and exist in a section.
2790 if (D->hasAttr<SectionAttr>())
2793 // Thread local vars aren't considered common linkage.
2794 if (D->getTLSKind())
2797 // Tentative definitions marked with WeakImportAttr are true definitions.
2798 if (D->hasAttr<WeakImportAttr>())
2801 // A variable cannot be both common and exist in a comdat.
2802 if (shouldBeInCOMDAT(CGM, *D))
2805 // Declarations with a required alignment do not have common linkage in MSVC
2807 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2808 if (D->hasAttr<AlignedAttr>())
2810 QualType VarType = D->getType();
2811 if (Context.isAlignmentRequired(VarType))
2814 if (const auto *RT = VarType->getAs<RecordType>()) {
2815 const RecordDecl *RD = RT->getDecl();
2816 for (const FieldDecl *FD : RD->fields()) {
2817 if (FD->isBitField())
2819 if (FD->hasAttr<AlignedAttr>())
2821 if (Context.isAlignmentRequired(FD->getType()))
2830 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2831 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2832 if (Linkage == GVA_Internal)
2833 return llvm::Function::InternalLinkage;
2835 if (D->hasAttr<WeakAttr>()) {
2836 if (IsConstantVariable)
2837 return llvm::GlobalVariable::WeakODRLinkage;
2839 return llvm::GlobalVariable::WeakAnyLinkage;
2842 // We are guaranteed to have a strong definition somewhere else,
2843 // so we can use available_externally linkage.
2844 if (Linkage == GVA_AvailableExternally)
2845 return llvm::GlobalValue::AvailableExternallyLinkage;
2847 // Note that Apple's kernel linker doesn't support symbol
2848 // coalescing, so we need to avoid linkonce and weak linkages there.
2849 // Normally, this means we just map to internal, but for explicit
2850 // instantiations we'll map to external.
2852 // In C++, the compiler has to emit a definition in every translation unit
2853 // that references the function. We should use linkonce_odr because
2854 // a) if all references in this translation unit are optimized away, we
2855 // don't need to codegen it. b) if the function persists, it needs to be
2856 // merged with other definitions. c) C++ has the ODR, so we know the
2857 // definition is dependable.
2858 if (Linkage == GVA_DiscardableODR)
2859 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2860 : llvm::Function::InternalLinkage;
2862 // An explicit instantiation of a template has weak linkage, since
2863 // explicit instantiations can occur in multiple translation units
2864 // and must all be equivalent. However, we are not allowed to
2865 // throw away these explicit instantiations.
2867 // We don't currently support CUDA device code spread out across multiple TUs,
2868 // so say that CUDA templates are either external (for kernels) or internal.
2869 // This lets llvm perform aggressive inter-procedural optimizations.
2870 if (Linkage == GVA_StrongODR) {
2871 if (Context.getLangOpts().AppleKext)
2872 return llvm::Function::ExternalLinkage;
2873 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2874 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2875 : llvm::Function::InternalLinkage;
2876 return llvm::Function::WeakODRLinkage;
2879 // C++ doesn't have tentative definitions and thus cannot have common
2881 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2882 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2883 CodeGenOpts.NoCommon))
2884 return llvm::GlobalVariable::CommonLinkage;
2886 // selectany symbols are externally visible, so use weak instead of
2887 // linkonce. MSVC optimizes away references to const selectany globals, so
2888 // all definitions should be the same and ODR linkage should be used.
2889 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2890 if (D->hasAttr<SelectAnyAttr>())
2891 return llvm::GlobalVariable::WeakODRLinkage;
2893 // Otherwise, we have strong external linkage.
2894 assert(Linkage == GVA_StrongExternal);
2895 return llvm::GlobalVariable::ExternalLinkage;
2898 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2899 const VarDecl *VD, bool IsConstant) {
2900 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2901 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2904 /// Replace the uses of a function that was declared with a non-proto type.
2905 /// We want to silently drop extra arguments from call sites
2906 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2907 llvm::Function *newFn) {
2909 if (old->use_empty()) return;
2911 llvm::Type *newRetTy = newFn->getReturnType();
2912 SmallVector<llvm::Value*, 4> newArgs;
2913 SmallVector<llvm::OperandBundleDef, 1> newBundles;
2915 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2917 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2918 llvm::User *user = use->getUser();
2920 // Recognize and replace uses of bitcasts. Most calls to
2921 // unprototyped functions will use bitcasts.
2922 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2923 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2924 replaceUsesOfNonProtoConstant(bitcast, newFn);
2928 // Recognize calls to the function.
2929 llvm::CallSite callSite(user);
2930 if (!callSite) continue;
2931 if (!callSite.isCallee(&*use)) continue;
2933 // If the return types don't match exactly, then we can't
2934 // transform this call unless it's dead.
2935 if (callSite->getType() != newRetTy && !callSite->use_empty())
2938 // Get the call site's attribute list.
2939 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
2940 llvm::AttributeList oldAttrs = callSite.getAttributes();
2942 // If the function was passed too few arguments, don't transform.
2943 unsigned newNumArgs = newFn->arg_size();
2944 if (callSite.arg_size() < newNumArgs) continue;
2946 // If extra arguments were passed, we silently drop them.
2947 // If any of the types mismatch, we don't transform.
2949 bool dontTransform = false;
2950 for (llvm::Argument &A : newFn->args()) {
2951 if (callSite.getArgument(argNo)->getType() != A.getType()) {
2952 dontTransform = true;
2956 // Add any parameter attributes.
2957 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
2963 // Okay, we can transform this. Create the new call instruction and copy
2964 // over the required information.
2965 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2967 // Copy over any operand bundles.
2968 callSite.getOperandBundlesAsDefs(newBundles);
2970 llvm::CallSite newCall;
2971 if (callSite.isCall()) {
2972 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2973 callSite.getInstruction());
2975 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2976 newCall = llvm::InvokeInst::Create(newFn,
2977 oldInvoke->getNormalDest(),
2978 oldInvoke->getUnwindDest(),
2979 newArgs, newBundles, "",
2980 callSite.getInstruction());
2982 newArgs.clear(); // for the next iteration
2984 if (!newCall->getType()->isVoidTy())
2985 newCall->takeName(callSite.getInstruction());
2986 newCall.setAttributes(llvm::AttributeList::get(
2987 newFn->getContext(), oldAttrs.getFnAttributes(),
2988 oldAttrs.getRetAttributes(), newArgAttrs));
2989 newCall.setCallingConv(callSite.getCallingConv());
2991 // Finally, remove the old call, replacing any uses with the new one.
2992 if (!callSite->use_empty())
2993 callSite->replaceAllUsesWith(newCall.getInstruction());
2995 // Copy debug location attached to CI.
2996 if (callSite->getDebugLoc())
2997 newCall->setDebugLoc(callSite->getDebugLoc());
2999 callSite->eraseFromParent();
3003 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3004 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3005 /// existing call uses of the old function in the module, this adjusts them to
3006 /// call the new function directly.
3008 /// This is not just a cleanup: the always_inline pass requires direct calls to
3009 /// functions to be able to inline them. If there is a bitcast in the way, it
3010 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3012 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3013 llvm::Function *NewFn) {
3014 // If we're redefining a global as a function, don't transform it.
3015 if (!isa<llvm::Function>(Old)) return;
3017 replaceUsesOfNonProtoConstant(Old, NewFn);
3020 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3021 auto DK = VD->isThisDeclarationADefinition();
3022 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3025 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3026 // If we have a definition, this might be a deferred decl. If the
3027 // instantiation is explicit, make sure we emit it at the end.
3028 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3029 GetAddrOfGlobalVar(VD);
3031 EmitTopLevelDecl(VD);
3034 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3035 llvm::GlobalValue *GV) {
3036 const auto *D = cast<FunctionDecl>(GD.getDecl());
3038 // Compute the function info and LLVM type.
3039 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3040 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3042 // Get or create the prototype for the function.
3043 if (!GV || (GV->getType()->getElementType() != Ty))
3044 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3049 if (!GV->isDeclaration())
3052 // We need to set linkage and visibility on the function before
3053 // generating code for it because various parts of IR generation
3054 // want to propagate this information down (e.g. to local static
3056 auto *Fn = cast<llvm::Function>(GV);
3057 setFunctionLinkage(GD, Fn);
3058 setFunctionDLLStorageClass(GD, Fn);
3060 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3061 setGlobalVisibility(Fn, D);
3063 MaybeHandleStaticInExternC(D, Fn);
3065 maybeSetTrivialComdat(*D, *Fn);
3067 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3069 setFunctionDefinitionAttributes(D, Fn);
3070 SetLLVMFunctionAttributesForDefinition(D, Fn);
3072 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3073 AddGlobalCtor(Fn, CA->getPriority());
3074 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3075 AddGlobalDtor(Fn, DA->getPriority());
3076 if (D->hasAttr<AnnotateAttr>())
3077 AddGlobalAnnotations(D, Fn);
3080 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3081 const auto *D = cast<ValueDecl>(GD.getDecl());
3082 const AliasAttr *AA = D->getAttr<AliasAttr>();
3083 assert(AA && "Not an alias?");
3085 StringRef MangledName = getMangledName(GD);
3087 if (AA->getAliasee() == MangledName) {
3088 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3092 // If there is a definition in the module, then it wins over the alias.
3093 // This is dubious, but allow it to be safe. Just ignore the alias.
3094 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3095 if (Entry && !Entry->isDeclaration())
3098 Aliases.push_back(GD);
3100 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3102 // Create a reference to the named value. This ensures that it is emitted
3103 // if a deferred decl.
3104 llvm::Constant *Aliasee;
3105 if (isa<llvm::FunctionType>(DeclTy))
3106 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3107 /*ForVTable=*/false);
3109 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3110 llvm::PointerType::getUnqual(DeclTy),
3113 // Create the new alias itself, but don't set a name yet.
3114 auto *GA = llvm::GlobalAlias::create(
3115 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3118 if (GA->getAliasee() == Entry) {
3119 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3123 assert(Entry->isDeclaration());
3125 // If there is a declaration in the module, then we had an extern followed
3126 // by the alias, as in:
3127 // extern int test6();
3129 // int test6() __attribute__((alias("test7")));
3131 // Remove it and replace uses of it with the alias.
3132 GA->takeName(Entry);
3134 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3136 Entry->eraseFromParent();
3138 GA->setName(MangledName);
3141 // Set attributes which are particular to an alias; this is a
3142 // specialization of the attributes which may be set on a global
3143 // variable/function.
3144 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3145 D->isWeakImported()) {
3146 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3149 if (const auto *VD = dyn_cast<VarDecl>(D))
3150 if (VD->getTLSKind())
3151 setTLSMode(GA, *VD);
3153 setAliasAttributes(D, GA);
3156 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3157 const auto *D = cast<ValueDecl>(GD.getDecl());
3158 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3159 assert(IFA && "Not an ifunc?");
3161 StringRef MangledName = getMangledName(GD);
3163 if (IFA->getResolver() == MangledName) {
3164 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3168 // Report an error if some definition overrides ifunc.
3169 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3170 if (Entry && !Entry->isDeclaration()) {
3172 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3173 DiagnosedConflictingDefinitions.insert(GD).second) {
3174 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3175 Diags.Report(OtherGD.getDecl()->getLocation(),
3176 diag::note_previous_definition);
3181 Aliases.push_back(GD);
3183 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3184 llvm::Constant *Resolver =
3185 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3186 /*ForVTable=*/false);
3187 llvm::GlobalIFunc *GIF =
3188 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3189 "", Resolver, &getModule());
3191 if (GIF->getResolver() == Entry) {
3192 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3195 assert(Entry->isDeclaration());
3197 // If there is a declaration in the module, then we had an extern followed
3198 // by the ifunc, as in:
3199 // extern int test();
3201 // int test() __attribute__((ifunc("resolver")));
3203 // Remove it and replace uses of it with the ifunc.
3204 GIF->takeName(Entry);
3206 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3208 Entry->eraseFromParent();
3210 GIF->setName(MangledName);
3212 SetCommonAttributes(D, GIF);
3215 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3216 ArrayRef<llvm::Type*> Tys) {
3217 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3221 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3222 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3223 const StringLiteral *Literal, bool TargetIsLSB,
3224 bool &IsUTF16, unsigned &StringLength) {
3225 StringRef String = Literal->getString();
3226 unsigned NumBytes = String.size();
3228 // Check for simple case.
3229 if (!Literal->containsNonAsciiOrNull()) {
3230 StringLength = NumBytes;
3231 return *Map.insert(std::make_pair(String, nullptr)).first;
3234 // Otherwise, convert the UTF8 literals into a string of shorts.
3237 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3238 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3239 llvm::UTF16 *ToPtr = &ToBuf[0];
3241 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3242 ToPtr + NumBytes, llvm::strictConversion);
3244 // ConvertUTF8toUTF16 returns the length in ToPtr.
3245 StringLength = ToPtr - &ToBuf[0];
3247 // Add an explicit null.
3249 return *Map.insert(std::make_pair(
3250 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3251 (StringLength + 1) * 2),
3256 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3257 unsigned StringLength = 0;
3258 bool isUTF16 = false;
3259 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3260 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3261 getDataLayout().isLittleEndian(), isUTF16,
3264 if (auto *C = Entry.second)
3265 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3267 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3268 llvm::Constant *Zeros[] = { Zero, Zero };
3270 // If we don't already have it, get __CFConstantStringClassReference.
3271 if (!CFConstantStringClassRef) {
3272 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3273 Ty = llvm::ArrayType::get(Ty, 0);
3274 llvm::Constant *GV =
3275 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3277 if (getTriple().isOSBinFormatCOFF()) {
3278 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3279 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3280 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3281 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3283 const VarDecl *VD = nullptr;
3284 for (const auto &Result : DC->lookup(&II))
3285 if ((VD = dyn_cast<VarDecl>(Result)))
3288 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3289 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3290 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3292 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3293 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3297 // Decay array -> ptr
3298 CFConstantStringClassRef =
3299 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3302 QualType CFTy = getContext().getCFConstantStringType();
3304 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3306 ConstantInitBuilder Builder(*this);
3307 auto Fields = Builder.beginStruct(STy);
3310 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3313 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3316 llvm::Constant *C = nullptr;
3318 auto Arr = llvm::makeArrayRef(
3319 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3320 Entry.first().size() / 2);
3321 C = llvm::ConstantDataArray::get(VMContext, Arr);
3323 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3326 // Note: -fwritable-strings doesn't make the backing store strings of
3327 // CFStrings writable. (See <rdar://problem/10657500>)
3329 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3330 llvm::GlobalValue::PrivateLinkage, C, ".str");
3331 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3332 // Don't enforce the target's minimum global alignment, since the only use
3333 // of the string is via this class initializer.
3334 CharUnits Align = isUTF16
3335 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3336 : getContext().getTypeAlignInChars(getContext().CharTy);
3337 GV->setAlignment(Align.getQuantity());
3339 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3340 // Without it LLVM can merge the string with a non unnamed_addr one during
3341 // LTO. Doing that changes the section it ends in, which surprises ld64.
3342 if (getTriple().isOSBinFormatMachO())
3343 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3344 : "__TEXT,__cstring,cstring_literals");
3347 llvm::Constant *Str =
3348 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3351 // Cast the UTF16 string to the correct type.
3352 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3356 auto Ty = getTypes().ConvertType(getContext().LongTy);
3357 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3359 CharUnits Alignment = getPointerAlign();
3362 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3363 /*isConstant=*/false,
3364 llvm::GlobalVariable::PrivateLinkage);
3365 switch (getTriple().getObjectFormat()) {
3366 case llvm::Triple::UnknownObjectFormat:
3367 llvm_unreachable("unknown file format");
3368 case llvm::Triple::COFF:
3369 case llvm::Triple::ELF:
3370 case llvm::Triple::Wasm:
3371 GV->setSection("cfstring");
3373 case llvm::Triple::MachO:
3374 GV->setSection("__DATA,__cfstring");
3379 return ConstantAddress(GV, Alignment);
3382 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3383 if (ObjCFastEnumerationStateType.isNull()) {
3384 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3385 D->startDefinition();
3387 QualType FieldTypes[] = {
3388 Context.UnsignedLongTy,
3389 Context.getPointerType(Context.getObjCIdType()),
3390 Context.getPointerType(Context.UnsignedLongTy),
3391 Context.getConstantArrayType(Context.UnsignedLongTy,
3392 llvm::APInt(32, 5), ArrayType::Normal, 0)
3395 for (size_t i = 0; i < 4; ++i) {
3396 FieldDecl *Field = FieldDecl::Create(Context,
3399 SourceLocation(), nullptr,
3400 FieldTypes[i], /*TInfo=*/nullptr,
3401 /*BitWidth=*/nullptr,
3404 Field->setAccess(AS_public);
3408 D->completeDefinition();
3409 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3412 return ObjCFastEnumerationStateType;
3416 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3417 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3419 // Don't emit it as the address of the string, emit the string data itself
3420 // as an inline array.
3421 if (E->getCharByteWidth() == 1) {
3422 SmallString<64> Str(E->getString());
3424 // Resize the string to the right size, which is indicated by its type.
3425 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3426 Str.resize(CAT->getSize().getZExtValue());
3427 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3430 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3431 llvm::Type *ElemTy = AType->getElementType();
3432 unsigned NumElements = AType->getNumElements();
3434 // Wide strings have either 2-byte or 4-byte elements.
3435 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3436 SmallVector<uint16_t, 32> Elements;
3437 Elements.reserve(NumElements);
3439 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3440 Elements.push_back(E->getCodeUnit(i));
3441 Elements.resize(NumElements);
3442 return llvm::ConstantDataArray::get(VMContext, Elements);
3445 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3446 SmallVector<uint32_t, 32> Elements;
3447 Elements.reserve(NumElements);
3449 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3450 Elements.push_back(E->getCodeUnit(i));
3451 Elements.resize(NumElements);
3452 return llvm::ConstantDataArray::get(VMContext, Elements);
3455 static llvm::GlobalVariable *
3456 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3457 CodeGenModule &CGM, StringRef GlobalName,
3458 CharUnits Alignment) {
3459 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3460 unsigned AddrSpace = 0;
3461 if (CGM.getLangOpts().OpenCL)
3462 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3464 llvm::Module &M = CGM.getModule();
3465 // Create a global variable for this string
3466 auto *GV = new llvm::GlobalVariable(
3467 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3468 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3469 GV->setAlignment(Alignment.getQuantity());
3470 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3471 if (GV->isWeakForLinker()) {
3472 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3473 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3479 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3480 /// constant array for the given string literal.
3482 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3484 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3486 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3487 llvm::GlobalVariable **Entry = nullptr;
3488 if (!LangOpts.WritableStrings) {
3489 Entry = &ConstantStringMap[C];
3490 if (auto GV = *Entry) {
3491 if (Alignment.getQuantity() > GV->getAlignment())
3492 GV->setAlignment(Alignment.getQuantity());
3493 return ConstantAddress(GV, Alignment);
3497 SmallString<256> MangledNameBuffer;
3498 StringRef GlobalVariableName;
3499 llvm::GlobalValue::LinkageTypes LT;
3501 // Mangle the string literal if the ABI allows for it. However, we cannot
3502 // do this if we are compiling with ASan or -fwritable-strings because they
3503 // rely on strings having normal linkage.
3504 if (!LangOpts.WritableStrings &&
3505 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3506 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3507 llvm::raw_svector_ostream Out(MangledNameBuffer);
3508 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3510 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3511 GlobalVariableName = MangledNameBuffer;
3513 LT = llvm::GlobalValue::PrivateLinkage;
3514 GlobalVariableName = Name;
3517 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3521 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3523 return ConstantAddress(GV, Alignment);
3526 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3527 /// array for the given ObjCEncodeExpr node.
3529 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3531 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3533 return GetAddrOfConstantCString(Str);
3536 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3537 /// the literal and a terminating '\0' character.
3538 /// The result has pointer to array type.
3539 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3540 const std::string &Str, const char *GlobalName) {
3541 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3542 CharUnits Alignment =
3543 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3546 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3548 // Don't share any string literals if strings aren't constant.
3549 llvm::GlobalVariable **Entry = nullptr;
3550 if (!LangOpts.WritableStrings) {
3551 Entry = &ConstantStringMap[C];
3552 if (auto GV = *Entry) {
3553 if (Alignment.getQuantity() > GV->getAlignment())
3554 GV->setAlignment(Alignment.getQuantity());
3555 return ConstantAddress(GV, Alignment);
3559 // Get the default prefix if a name wasn't specified.
3561 GlobalName = ".str";
3562 // Create a global variable for this.
3563 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3564 GlobalName, Alignment);
3567 return ConstantAddress(GV, Alignment);
3570 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3571 const MaterializeTemporaryExpr *E, const Expr *Init) {
3572 assert((E->getStorageDuration() == SD_Static ||
3573 E->getStorageDuration() == SD_Thread) && "not a global temporary");
3574 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3576 // If we're not materializing a subobject of the temporary, keep the
3577 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3578 QualType MaterializedType = Init->getType();
3579 if (Init == E->GetTemporaryExpr())
3580 MaterializedType = E->getType();
3582 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3584 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3585 return ConstantAddress(Slot, Align);
3587 // FIXME: If an externally-visible declaration extends multiple temporaries,
3588 // we need to give each temporary the same name in every translation unit (and
3589 // we also need to make the temporaries externally-visible).
3590 SmallString<256> Name;
3591 llvm::raw_svector_ostream Out(Name);
3592 getCXXABI().getMangleContext().mangleReferenceTemporary(
3593 VD, E->getManglingNumber(), Out);
3595 APValue *Value = nullptr;
3596 if (E->getStorageDuration() == SD_Static) {
3597 // We might have a cached constant initializer for this temporary. Note
3598 // that this might have a different value from the value computed by
3599 // evaluating the initializer if the surrounding constant expression
3600 // modifies the temporary.
3601 Value = getContext().getMaterializedTemporaryValue(E, false);
3602 if (Value && Value->isUninit())
3606 // Try evaluating it now, it might have a constant initializer.
3607 Expr::EvalResult EvalResult;
3608 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3609 !EvalResult.hasSideEffects())
3610 Value = &EvalResult.Val;
3612 llvm::Constant *InitialValue = nullptr;
3613 bool Constant = false;
3616 // The temporary has a constant initializer, use it.
3617 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3618 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3619 Type = InitialValue->getType();
3621 // No initializer, the initialization will be provided when we
3622 // initialize the declaration which performed lifetime extension.
3623 Type = getTypes().ConvertTypeForMem(MaterializedType);
3626 // Create a global variable for this lifetime-extended temporary.
3627 llvm::GlobalValue::LinkageTypes Linkage =
3628 getLLVMLinkageVarDefinition(VD, Constant);
3629 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3630 const VarDecl *InitVD;
3631 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3632 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3633 // Temporaries defined inside a class get linkonce_odr linkage because the
3634 // class can be defined in multipe translation units.
3635 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3637 // There is no need for this temporary to have external linkage if the
3638 // VarDecl has external linkage.
3639 Linkage = llvm::GlobalVariable::InternalLinkage;
3642 unsigned AddrSpace = GetGlobalVarAddressSpace(
3643 VD, getContext().getTargetAddressSpace(MaterializedType));
3644 auto *GV = new llvm::GlobalVariable(
3645 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3646 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3648 setGlobalVisibility(GV, VD);
3649 GV->setAlignment(Align.getQuantity());
3650 if (supportsCOMDAT() && GV->isWeakForLinker())
3651 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3652 if (VD->getTLSKind())
3653 setTLSMode(GV, *VD);
3654 MaterializedGlobalTemporaryMap[E] = GV;
3655 return ConstantAddress(GV, Align);
3658 /// EmitObjCPropertyImplementations - Emit information for synthesized
3659 /// properties for an implementation.
3660 void CodeGenModule::EmitObjCPropertyImplementations(const
3661 ObjCImplementationDecl *D) {
3662 for (const auto *PID : D->property_impls()) {
3663 // Dynamic is just for type-checking.
3664 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3665 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3667 // Determine which methods need to be implemented, some may have
3668 // been overridden. Note that ::isPropertyAccessor is not the method
3669 // we want, that just indicates if the decl came from a
3670 // property. What we want to know is if the method is defined in
3671 // this implementation.
3672 if (!D->getInstanceMethod(PD->getGetterName()))
3673 CodeGenFunction(*this).GenerateObjCGetter(
3674 const_cast<ObjCImplementationDecl *>(D), PID);
3675 if (!PD->isReadOnly() &&
3676 !D->getInstanceMethod(PD->getSetterName()))
3677 CodeGenFunction(*this).GenerateObjCSetter(
3678 const_cast<ObjCImplementationDecl *>(D), PID);
3683 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3684 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3685 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3686 ivar; ivar = ivar->getNextIvar())
3687 if (ivar->getType().isDestructedType())
3693 static bool AllTrivialInitializers(CodeGenModule &CGM,
3694 ObjCImplementationDecl *D) {
3695 CodeGenFunction CGF(CGM);
3696 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3697 E = D->init_end(); B != E; ++B) {
3698 CXXCtorInitializer *CtorInitExp = *B;
3699 Expr *Init = CtorInitExp->getInit();
3700 if (!CGF.isTrivialInitializer(Init))
3706 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3707 /// for an implementation.
3708 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3709 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3710 if (needsDestructMethod(D)) {
3711 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3712 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3713 ObjCMethodDecl *DTORMethod =
3714 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3715 cxxSelector, getContext().VoidTy, nullptr, D,
3716 /*isInstance=*/true, /*isVariadic=*/false,
3717 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3718 /*isDefined=*/false, ObjCMethodDecl::Required);
3719 D->addInstanceMethod(DTORMethod);
3720 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3721 D->setHasDestructors(true);
3724 // If the implementation doesn't have any ivar initializers, we don't need
3725 // a .cxx_construct.
3726 if (D->getNumIvarInitializers() == 0 ||
3727 AllTrivialInitializers(*this, D))
3730 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3731 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3732 // The constructor returns 'self'.
3733 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3737 getContext().getObjCIdType(),
3738 nullptr, D, /*isInstance=*/true,
3739 /*isVariadic=*/false,
3740 /*isPropertyAccessor=*/true,
3741 /*isImplicitlyDeclared=*/true,
3742 /*isDefined=*/false,
3743 ObjCMethodDecl::Required);
3744 D->addInstanceMethod(CTORMethod);
3745 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3746 D->setHasNonZeroConstructors(true);
3749 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3750 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3751 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3752 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3753 ErrorUnsupported(LSD, "linkage spec");
3757 EmitDeclContext(LSD);
3760 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3761 for (auto *I : DC->decls()) {
3762 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3763 // are themselves considered "top-level", so EmitTopLevelDecl on an
3764 // ObjCImplDecl does not recursively visit them. We need to do that in
3765 // case they're nested inside another construct (LinkageSpecDecl /
3766 // ExportDecl) that does stop them from being considered "top-level".
3767 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3768 for (auto *M : OID->methods())
3769 EmitTopLevelDecl(M);
3772 EmitTopLevelDecl(I);
3776 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3777 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3778 // Ignore dependent declarations.
3779 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3782 switch (D->getKind()) {
3783 case Decl::CXXConversion:
3784 case Decl::CXXMethod:
3785 case Decl::Function:
3786 // Skip function templates
3787 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3788 cast<FunctionDecl>(D)->isLateTemplateParsed())
3791 EmitGlobal(cast<FunctionDecl>(D));
3792 // Always provide some coverage mapping
3793 // even for the functions that aren't emitted.
3794 AddDeferredUnusedCoverageMapping(D);
3797 case Decl::CXXDeductionGuide:
3798 // Function-like, but does not result in code emission.
3802 case Decl::Decomposition:
3803 // Skip variable templates
3804 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3806 case Decl::VarTemplateSpecialization:
3807 EmitGlobal(cast<VarDecl>(D));
3808 if (auto *DD = dyn_cast<DecompositionDecl>(D))
3809 for (auto *B : DD->bindings())
3810 if (auto *HD = B->getHoldingVar())
3814 // Indirect fields from global anonymous structs and unions can be
3815 // ignored; only the actual variable requires IR gen support.
3816 case Decl::IndirectField:
3820 case Decl::Namespace:
3821 EmitDeclContext(cast<NamespaceDecl>(D));
3823 case Decl::CXXRecord:
3825 if (auto *ES = D->getASTContext().getExternalSource())
3826 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3827 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3829 // Emit any static data members, they may be definitions.
3830 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3831 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3832 EmitTopLevelDecl(I);
3834 // No code generation needed.
3835 case Decl::UsingShadow:
3836 case Decl::ClassTemplate:
3837 case Decl::VarTemplate:
3838 case Decl::VarTemplatePartialSpecialization:
3839 case Decl::FunctionTemplate:
3840 case Decl::TypeAliasTemplate:
3844 case Decl::Using: // using X; [C++]
3845 if (CGDebugInfo *DI = getModuleDebugInfo())
3846 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3848 case Decl::NamespaceAlias:
3849 if (CGDebugInfo *DI = getModuleDebugInfo())
3850 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3852 case Decl::UsingDirective: // using namespace X; [C++]
3853 if (CGDebugInfo *DI = getModuleDebugInfo())
3854 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3856 case Decl::CXXConstructor:
3857 // Skip function templates
3858 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3859 cast<FunctionDecl>(D)->isLateTemplateParsed())
3862 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3864 case Decl::CXXDestructor:
3865 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3867 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3870 case Decl::StaticAssert:
3874 // Objective-C Decls
3876 // Forward declarations, no (immediate) code generation.
3877 case Decl::ObjCInterface:
3878 case Decl::ObjCCategory:
3881 case Decl::ObjCProtocol: {
3882 auto *Proto = cast<ObjCProtocolDecl>(D);
3883 if (Proto->isThisDeclarationADefinition())
3884 ObjCRuntime->GenerateProtocol(Proto);
3888 case Decl::ObjCCategoryImpl:
3889 // Categories have properties but don't support synthesize so we
3890 // can ignore them here.
3891 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3894 case Decl::ObjCImplementation: {
3895 auto *OMD = cast<ObjCImplementationDecl>(D);
3896 EmitObjCPropertyImplementations(OMD);
3897 EmitObjCIvarInitializations(OMD);
3898 ObjCRuntime->GenerateClass(OMD);
3899 // Emit global variable debug information.
3900 if (CGDebugInfo *DI = getModuleDebugInfo())
3901 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3902 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3903 OMD->getClassInterface()), OMD->getLocation());
3906 case Decl::ObjCMethod: {
3907 auto *OMD = cast<ObjCMethodDecl>(D);
3908 // If this is not a prototype, emit the body.
3910 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3913 case Decl::ObjCCompatibleAlias:
3914 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3917 case Decl::PragmaComment: {
3918 const auto *PCD = cast<PragmaCommentDecl>(D);
3919 switch (PCD->getCommentKind()) {
3921 llvm_unreachable("unexpected pragma comment kind");
3923 AppendLinkerOptions(PCD->getArg());
3926 AddDependentLib(PCD->getArg());
3931 break; // We ignore all of these.
3936 case Decl::PragmaDetectMismatch: {
3937 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3938 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3942 case Decl::LinkageSpec:
3943 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3946 case Decl::FileScopeAsm: {
3947 // File-scope asm is ignored during device-side CUDA compilation.
3948 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3950 // File-scope asm is ignored during device-side OpenMP compilation.
3951 if (LangOpts.OpenMPIsDevice)
3953 auto *AD = cast<FileScopeAsmDecl>(D);
3954 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3958 case Decl::Import: {
3959 auto *Import = cast<ImportDecl>(D);
3961 // If we've already imported this module, we're done.
3962 if (!ImportedModules.insert(Import->getImportedModule()))
3965 // Emit debug information for direct imports.
3966 if (!Import->getImportedOwningModule()) {
3967 if (CGDebugInfo *DI = getModuleDebugInfo())
3968 DI->EmitImportDecl(*Import);
3971 // Find all of the submodules and emit the module initializers.
3972 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3973 SmallVector<clang::Module *, 16> Stack;
3974 Visited.insert(Import->getImportedModule());
3975 Stack.push_back(Import->getImportedModule());
3977 while (!Stack.empty()) {
3978 clang::Module *Mod = Stack.pop_back_val();
3979 if (!EmittedModuleInitializers.insert(Mod).second)
3982 for (auto *D : Context.getModuleInitializers(Mod))
3983 EmitTopLevelDecl(D);
3985 // Visit the submodules of this module.
3986 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
3987 SubEnd = Mod->submodule_end();
3988 Sub != SubEnd; ++Sub) {
3989 // Skip explicit children; they need to be explicitly imported to emit
3990 // the initializers.
3991 if ((*Sub)->IsExplicit)
3994 if (Visited.insert(*Sub).second)
3995 Stack.push_back(*Sub);
4002 EmitDeclContext(cast<ExportDecl>(D));
4005 case Decl::OMPThreadPrivate:
4006 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4009 case Decl::ClassTemplateSpecialization: {
4010 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4012 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4013 Spec->hasDefinition())
4014 DebugInfo->completeTemplateDefinition(*Spec);
4018 case Decl::OMPDeclareReduction:
4019 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4023 // Make sure we handled everything we should, every other kind is a
4024 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4025 // function. Need to recode Decl::Kind to do that easily.
4026 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4031 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4032 // Do we need to generate coverage mapping?
4033 if (!CodeGenOpts.CoverageMapping)
4035 switch (D->getKind()) {
4036 case Decl::CXXConversion:
4037 case Decl::CXXMethod:
4038 case Decl::Function:
4039 case Decl::ObjCMethod:
4040 case Decl::CXXConstructor:
4041 case Decl::CXXDestructor: {
4042 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4044 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4045 if (I == DeferredEmptyCoverageMappingDecls.end())
4046 DeferredEmptyCoverageMappingDecls[D] = true;
4054 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4055 // Do we need to generate coverage mapping?
4056 if (!CodeGenOpts.CoverageMapping)
4058 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4059 if (Fn->isTemplateInstantiation())
4060 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4062 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4063 if (I == DeferredEmptyCoverageMappingDecls.end())
4064 DeferredEmptyCoverageMappingDecls[D] = false;
4069 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4070 std::vector<const Decl *> DeferredDecls;
4071 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4074 DeferredDecls.push_back(I.first);
4076 // Sort the declarations by their location to make sure that the tests get a
4077 // predictable order for the coverage mapping for the unused declarations.
4078 if (CodeGenOpts.DumpCoverageMapping)
4079 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4080 [] (const Decl *LHS, const Decl *RHS) {
4081 return LHS->getLocStart() < RHS->getLocStart();
4083 for (const auto *D : DeferredDecls) {
4084 switch (D->getKind()) {
4085 case Decl::CXXConversion:
4086 case Decl::CXXMethod:
4087 case Decl::Function:
4088 case Decl::ObjCMethod: {
4089 CodeGenPGO PGO(*this);
4090 GlobalDecl GD(cast<FunctionDecl>(D));
4091 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4092 getFunctionLinkage(GD));
4095 case Decl::CXXConstructor: {
4096 CodeGenPGO PGO(*this);
4097 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4098 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4099 getFunctionLinkage(GD));
4102 case Decl::CXXDestructor: {
4103 CodeGenPGO PGO(*this);
4104 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4105 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4106 getFunctionLinkage(GD));
4115 /// Turns the given pointer into a constant.
4116 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4118 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4119 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4120 return llvm::ConstantInt::get(i64, PtrInt);
4123 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4124 llvm::NamedMDNode *&GlobalMetadata,
4126 llvm::GlobalValue *Addr) {
4127 if (!GlobalMetadata)
4129 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4131 // TODO: should we report variant information for ctors/dtors?
4132 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4133 llvm::ConstantAsMetadata::get(GetPointerConstant(
4134 CGM.getLLVMContext(), D.getDecl()))};
4135 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4138 /// For each function which is declared within an extern "C" region and marked
4139 /// as 'used', but has internal linkage, create an alias from the unmangled
4140 /// name to the mangled name if possible. People expect to be able to refer
4141 /// to such functions with an unmangled name from inline assembly within the
4142 /// same translation unit.
4143 void CodeGenModule::EmitStaticExternCAliases() {
4144 // Don't do anything if we're generating CUDA device code -- the NVPTX
4145 // assembly target doesn't support aliases.
4146 if (Context.getTargetInfo().getTriple().isNVPTX())
4148 for (auto &I : StaticExternCValues) {
4149 IdentifierInfo *Name = I.first;
4150 llvm::GlobalValue *Val = I.second;
4151 if (Val && !getModule().getNamedValue(Name->getName()))
4152 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4156 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4157 GlobalDecl &Result) const {
4158 auto Res = Manglings.find(MangledName);
4159 if (Res == Manglings.end())
4161 Result = Res->getValue();
4165 /// Emits metadata nodes associating all the global values in the
4166 /// current module with the Decls they came from. This is useful for
4167 /// projects using IR gen as a subroutine.
4169 /// Since there's currently no way to associate an MDNode directly
4170 /// with an llvm::GlobalValue, we create a global named metadata
4171 /// with the name 'clang.global.decl.ptrs'.
4172 void CodeGenModule::EmitDeclMetadata() {
4173 llvm::NamedMDNode *GlobalMetadata = nullptr;
4175 for (auto &I : MangledDeclNames) {
4176 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4177 // Some mangled names don't necessarily have an associated GlobalValue
4178 // in this module, e.g. if we mangled it for DebugInfo.
4180 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4184 /// Emits metadata nodes for all the local variables in the current
4186 void CodeGenFunction::EmitDeclMetadata() {
4187 if (LocalDeclMap.empty()) return;
4189 llvm::LLVMContext &Context = getLLVMContext();
4191 // Find the unique metadata ID for this name.
4192 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4194 llvm::NamedMDNode *GlobalMetadata = nullptr;
4196 for (auto &I : LocalDeclMap) {
4197 const Decl *D = I.first;
4198 llvm::Value *Addr = I.second.getPointer();
4199 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4200 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4201 Alloca->setMetadata(
4202 DeclPtrKind, llvm::MDNode::get(
4203 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4204 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4205 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4206 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4211 void CodeGenModule::EmitVersionIdentMetadata() {
4212 llvm::NamedMDNode *IdentMetadata =
4213 TheModule.getOrInsertNamedMetadata("llvm.ident");
4214 std::string Version = getClangFullVersion();
4215 llvm::LLVMContext &Ctx = TheModule.getContext();
4217 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4218 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4221 void CodeGenModule::EmitTargetMetadata() {
4222 // Warning, new MangledDeclNames may be appended within this loop.
4223 // We rely on MapVector insertions adding new elements to the end
4224 // of the container.
4225 // FIXME: Move this loop into the one target that needs it, and only
4226 // loop over those declarations for which we couldn't emit the target
4227 // metadata when we emitted the declaration.
4228 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4229 auto Val = *(MangledDeclNames.begin() + I);
4230 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4231 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4232 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4236 void CodeGenModule::EmitCoverageFile() {
4237 if (getCodeGenOpts().CoverageDataFile.empty() &&
4238 getCodeGenOpts().CoverageNotesFile.empty())
4241 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4245 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4246 llvm::LLVMContext &Ctx = TheModule.getContext();
4247 auto *CoverageDataFile =
4248 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4249 auto *CoverageNotesFile =
4250 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4251 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4252 llvm::MDNode *CU = CUNode->getOperand(i);
4253 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4254 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4258 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4259 // Sema has checked that all uuid strings are of the form
4260 // "12345678-1234-1234-1234-1234567890ab".
4261 assert(Uuid.size() == 36);
4262 for (unsigned i = 0; i < 36; ++i) {
4263 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4264 else assert(isHexDigit(Uuid[i]));
4267 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4268 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4270 llvm::Constant *Field3[8];
4271 for (unsigned Idx = 0; Idx < 8; ++Idx)
4272 Field3[Idx] = llvm::ConstantInt::get(
4273 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4275 llvm::Constant *Fields[4] = {
4276 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4277 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4278 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4279 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4282 return llvm::ConstantStruct::getAnon(Fields);
4285 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4287 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4288 // FIXME: should we even be calling this method if RTTI is disabled
4289 // and it's not for EH?
4290 if (!ForEH && !getLangOpts().RTTI)
4291 return llvm::Constant::getNullValue(Int8PtrTy);
4293 if (ForEH && Ty->isObjCObjectPointerType() &&
4294 LangOpts.ObjCRuntime.isGNUFamily())
4295 return ObjCRuntime->GetEHType(Ty);
4297 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4300 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4301 for (auto RefExpr : D->varlists()) {
4302 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4304 VD->getAnyInitializer() &&
4305 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4308 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4309 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4310 VD, Addr, RefExpr->getLocStart(), PerformInit))
4311 CXXGlobalInits.push_back(InitFunction);
4315 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4316 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4320 if (isExternallyVisible(T->getLinkage())) {
4321 std::string OutName;
4322 llvm::raw_string_ostream Out(OutName);
4323 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4325 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4327 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4328 llvm::ArrayRef<llvm::Metadata *>());
4334 /// Returns whether this module needs the "all-vtables" type identifier.
4335 bool CodeGenModule::NeedAllVtablesTypeId() const {
4336 // Returns true if at least one of vtable-based CFI checkers is enabled and
4337 // is not in the trapping mode.
4338 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4339 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4340 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4341 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4342 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4343 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4344 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4345 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4348 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4350 const CXXRecordDecl *RD) {
4351 llvm::Metadata *MD =
4352 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4353 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4355 if (CodeGenOpts.SanitizeCfiCrossDso)
4356 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4357 VTable->addTypeMetadata(Offset.getQuantity(),
4358 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4360 if (NeedAllVtablesTypeId()) {
4361 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4362 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4366 // Fills in the supplied string map with the set of target features for the
4367 // passed in function.
4368 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4369 const FunctionDecl *FD) {
4370 StringRef TargetCPU = Target.getTargetOpts().CPU;
4371 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4372 // If we have a TargetAttr build up the feature map based on that.
4373 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4375 // Make a copy of the features as passed on the command line into the
4376 // beginning of the additional features from the function to override.
4377 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4378 Target.getTargetOpts().FeaturesAsWritten.begin(),
4379 Target.getTargetOpts().FeaturesAsWritten.end());
4381 if (ParsedAttr.second != "")
4382 TargetCPU = ParsedAttr.second;
4384 // Now populate the feature map, first with the TargetCPU which is either
4385 // the default or a new one from the target attribute string. Then we'll use
4386 // the passed in features (FeaturesAsWritten) along with the new ones from
4388 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4390 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4391 Target.getTargetOpts().Features);
4395 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4397 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4402 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4403 CodeGenFunction &CGF) {
4404 llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4405 auto SamplerT = getOpenCLRuntime().getSamplerType();
4406 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4407 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4408 "__translate_sampler_initializer"),