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 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
569 llvm::MDNode::get(getLLVMContext(), {}));
572 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
573 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
574 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
577 /// ErrorUnsupported - Print out an error that codegen doesn't support the
578 /// specified stmt yet.
579 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
580 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
581 "cannot compile this %0 yet");
582 std::string Msg = Type;
583 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
584 << Msg << S->getSourceRange();
587 /// ErrorUnsupported - Print out an error that codegen doesn't support the
588 /// specified decl yet.
589 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
590 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
591 "cannot compile this %0 yet");
592 std::string Msg = Type;
593 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
596 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
597 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
600 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
601 const NamedDecl *D) const {
602 // Internal definitions always have default visibility.
603 if (GV->hasLocalLinkage()) {
604 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
608 // Set visibility for definitions.
609 LinkageInfo LV = D->getLinkageAndVisibility();
610 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
611 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
614 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
615 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
616 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
617 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
618 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
619 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
622 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
623 CodeGenOptions::TLSModel M) {
625 case CodeGenOptions::GeneralDynamicTLSModel:
626 return llvm::GlobalVariable::GeneralDynamicTLSModel;
627 case CodeGenOptions::LocalDynamicTLSModel:
628 return llvm::GlobalVariable::LocalDynamicTLSModel;
629 case CodeGenOptions::InitialExecTLSModel:
630 return llvm::GlobalVariable::InitialExecTLSModel;
631 case CodeGenOptions::LocalExecTLSModel:
632 return llvm::GlobalVariable::LocalExecTLSModel;
634 llvm_unreachable("Invalid TLS model!");
637 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
638 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
640 llvm::GlobalValue::ThreadLocalMode TLM;
641 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
643 // Override the TLS model if it is explicitly specified.
644 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
645 TLM = GetLLVMTLSModel(Attr->getModel());
648 GV->setThreadLocalMode(TLM);
651 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
652 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
654 // Some ABIs don't have constructor variants. Make sure that base and
655 // complete constructors get mangled the same.
656 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
657 if (!getTarget().getCXXABI().hasConstructorVariants()) {
658 CXXCtorType OrigCtorType = GD.getCtorType();
659 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
660 if (OrigCtorType == Ctor_Base)
661 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
665 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
666 if (!FoundStr.empty())
669 const auto *ND = cast<NamedDecl>(GD.getDecl());
670 SmallString<256> Buffer;
672 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
673 llvm::raw_svector_ostream Out(Buffer);
674 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
675 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
676 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
677 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
679 getCXXABI().getMangleContext().mangleName(ND, Out);
682 IdentifierInfo *II = ND->getIdentifier();
683 assert(II && "Attempt to mangle unnamed decl.");
684 const auto *FD = dyn_cast<FunctionDecl>(ND);
687 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
688 llvm::raw_svector_ostream Out(Buffer);
689 Out << "__regcall3__" << II->getName();
696 // Keep the first result in the case of a mangling collision.
697 auto Result = Manglings.insert(std::make_pair(Str, GD));
698 return FoundStr = Result.first->first();
701 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
702 const BlockDecl *BD) {
703 MangleContext &MangleCtx = getCXXABI().getMangleContext();
704 const Decl *D = GD.getDecl();
706 SmallString<256> Buffer;
707 llvm::raw_svector_ostream Out(Buffer);
709 MangleCtx.mangleGlobalBlock(BD,
710 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
711 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
712 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
713 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
714 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
716 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
718 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
719 return Result.first->first();
722 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
723 return getModule().getNamedValue(Name);
726 /// AddGlobalCtor - Add a function to the list that will be called before
728 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
729 llvm::Constant *AssociatedData) {
730 // FIXME: Type coercion of void()* types.
731 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
734 /// AddGlobalDtor - Add a function to the list that will be called
735 /// when the module is unloaded.
736 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
737 // FIXME: Type coercion of void()* types.
738 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
741 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
742 if (Fns.empty()) return;
744 // Ctor function type is void()*.
745 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
746 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
748 // Get the type of a ctor entry, { i32, void ()*, i8* }.
749 llvm::StructType *CtorStructTy = llvm::StructType::get(
750 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
752 // Construct the constructor and destructor arrays.
753 ConstantInitBuilder builder(*this);
754 auto ctors = builder.beginArray(CtorStructTy);
755 for (const auto &I : Fns) {
756 auto ctor = ctors.beginStruct(CtorStructTy);
757 ctor.addInt(Int32Ty, I.Priority);
758 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
759 if (I.AssociatedData)
760 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
762 ctor.addNullPointer(VoidPtrTy);
763 ctor.finishAndAddTo(ctors);
767 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
769 llvm::GlobalValue::AppendingLinkage);
771 // The LTO linker doesn't seem to like it when we set an alignment
772 // on appending variables. Take it off as a workaround.
773 list->setAlignment(0);
778 llvm::GlobalValue::LinkageTypes
779 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
780 const auto *D = cast<FunctionDecl>(GD.getDecl());
782 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
784 if (isa<CXXDestructorDecl>(D) &&
785 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
787 // Destructor variants in the Microsoft C++ ABI are always internal or
788 // linkonce_odr thunks emitted on an as-needed basis.
789 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
790 : llvm::GlobalValue::LinkOnceODRLinkage;
793 if (isa<CXXConstructorDecl>(D) &&
794 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
795 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
796 // Our approach to inheriting constructors is fundamentally different from
797 // that used by the MS ABI, so keep our inheriting constructor thunks
798 // internal rather than trying to pick an unambiguous mangling for them.
799 return llvm::GlobalValue::InternalLinkage;
802 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
805 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
806 const auto *FD = cast<FunctionDecl>(GD.getDecl());
808 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
809 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
810 // Don't dllexport/import destructor thunks.
811 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
816 if (FD->hasAttr<DLLImportAttr>())
817 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
818 else if (FD->hasAttr<DLLExportAttr>())
819 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
821 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
824 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
825 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
826 if (!MDS) return nullptr;
828 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
831 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
833 setNonAliasAttributes(D, F);
836 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
837 const CGFunctionInfo &Info,
839 unsigned CallingConv;
840 llvm::AttributeList PAL;
841 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
842 F->setAttributes(PAL);
843 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
846 /// Determines whether the language options require us to model
847 /// unwind exceptions. We treat -fexceptions as mandating this
848 /// except under the fragile ObjC ABI with only ObjC exceptions
849 /// enabled. This means, for example, that C with -fexceptions
851 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
852 // If exceptions are completely disabled, obviously this is false.
853 if (!LangOpts.Exceptions) return false;
855 // If C++ exceptions are enabled, this is true.
856 if (LangOpts.CXXExceptions) return true;
858 // If ObjC exceptions are enabled, this depends on the ABI.
859 if (LangOpts.ObjCExceptions) {
860 return LangOpts.ObjCRuntime.hasUnwindExceptions();
866 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
870 if (CodeGenOpts.UnwindTables)
871 B.addAttribute(llvm::Attribute::UWTable);
873 if (!hasUnwindExceptions(LangOpts))
874 B.addAttribute(llvm::Attribute::NoUnwind);
876 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
877 B.addAttribute(llvm::Attribute::StackProtect);
878 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
879 B.addAttribute(llvm::Attribute::StackProtectStrong);
880 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
881 B.addAttribute(llvm::Attribute::StackProtectReq);
884 // If we don't have a declaration to control inlining, the function isn't
885 // explicitly marked as alwaysinline for semantic reasons, and inlining is
886 // disabled, mark the function as noinline.
887 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
888 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
889 B.addAttribute(llvm::Attribute::NoInline);
892 llvm::AttributeList::FunctionIndex,
893 llvm::AttributeList::get(F->getContext(),
894 llvm::AttributeList::FunctionIndex, B));
898 if (D->hasAttr<OptimizeNoneAttr>()) {
899 B.addAttribute(llvm::Attribute::OptimizeNone);
901 // OptimizeNone implies noinline; we should not be inlining such functions.
902 B.addAttribute(llvm::Attribute::NoInline);
903 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
904 "OptimizeNone and AlwaysInline on same function!");
906 // We still need to handle naked functions even though optnone subsumes
907 // much of their semantics.
908 if (D->hasAttr<NakedAttr>())
909 B.addAttribute(llvm::Attribute::Naked);
911 // OptimizeNone wins over OptimizeForSize and MinSize.
912 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
913 F->removeFnAttr(llvm::Attribute::MinSize);
914 } else if (D->hasAttr<NakedAttr>()) {
915 // Naked implies noinline: we should not be inlining such functions.
916 B.addAttribute(llvm::Attribute::Naked);
917 B.addAttribute(llvm::Attribute::NoInline);
918 } else if (D->hasAttr<NoDuplicateAttr>()) {
919 B.addAttribute(llvm::Attribute::NoDuplicate);
920 } else if (D->hasAttr<NoInlineAttr>()) {
921 B.addAttribute(llvm::Attribute::NoInline);
922 } else if (D->hasAttr<AlwaysInlineAttr>() &&
923 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
924 // (noinline wins over always_inline, and we can't specify both in IR)
925 B.addAttribute(llvm::Attribute::AlwaysInline);
926 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
927 // If we're not inlining, then force everything that isn't always_inline to
928 // carry an explicit noinline attribute.
929 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
930 B.addAttribute(llvm::Attribute::NoInline);
932 // Otherwise, propagate the inline hint attribute and potentially use its
933 // absence to mark things as noinline.
934 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
935 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
936 return Redecl->isInlineSpecified();
938 B.addAttribute(llvm::Attribute::InlineHint);
939 } else if (CodeGenOpts.getInlining() ==
940 CodeGenOptions::OnlyHintInlining &&
942 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
943 B.addAttribute(llvm::Attribute::NoInline);
948 // Add other optimization related attributes if we are optimizing this
950 if (!D->hasAttr<OptimizeNoneAttr>()) {
951 if (D->hasAttr<ColdAttr>()) {
952 B.addAttribute(llvm::Attribute::OptimizeForSize);
953 B.addAttribute(llvm::Attribute::Cold);
956 if (D->hasAttr<MinSizeAttr>())
957 B.addAttribute(llvm::Attribute::MinSize);
960 F->addAttributes(llvm::AttributeList::FunctionIndex,
961 llvm::AttributeList::get(
962 F->getContext(), llvm::AttributeList::FunctionIndex, B));
964 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
966 F->setAlignment(alignment);
968 // Some C++ ABIs require 2-byte alignment for member functions, in order to
969 // reserve a bit for differentiating between virtual and non-virtual member
970 // functions. If the current target's C++ ABI requires this and this is a
971 // member function, set its alignment accordingly.
972 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
973 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
977 // In the cross-dso CFI mode, we want !type attributes on definitions only.
978 if (CodeGenOpts.SanitizeCfiCrossDso)
979 if (auto *FD = dyn_cast<FunctionDecl>(D))
980 CreateFunctionTypeMetadata(FD, F);
983 void CodeGenModule::SetCommonAttributes(const Decl *D,
984 llvm::GlobalValue *GV) {
985 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
986 setGlobalVisibility(GV, ND);
988 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
990 if (D && D->hasAttr<UsedAttr>())
994 void CodeGenModule::setAliasAttributes(const Decl *D,
995 llvm::GlobalValue *GV) {
996 SetCommonAttributes(D, GV);
998 // Process the dllexport attribute based on whether the original definition
999 // (not necessarily the aliasee) was exported.
1000 if (D->hasAttr<DLLExportAttr>())
1001 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1004 void CodeGenModule::setNonAliasAttributes(const Decl *D,
1005 llvm::GlobalObject *GO) {
1006 SetCommonAttributes(D, GO);
1009 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1010 GO->setSection(SA->getName());
1012 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1015 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1017 const CGFunctionInfo &FI) {
1018 SetLLVMFunctionAttributes(D, FI, F);
1019 SetLLVMFunctionAttributesForDefinition(D, F);
1021 F->setLinkage(llvm::Function::InternalLinkage);
1023 setNonAliasAttributes(D, F);
1026 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1027 const NamedDecl *ND) {
1028 // Set linkage and visibility in case we never see a definition.
1029 LinkageInfo LV = ND->getLinkageAndVisibility();
1030 if (LV.getLinkage() != ExternalLinkage) {
1031 // Don't set internal linkage on declarations.
1033 if (ND->hasAttr<DLLImportAttr>()) {
1034 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1035 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1036 } else if (ND->hasAttr<DLLExportAttr>()) {
1037 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1038 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1039 // "extern_weak" is overloaded in LLVM; we probably should have
1040 // separate linkage types for this.
1041 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1044 // Set visibility on a declaration only if it's explicit.
1045 if (LV.isVisibilityExplicit())
1046 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1050 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1051 llvm::Function *F) {
1052 // Only if we are checking indirect calls.
1053 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1056 // Non-static class methods are handled via vtable pointer checks elsewhere.
1057 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1060 // Additionally, if building with cross-DSO support...
1061 if (CodeGenOpts.SanitizeCfiCrossDso) {
1062 // Skip available_externally functions. They won't be codegen'ed in the
1063 // current module anyway.
1064 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1068 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1069 F->addTypeMetadata(0, MD);
1071 // Emit a hash-based bit set entry for cross-DSO calls.
1072 if (CodeGenOpts.SanitizeCfiCrossDso)
1073 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1074 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1077 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1078 bool IsIncompleteFunction,
1080 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1081 // If this is an intrinsic function, set the function's attributes
1082 // to the intrinsic's attributes.
1083 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1087 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1089 if (!IsIncompleteFunction)
1090 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1092 // Add the Returned attribute for "this", except for iOS 5 and earlier
1093 // where substantial code, including the libstdc++ dylib, was compiled with
1094 // GCC and does not actually return "this".
1095 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1096 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1097 assert(!F->arg_empty() &&
1098 F->arg_begin()->getType()
1099 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1100 "unexpected this return");
1101 F->addAttribute(1, llvm::Attribute::Returned);
1104 // Only a few attributes are set on declarations; these may later be
1105 // overridden by a definition.
1107 setLinkageAndVisibilityForGV(F, FD);
1109 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1110 F->setSection(SA->getName());
1112 if (FD->isReplaceableGlobalAllocationFunction()) {
1113 // A replaceable global allocation function does not act like a builtin by
1114 // default, only if it is invoked by a new-expression or delete-expression.
1115 F->addAttribute(llvm::AttributeList::FunctionIndex,
1116 llvm::Attribute::NoBuiltin);
1118 // A sane operator new returns a non-aliasing pointer.
1119 // FIXME: Also add NonNull attribute to the return value
1120 // for the non-nothrow forms?
1121 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1122 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1123 (Kind == OO_New || Kind == OO_Array_New))
1124 F->addAttribute(llvm::AttributeList::ReturnIndex,
1125 llvm::Attribute::NoAlias);
1128 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1129 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1130 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1131 if (MD->isVirtual())
1132 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1134 // Don't emit entries for function declarations in the cross-DSO mode. This
1135 // is handled with better precision by the receiving DSO.
1136 if (!CodeGenOpts.SanitizeCfiCrossDso)
1137 CreateFunctionTypeMetadata(FD, F);
1140 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1141 assert(!GV->isDeclaration() &&
1142 "Only globals with definition can force usage.");
1143 LLVMUsed.emplace_back(GV);
1146 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1147 assert(!GV->isDeclaration() &&
1148 "Only globals with definition can force usage.");
1149 LLVMCompilerUsed.emplace_back(GV);
1152 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1153 std::vector<llvm::WeakVH> &List) {
1154 // Don't create llvm.used if there is no need.
1158 // Convert List to what ConstantArray needs.
1159 SmallVector<llvm::Constant*, 8> UsedArray;
1160 UsedArray.resize(List.size());
1161 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1163 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1164 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1167 if (UsedArray.empty())
1169 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1171 auto *GV = new llvm::GlobalVariable(
1172 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1173 llvm::ConstantArray::get(ATy, UsedArray), Name);
1175 GV->setSection("llvm.metadata");
1178 void CodeGenModule::emitLLVMUsed() {
1179 emitUsed(*this, "llvm.used", LLVMUsed);
1180 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1183 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1184 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1185 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1188 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1189 llvm::SmallString<32> Opt;
1190 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1191 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1192 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1195 void CodeGenModule::AddDependentLib(StringRef Lib) {
1196 llvm::SmallString<24> Opt;
1197 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1198 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1199 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1202 /// \brief Add link options implied by the given module, including modules
1203 /// it depends on, using a postorder walk.
1204 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1205 SmallVectorImpl<llvm::Metadata *> &Metadata,
1206 llvm::SmallPtrSet<Module *, 16> &Visited) {
1207 // Import this module's parent.
1208 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1209 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1212 // Import this module's dependencies.
1213 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1214 if (Visited.insert(Mod->Imports[I - 1]).second)
1215 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1218 // Add linker options to link against the libraries/frameworks
1219 // described by this module.
1220 llvm::LLVMContext &Context = CGM.getLLVMContext();
1221 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1222 // Link against a framework. Frameworks are currently Darwin only, so we
1223 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1224 if (Mod->LinkLibraries[I-1].IsFramework) {
1225 llvm::Metadata *Args[2] = {
1226 llvm::MDString::get(Context, "-framework"),
1227 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1229 Metadata.push_back(llvm::MDNode::get(Context, Args));
1233 // Link against a library.
1234 llvm::SmallString<24> Opt;
1235 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1236 Mod->LinkLibraries[I-1].Library, Opt);
1237 auto *OptString = llvm::MDString::get(Context, Opt);
1238 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1242 void CodeGenModule::EmitModuleLinkOptions() {
1243 // Collect the set of all of the modules we want to visit to emit link
1244 // options, which is essentially the imported modules and all of their
1245 // non-explicit child modules.
1246 llvm::SetVector<clang::Module *> LinkModules;
1247 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1248 SmallVector<clang::Module *, 16> Stack;
1250 // Seed the stack with imported modules.
1251 for (Module *M : ImportedModules) {
1252 // Do not add any link flags when an implementation TU of a module imports
1253 // a header of that same module.
1254 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1255 !getLangOpts().isCompilingModule())
1257 if (Visited.insert(M).second)
1261 // Find all of the modules to import, making a little effort to prune
1262 // non-leaf modules.
1263 while (!Stack.empty()) {
1264 clang::Module *Mod = Stack.pop_back_val();
1266 bool AnyChildren = false;
1268 // Visit the submodules of this module.
1269 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1270 SubEnd = Mod->submodule_end();
1271 Sub != SubEnd; ++Sub) {
1272 // Skip explicit children; they need to be explicitly imported to be
1274 if ((*Sub)->IsExplicit)
1277 if (Visited.insert(*Sub).second) {
1278 Stack.push_back(*Sub);
1283 // We didn't find any children, so add this module to the list of
1284 // modules to link against.
1286 LinkModules.insert(Mod);
1290 // Add link options for all of the imported modules in reverse topological
1291 // order. We don't do anything to try to order import link flags with respect
1292 // to linker options inserted by things like #pragma comment().
1293 SmallVector<llvm::Metadata *, 16> MetadataArgs;
1295 for (Module *M : LinkModules)
1296 if (Visited.insert(M).second)
1297 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1298 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1299 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1301 // Add the linker options metadata flag.
1302 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1303 llvm::MDNode::get(getLLVMContext(),
1304 LinkerOptionsMetadata));
1307 void CodeGenModule::EmitDeferred() {
1308 // Emit code for any potentially referenced deferred decls. Since a
1309 // previously unused static decl may become used during the generation of code
1310 // for a static function, iterate until no changes are made.
1312 if (!DeferredVTables.empty()) {
1313 EmitDeferredVTables();
1315 // Emitting a vtable doesn't directly cause more vtables to
1316 // become deferred, although it can cause functions to be
1317 // emitted that then need those vtables.
1318 assert(DeferredVTables.empty());
1321 // Stop if we're out of both deferred vtables and deferred declarations.
1322 if (DeferredDeclsToEmit.empty())
1325 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1326 // work, it will not interfere with this.
1327 std::vector<DeferredGlobal> CurDeclsToEmit;
1328 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1330 for (DeferredGlobal &G : CurDeclsToEmit) {
1331 GlobalDecl D = G.GD;
1334 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1335 // to get GlobalValue with exactly the type we need, not something that
1336 // might had been created for another decl with the same mangled name but
1338 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1339 GetAddrOfGlobal(D, ForDefinition));
1341 // In case of different address spaces, we may still get a cast, even with
1342 // IsForDefinition equal to true. Query mangled names table to get
1345 GV = GetGlobalValue(getMangledName(D));
1347 // Make sure GetGlobalValue returned non-null.
1350 // Check to see if we've already emitted this. This is necessary
1351 // for a couple of reasons: first, decls can end up in the
1352 // deferred-decls queue multiple times, and second, decls can end
1353 // up with definitions in unusual ways (e.g. by an extern inline
1354 // function acquiring a strong function redefinition). Just
1355 // ignore these cases.
1356 if (!GV->isDeclaration())
1359 // Otherwise, emit the definition and move on to the next one.
1360 EmitGlobalDefinition(D, GV);
1362 // If we found out that we need to emit more decls, do that recursively.
1363 // This has the advantage that the decls are emitted in a DFS and related
1364 // ones are close together, which is convenient for testing.
1365 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1367 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1372 void CodeGenModule::EmitGlobalAnnotations() {
1373 if (Annotations.empty())
1376 // Create a new global variable for the ConstantStruct in the Module.
1377 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1378 Annotations[0]->getType(), Annotations.size()), Annotations);
1379 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1380 llvm::GlobalValue::AppendingLinkage,
1381 Array, "llvm.global.annotations");
1382 gv->setSection(AnnotationSection);
1385 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1386 llvm::Constant *&AStr = AnnotationStrings[Str];
1390 // Not found yet, create a new global.
1391 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1393 new llvm::GlobalVariable(getModule(), s->getType(), true,
1394 llvm::GlobalValue::PrivateLinkage, s, ".str");
1395 gv->setSection(AnnotationSection);
1396 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1401 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1402 SourceManager &SM = getContext().getSourceManager();
1403 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1405 return EmitAnnotationString(PLoc.getFilename());
1406 return EmitAnnotationString(SM.getBufferName(Loc));
1409 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1410 SourceManager &SM = getContext().getSourceManager();
1411 PresumedLoc PLoc = SM.getPresumedLoc(L);
1412 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1413 SM.getExpansionLineNumber(L);
1414 return llvm::ConstantInt::get(Int32Ty, LineNo);
1417 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1418 const AnnotateAttr *AA,
1420 // Get the globals for file name, annotation, and the line number.
1421 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1422 *UnitGV = EmitAnnotationUnit(L),
1423 *LineNoCst = EmitAnnotationLineNo(L);
1425 // Create the ConstantStruct for the global annotation.
1426 llvm::Constant *Fields[4] = {
1427 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1428 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1429 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1432 return llvm::ConstantStruct::getAnon(Fields);
1435 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1436 llvm::GlobalValue *GV) {
1437 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1438 // Get the struct elements for these annotations.
1439 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1440 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1443 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1444 SourceLocation Loc) const {
1445 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1446 // Blacklist by function name.
1447 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1449 // Blacklist by location.
1451 return SanitizerBL.isBlacklistedLocation(Loc);
1452 // If location is unknown, this may be a compiler-generated function. Assume
1453 // it's located in the main file.
1454 auto &SM = Context.getSourceManager();
1455 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1456 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1461 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1462 SourceLocation Loc, QualType Ty,
1463 StringRef Category) const {
1464 // For now globals can be blacklisted only in ASan and KASan.
1465 if (!LangOpts.Sanitize.hasOneOf(
1466 SanitizerKind::Address | SanitizerKind::KernelAddress))
1468 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1469 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1471 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1473 // Check global type.
1475 // Drill down the array types: if global variable of a fixed type is
1476 // blacklisted, we also don't instrument arrays of them.
1477 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1478 Ty = AT->getElementType();
1479 Ty = Ty.getCanonicalType().getUnqualifiedType();
1480 // We allow to blacklist only record types (classes, structs etc.)
1481 if (Ty->isRecordType()) {
1482 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1483 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1490 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1491 StringRef Category) const {
1492 if (!LangOpts.XRayInstrument)
1494 const auto &XRayFilter = getContext().getXRayFilter();
1495 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1496 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1498 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1499 if (Attr == ImbueAttr::NONE)
1500 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1502 case ImbueAttr::NONE:
1504 case ImbueAttr::ALWAYS:
1505 Fn->addFnAttr("function-instrument", "xray-always");
1507 case ImbueAttr::NEVER:
1508 Fn->addFnAttr("function-instrument", "xray-never");
1514 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1515 // Never defer when EmitAllDecls is specified.
1516 if (LangOpts.EmitAllDecls)
1519 return getContext().DeclMustBeEmitted(Global);
1522 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1523 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1524 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1525 // Implicit template instantiations may change linkage if they are later
1526 // explicitly instantiated, so they should not be emitted eagerly.
1528 if (const auto *VD = dyn_cast<VarDecl>(Global))
1529 if (Context.getInlineVariableDefinitionKind(VD) ==
1530 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1531 // A definition of an inline constexpr static data member may change
1532 // linkage later if it's redeclared outside the class.
1534 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1535 // codegen for global variables, because they may be marked as threadprivate.
1536 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1537 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1543 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1544 const CXXUuidofExpr* E) {
1545 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1547 StringRef Uuid = E->getUuidStr();
1548 std::string Name = "_GUID_" + Uuid.lower();
1549 std::replace(Name.begin(), Name.end(), '-', '_');
1551 // The UUID descriptor should be pointer aligned.
1552 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1554 // Look for an existing global.
1555 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1556 return ConstantAddress(GV, Alignment);
1558 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1559 assert(Init && "failed to initialize as constant");
1561 auto *GV = new llvm::GlobalVariable(
1562 getModule(), Init->getType(),
1563 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1564 if (supportsCOMDAT())
1565 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1566 return ConstantAddress(GV, Alignment);
1569 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1570 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1571 assert(AA && "No alias?");
1573 CharUnits Alignment = getContext().getDeclAlign(VD);
1574 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1576 // See if there is already something with the target's name in the module.
1577 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1579 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1580 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1581 return ConstantAddress(Ptr, Alignment);
1584 llvm::Constant *Aliasee;
1585 if (isa<llvm::FunctionType>(DeclTy))
1586 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1587 GlobalDecl(cast<FunctionDecl>(VD)),
1588 /*ForVTable=*/false);
1590 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1591 llvm::PointerType::getUnqual(DeclTy),
1594 auto *F = cast<llvm::GlobalValue>(Aliasee);
1595 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1596 WeakRefReferences.insert(F);
1598 return ConstantAddress(Aliasee, Alignment);
1601 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1602 const auto *Global = cast<ValueDecl>(GD.getDecl());
1604 // Weak references don't produce any output by themselves.
1605 if (Global->hasAttr<WeakRefAttr>())
1608 // If this is an alias definition (which otherwise looks like a declaration)
1610 if (Global->hasAttr<AliasAttr>())
1611 return EmitAliasDefinition(GD);
1613 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1614 if (Global->hasAttr<IFuncAttr>())
1615 return emitIFuncDefinition(GD);
1617 // If this is CUDA, be selective about which declarations we emit.
1618 if (LangOpts.CUDA) {
1619 if (LangOpts.CUDAIsDevice) {
1620 if (!Global->hasAttr<CUDADeviceAttr>() &&
1621 !Global->hasAttr<CUDAGlobalAttr>() &&
1622 !Global->hasAttr<CUDAConstantAttr>() &&
1623 !Global->hasAttr<CUDASharedAttr>())
1626 // We need to emit host-side 'shadows' for all global
1627 // device-side variables because the CUDA runtime needs their
1628 // size and host-side address in order to provide access to
1629 // their device-side incarnations.
1631 // So device-only functions are the only things we skip.
1632 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1633 Global->hasAttr<CUDADeviceAttr>())
1636 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1637 "Expected Variable or Function");
1641 if (LangOpts.OpenMP) {
1642 // If this is OpenMP device, check if it is legal to emit this global
1644 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1646 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1647 if (MustBeEmitted(Global))
1648 EmitOMPDeclareReduction(DRD);
1653 // Ignore declarations, they will be emitted on their first use.
1654 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1655 // Forward declarations are emitted lazily on first use.
1656 if (!FD->doesThisDeclarationHaveABody()) {
1657 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1660 StringRef MangledName = getMangledName(GD);
1662 // Compute the function info and LLVM type.
1663 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1664 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1666 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1667 /*DontDefer=*/false);
1671 const auto *VD = cast<VarDecl>(Global);
1672 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1673 // We need to emit device-side global CUDA variables even if a
1674 // variable does not have a definition -- we still need to define
1675 // host-side shadow for it.
1676 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1677 !VD->hasDefinition() &&
1678 (VD->hasAttr<CUDAConstantAttr>() ||
1679 VD->hasAttr<CUDADeviceAttr>());
1680 if (!MustEmitForCuda &&
1681 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1682 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1683 // If this declaration may have caused an inline variable definition to
1684 // change linkage, make sure that it's emitted.
1685 if (Context.getInlineVariableDefinitionKind(VD) ==
1686 ASTContext::InlineVariableDefinitionKind::Strong)
1687 GetAddrOfGlobalVar(VD);
1692 // Defer code generation to first use when possible, e.g. if this is an inline
1693 // function. If the global must always be emitted, do it eagerly if possible
1694 // to benefit from cache locality.
1695 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1696 // Emit the definition if it can't be deferred.
1697 EmitGlobalDefinition(GD);
1701 // If we're deferring emission of a C++ variable with an
1702 // initializer, remember the order in which it appeared in the file.
1703 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1704 cast<VarDecl>(Global)->hasInit()) {
1705 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1706 CXXGlobalInits.push_back(nullptr);
1709 StringRef MangledName = getMangledName(GD);
1710 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1711 // The value has already been used and should therefore be emitted.
1712 addDeferredDeclToEmit(GV, GD);
1713 } else if (MustBeEmitted(Global)) {
1714 // The value must be emitted, but cannot be emitted eagerly.
1715 assert(!MayBeEmittedEagerly(Global));
1716 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1718 // Otherwise, remember that we saw a deferred decl with this name. The
1719 // first use of the mangled name will cause it to move into
1720 // DeferredDeclsToEmit.
1721 DeferredDecls[MangledName] = GD;
1725 // Check if T is a class type with a destructor that's not dllimport.
1726 static bool HasNonDllImportDtor(QualType T) {
1727 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1728 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1729 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1736 struct FunctionIsDirectlyRecursive :
1737 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1738 const StringRef Name;
1739 const Builtin::Context &BI;
1741 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1742 Name(N), BI(C), Result(false) {
1744 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1746 bool TraverseCallExpr(CallExpr *E) {
1747 const FunctionDecl *FD = E->getDirectCallee();
1750 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1751 if (Attr && Name == Attr->getLabel()) {
1755 unsigned BuiltinID = FD->getBuiltinID();
1756 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1758 StringRef BuiltinName = BI.getName(BuiltinID);
1759 if (BuiltinName.startswith("__builtin_") &&
1760 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1768 // Make sure we're not referencing non-imported vars or functions.
1769 struct DLLImportFunctionVisitor
1770 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1771 bool SafeToInline = true;
1773 bool shouldVisitImplicitCode() const { return true; }
1775 bool VisitVarDecl(VarDecl *VD) {
1776 if (VD->getTLSKind()) {
1777 // A thread-local variable cannot be imported.
1778 SafeToInline = false;
1779 return SafeToInline;
1782 // A variable definition might imply a destructor call.
1783 if (VD->isThisDeclarationADefinition())
1784 SafeToInline = !HasNonDllImportDtor(VD->getType());
1786 return SafeToInline;
1789 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1790 if (const auto *D = E->getTemporary()->getDestructor())
1791 SafeToInline = D->hasAttr<DLLImportAttr>();
1792 return SafeToInline;
1795 bool VisitDeclRefExpr(DeclRefExpr *E) {
1796 ValueDecl *VD = E->getDecl();
1797 if (isa<FunctionDecl>(VD))
1798 SafeToInline = VD->hasAttr<DLLImportAttr>();
1799 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1800 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1801 return SafeToInline;
1804 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1805 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1806 return SafeToInline;
1809 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1810 CXXMethodDecl *M = E->getMethodDecl();
1812 // Call through a pointer to member function. This is safe to inline.
1813 SafeToInline = true;
1815 SafeToInline = M->hasAttr<DLLImportAttr>();
1817 return SafeToInline;
1820 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1821 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1822 return SafeToInline;
1825 bool VisitCXXNewExpr(CXXNewExpr *E) {
1826 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1827 return SafeToInline;
1832 // isTriviallyRecursive - Check if this function calls another
1833 // decl that, because of the asm attribute or the other decl being a builtin,
1834 // ends up pointing to itself.
1836 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1838 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1839 // asm labels are a special kind of mangling we have to support.
1840 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1843 Name = Attr->getLabel();
1845 Name = FD->getName();
1848 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1849 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1850 return Walker.Result;
1853 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1854 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1856 const auto *F = cast<FunctionDecl>(GD.getDecl());
1857 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1860 if (F->hasAttr<DLLImportAttr>()) {
1861 // Check whether it would be safe to inline this dllimport function.
1862 DLLImportFunctionVisitor Visitor;
1863 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1864 if (!Visitor.SafeToInline)
1867 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1868 // Implicit destructor invocations aren't captured in the AST, so the
1869 // check above can't see them. Check for them manually here.
1870 for (const Decl *Member : Dtor->getParent()->decls())
1871 if (isa<FieldDecl>(Member))
1872 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1874 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1875 if (HasNonDllImportDtor(B.getType()))
1880 // PR9614. Avoid cases where the source code is lying to us. An available
1881 // externally function should have an equivalent function somewhere else,
1882 // but a function that calls itself is clearly not equivalent to the real
1884 // This happens in glibc's btowc and in some configure checks.
1885 return !isTriviallyRecursive(F);
1888 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1889 const auto *D = cast<ValueDecl>(GD.getDecl());
1891 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1892 Context.getSourceManager(),
1893 "Generating code for declaration");
1895 if (isa<FunctionDecl>(D)) {
1896 // At -O0, don't generate IR for functions with available_externally
1898 if (!shouldEmitFunction(GD))
1901 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1902 // Make sure to emit the definition(s) before we emit the thunks.
1903 // This is necessary for the generation of certain thunks.
1904 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1905 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1906 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1907 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1909 EmitGlobalFunctionDefinition(GD, GV);
1911 if (Method->isVirtual())
1912 getVTables().EmitThunks(GD);
1917 return EmitGlobalFunctionDefinition(GD, GV);
1920 if (const auto *VD = dyn_cast<VarDecl>(D))
1921 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1923 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1926 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1927 llvm::Function *NewFn);
1929 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1930 /// module, create and return an llvm Function with the specified type. If there
1931 /// is something in the module with the specified name, return it potentially
1932 /// bitcasted to the right type.
1934 /// If D is non-null, it specifies a decl that correspond to this. This is used
1935 /// to set the attributes on the function when it is first created.
1936 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
1937 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
1938 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
1939 ForDefinition_t IsForDefinition) {
1940 const Decl *D = GD.getDecl();
1942 // Lookup the entry, lazily creating it if necessary.
1943 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1945 if (WeakRefReferences.erase(Entry)) {
1946 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1947 if (FD && !FD->hasAttr<WeakAttr>())
1948 Entry->setLinkage(llvm::Function::ExternalLinkage);
1951 // Handle dropped DLL attributes.
1952 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1953 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1955 // If there are two attempts to define the same mangled name, issue an
1957 if (IsForDefinition && !Entry->isDeclaration()) {
1959 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1960 // to make sure that we issue an error only once.
1961 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1962 (GD.getCanonicalDecl().getDecl() !=
1963 OtherGD.getCanonicalDecl().getDecl()) &&
1964 DiagnosedConflictingDefinitions.insert(GD).second) {
1965 getDiags().Report(D->getLocation(),
1966 diag::err_duplicate_mangled_name);
1967 getDiags().Report(OtherGD.getDecl()->getLocation(),
1968 diag::note_previous_definition);
1972 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1973 (Entry->getType()->getElementType() == Ty)) {
1977 // Make sure the result is of the correct type.
1978 // (If function is requested for a definition, we always need to create a new
1979 // function, not just return a bitcast.)
1980 if (!IsForDefinition)
1981 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1984 // This function doesn't have a complete type (for example, the return
1985 // type is an incomplete struct). Use a fake type instead, and make
1986 // sure not to try to set attributes.
1987 bool IsIncompleteFunction = false;
1989 llvm::FunctionType *FTy;
1990 if (isa<llvm::FunctionType>(Ty)) {
1991 FTy = cast<llvm::FunctionType>(Ty);
1993 FTy = llvm::FunctionType::get(VoidTy, false);
1994 IsIncompleteFunction = true;
1998 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1999 Entry ? StringRef() : MangledName, &getModule());
2001 // If we already created a function with the same mangled name (but different
2002 // type) before, take its name and add it to the list of functions to be
2003 // replaced with F at the end of CodeGen.
2005 // This happens if there is a prototype for a function (e.g. "int f()") and
2006 // then a definition of a different type (e.g. "int f(int x)").
2010 // This might be an implementation of a function without a prototype, in
2011 // which case, try to do special replacement of calls which match the new
2012 // prototype. The really key thing here is that we also potentially drop
2013 // arguments from the call site so as to make a direct call, which makes the
2014 // inliner happier and suppresses a number of optimizer warnings (!) about
2015 // dropping arguments.
2016 if (!Entry->use_empty()) {
2017 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2018 Entry->removeDeadConstantUsers();
2021 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2022 F, Entry->getType()->getElementType()->getPointerTo());
2023 addGlobalValReplacement(Entry, BC);
2026 assert(F->getName() == MangledName && "name was uniqued!");
2028 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2029 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2030 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2031 F->addAttributes(llvm::AttributeList::FunctionIndex,
2032 llvm::AttributeList::get(
2033 VMContext, llvm::AttributeList::FunctionIndex, B));
2037 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2038 // each other bottoming out with the base dtor. Therefore we emit non-base
2039 // dtors on usage, even if there is no dtor definition in the TU.
2040 if (D && isa<CXXDestructorDecl>(D) &&
2041 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2043 addDeferredDeclToEmit(F, GD);
2045 // This is the first use or definition of a mangled name. If there is a
2046 // deferred decl with this name, remember that we need to emit it at the end
2048 auto DDI = DeferredDecls.find(MangledName);
2049 if (DDI != DeferredDecls.end()) {
2050 // Move the potentially referenced deferred decl to the
2051 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2052 // don't need it anymore).
2053 addDeferredDeclToEmit(F, DDI->second);
2054 DeferredDecls.erase(DDI);
2056 // Otherwise, there are cases we have to worry about where we're
2057 // using a declaration for which we must emit a definition but where
2058 // we might not find a top-level definition:
2059 // - member functions defined inline in their classes
2060 // - friend functions defined inline in some class
2061 // - special member functions with implicit definitions
2062 // If we ever change our AST traversal to walk into class methods,
2063 // this will be unnecessary.
2065 // We also don't emit a definition for a function if it's going to be an
2066 // entry in a vtable, unless it's already marked as used.
2067 } else if (getLangOpts().CPlusPlus && D) {
2068 // Look for a declaration that's lexically in a record.
2069 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2070 FD = FD->getPreviousDecl()) {
2071 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2072 if (FD->doesThisDeclarationHaveABody()) {
2073 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
2081 // Make sure the result is of the requested type.
2082 if (!IsIncompleteFunction) {
2083 assert(F->getType()->getElementType() == Ty);
2087 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2088 return llvm::ConstantExpr::getBitCast(F, PTy);
2091 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2092 /// non-null, then this function will use the specified type if it has to
2093 /// create it (this occurs when we see a definition of the function).
2094 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2098 ForDefinition_t IsForDefinition) {
2099 // If there was no specific requested type, just convert it now.
2101 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2102 auto CanonTy = Context.getCanonicalType(FD->getType());
2103 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2106 StringRef MangledName = getMangledName(GD);
2107 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2108 /*IsThunk=*/false, llvm::AttributeList(),
2112 static const FunctionDecl *
2113 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2114 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2115 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2117 IdentifierInfo &CII = C.Idents.get(Name);
2118 for (const auto &Result : DC->lookup(&CII))
2119 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2122 if (!C.getLangOpts().CPlusPlus)
2125 // Demangle the premangled name from getTerminateFn()
2126 IdentifierInfo &CXXII =
2127 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2128 ? C.Idents.get("terminate")
2129 : C.Idents.get(Name);
2131 for (const auto &N : {"__cxxabiv1", "std"}) {
2132 IdentifierInfo &NS = C.Idents.get(N);
2133 for (const auto &Result : DC->lookup(&NS)) {
2134 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2135 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2136 for (const auto &Result : LSD->lookup(&NS))
2137 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2141 for (const auto &Result : ND->lookup(&CXXII))
2142 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2150 /// CreateRuntimeFunction - Create a new runtime function with the specified
2153 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2154 llvm::AttributeList ExtraAttrs,
2157 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2158 /*DontDefer=*/false, /*IsThunk=*/false,
2161 if (auto *F = dyn_cast<llvm::Function>(C)) {
2163 F->setCallingConv(getRuntimeCC());
2165 if (!Local && getTriple().isOSBinFormatCOFF() &&
2166 !getCodeGenOpts().LTOVisibilityPublicStd) {
2167 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2168 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2169 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2170 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2179 /// CreateBuiltinFunction - Create a new builtin function with the specified
2182 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2183 llvm::AttributeList ExtraAttrs) {
2185 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2186 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2187 if (auto *F = dyn_cast<llvm::Function>(C))
2189 F->setCallingConv(getBuiltinCC());
2193 /// isTypeConstant - Determine whether an object of this type can be emitted
2196 /// If ExcludeCtor is true, the duration when the object's constructor runs
2197 /// will not be considered. The caller will need to verify that the object is
2198 /// not written to during its construction.
2199 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2200 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2203 if (Context.getLangOpts().CPlusPlus) {
2204 if (const CXXRecordDecl *Record
2205 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2206 return ExcludeCtor && !Record->hasMutableFields() &&
2207 Record->hasTrivialDestructor();
2213 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2214 /// create and return an llvm GlobalVariable with the specified type. If there
2215 /// is something in the module with the specified name, return it potentially
2216 /// bitcasted to the right type.
2218 /// If D is non-null, it specifies a decl that correspond to this. This is used
2219 /// to set the attributes on the global when it is first created.
2221 /// If IsForDefinition is true, it is guranteed that an actual global with
2222 /// type Ty will be returned, not conversion of a variable with the same
2223 /// mangled name but some other type.
2225 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2226 llvm::PointerType *Ty,
2228 ForDefinition_t IsForDefinition) {
2229 // Lookup the entry, lazily creating it if necessary.
2230 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2232 if (WeakRefReferences.erase(Entry)) {
2233 if (D && !D->hasAttr<WeakAttr>())
2234 Entry->setLinkage(llvm::Function::ExternalLinkage);
2237 // Handle dropped DLL attributes.
2238 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2239 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2241 if (Entry->getType() == Ty)
2244 // If there are two attempts to define the same mangled name, issue an
2246 if (IsForDefinition && !Entry->isDeclaration()) {
2248 const VarDecl *OtherD;
2250 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2251 // to make sure that we issue an error only once.
2252 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2253 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2254 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2255 OtherD->hasInit() &&
2256 DiagnosedConflictingDefinitions.insert(D).second) {
2257 getDiags().Report(D->getLocation(),
2258 diag::err_duplicate_mangled_name);
2259 getDiags().Report(OtherGD.getDecl()->getLocation(),
2260 diag::note_previous_definition);
2264 // Make sure the result is of the correct type.
2265 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2266 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2268 // (If global is requested for a definition, we always need to create a new
2269 // global, not just return a bitcast.)
2270 if (!IsForDefinition)
2271 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2274 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2275 auto *GV = new llvm::GlobalVariable(
2276 getModule(), Ty->getElementType(), false,
2277 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2278 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2280 // If we already created a global with the same mangled name (but different
2281 // type) before, take its name and remove it from its parent.
2283 GV->takeName(Entry);
2285 if (!Entry->use_empty()) {
2286 llvm::Constant *NewPtrForOldDecl =
2287 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2288 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2291 Entry->eraseFromParent();
2294 // This is the first use or definition of a mangled name. If there is a
2295 // deferred decl with this name, remember that we need to emit it at the end
2297 auto DDI = DeferredDecls.find(MangledName);
2298 if (DDI != DeferredDecls.end()) {
2299 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2300 // list, and remove it from DeferredDecls (since we don't need it anymore).
2301 addDeferredDeclToEmit(GV, DDI->second);
2302 DeferredDecls.erase(DDI);
2305 // Handle things which are present even on external declarations.
2307 // FIXME: This code is overly simple and should be merged with other global
2309 GV->setConstant(isTypeConstant(D->getType(), false));
2311 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2313 setLinkageAndVisibilityForGV(GV, D);
2315 if (D->getTLSKind()) {
2316 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2317 CXXThreadLocals.push_back(D);
2321 // If required by the ABI, treat declarations of static data members with
2322 // inline initializers as definitions.
2323 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2324 EmitGlobalVarDefinition(D);
2327 // Handle XCore specific ABI requirements.
2328 if (getTriple().getArch() == llvm::Triple::xcore &&
2329 D->getLanguageLinkage() == CLanguageLinkage &&
2330 D->getType().isConstant(Context) &&
2331 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2332 GV->setSection(".cp.rodata");
2335 if (AddrSpace != Ty->getAddressSpace())
2336 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2342 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2343 ForDefinition_t IsForDefinition) {
2344 const Decl *D = GD.getDecl();
2345 if (isa<CXXConstructorDecl>(D))
2346 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2347 getFromCtorType(GD.getCtorType()),
2348 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2349 /*DontDefer=*/false, IsForDefinition);
2350 else if (isa<CXXDestructorDecl>(D))
2351 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2352 getFromDtorType(GD.getDtorType()),
2353 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2354 /*DontDefer=*/false, IsForDefinition);
2355 else if (isa<CXXMethodDecl>(D)) {
2356 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2357 cast<CXXMethodDecl>(D));
2358 auto Ty = getTypes().GetFunctionType(*FInfo);
2359 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2361 } else if (isa<FunctionDecl>(D)) {
2362 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2363 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2364 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2367 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2371 llvm::GlobalVariable *
2372 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2374 llvm::GlobalValue::LinkageTypes Linkage) {
2375 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2376 llvm::GlobalVariable *OldGV = nullptr;
2379 // Check if the variable has the right type.
2380 if (GV->getType()->getElementType() == Ty)
2383 // Because C++ name mangling, the only way we can end up with an already
2384 // existing global with the same name is if it has been declared extern "C".
2385 assert(GV->isDeclaration() && "Declaration has wrong type!");
2389 // Create a new variable.
2390 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2391 Linkage, nullptr, Name);
2394 // Replace occurrences of the old variable if needed.
2395 GV->takeName(OldGV);
2397 if (!OldGV->use_empty()) {
2398 llvm::Constant *NewPtrForOldDecl =
2399 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2400 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2403 OldGV->eraseFromParent();
2406 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2407 !GV->hasAvailableExternallyLinkage())
2408 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2413 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2414 /// given global variable. If Ty is non-null and if the global doesn't exist,
2415 /// then it will be created with the specified type instead of whatever the
2416 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2417 /// that an actual global with type Ty will be returned, not conversion of a
2418 /// variable with the same mangled name but some other type.
2419 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2421 ForDefinition_t IsForDefinition) {
2422 assert(D->hasGlobalStorage() && "Not a global variable");
2423 QualType ASTTy = D->getType();
2425 Ty = getTypes().ConvertTypeForMem(ASTTy);
2427 llvm::PointerType *PTy =
2428 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2430 StringRef MangledName = getMangledName(D);
2431 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2434 /// CreateRuntimeVariable - Create a new runtime global variable with the
2435 /// specified type and name.
2437 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2439 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2442 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2443 assert(!D->getInit() && "Cannot emit definite definitions here!");
2445 StringRef MangledName = getMangledName(D);
2446 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2448 // We already have a definition, not declaration, with the same mangled name.
2449 // Emitting of declaration is not required (and actually overwrites emitted
2451 if (GV && !GV->isDeclaration())
2454 // If we have not seen a reference to this variable yet, place it into the
2455 // deferred declarations table to be emitted if needed later.
2456 if (!MustBeEmitted(D) && !GV) {
2457 DeferredDecls[MangledName] = D;
2461 // The tentative definition is the only definition.
2462 EmitGlobalVarDefinition(D);
2465 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2466 return Context.toCharUnitsFromBits(
2467 getDataLayout().getTypeStoreSizeInBits(Ty));
2470 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2471 unsigned AddrSpace) {
2472 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2473 if (D->hasAttr<CUDAConstantAttr>())
2474 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2475 else if (D->hasAttr<CUDASharedAttr>())
2476 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2478 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2484 template<typename SomeDecl>
2485 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2486 llvm::GlobalValue *GV) {
2487 if (!getLangOpts().CPlusPlus)
2490 // Must have 'used' attribute, or else inline assembly can't rely on
2491 // the name existing.
2492 if (!D->template hasAttr<UsedAttr>())
2495 // Must have internal linkage and an ordinary name.
2496 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2499 // Must be in an extern "C" context. Entities declared directly within
2500 // a record are not extern "C" even if the record is in such a context.
2501 const SomeDecl *First = D->getFirstDecl();
2502 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2505 // OK, this is an internal linkage entity inside an extern "C" linkage
2506 // specification. Make a note of that so we can give it the "expected"
2507 // mangled name if nothing else is using that name.
2508 std::pair<StaticExternCMap::iterator, bool> R =
2509 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2511 // If we have multiple internal linkage entities with the same name
2512 // in extern "C" regions, none of them gets that name.
2514 R.first->second = nullptr;
2517 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2518 if (!CGM.supportsCOMDAT())
2521 if (D.hasAttr<SelectAnyAttr>())
2525 if (auto *VD = dyn_cast<VarDecl>(&D))
2526 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2528 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2532 case GVA_AvailableExternally:
2533 case GVA_StrongExternal:
2535 case GVA_DiscardableODR:
2539 llvm_unreachable("No such linkage");
2542 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2543 llvm::GlobalObject &GO) {
2544 if (!shouldBeInCOMDAT(*this, D))
2546 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2549 /// Pass IsTentative as true if you want to create a tentative definition.
2550 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2552 // OpenCL global variables of sampler type are translated to function calls,
2553 // therefore no need to be translated.
2554 QualType ASTTy = D->getType();
2555 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2558 llvm::Constant *Init = nullptr;
2559 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2560 bool NeedsGlobalCtor = false;
2561 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2563 const VarDecl *InitDecl;
2564 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2566 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2567 // as part of their declaration." Sema has already checked for
2568 // error cases, so we just need to set Init to UndefValue.
2569 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2570 D->hasAttr<CUDASharedAttr>())
2571 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2572 else if (!InitExpr) {
2573 // This is a tentative definition; tentative definitions are
2574 // implicitly initialized with { 0 }.
2576 // Note that tentative definitions are only emitted at the end of
2577 // a translation unit, so they should never have incomplete
2578 // type. In addition, EmitTentativeDefinition makes sure that we
2579 // never attempt to emit a tentative definition if a real one
2580 // exists. A use may still exists, however, so we still may need
2582 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2583 Init = EmitNullConstant(D->getType());
2585 initializedGlobalDecl = GlobalDecl(D);
2586 Init = EmitConstantInit(*InitDecl);
2589 QualType T = InitExpr->getType();
2590 if (D->getType()->isReferenceType())
2593 if (getLangOpts().CPlusPlus) {
2594 Init = EmitNullConstant(T);
2595 NeedsGlobalCtor = true;
2597 ErrorUnsupported(D, "static initializer");
2598 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2601 // We don't need an initializer, so remove the entry for the delayed
2602 // initializer position (just in case this entry was delayed) if we
2603 // also don't need to register a destructor.
2604 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2605 DelayedCXXInitPosition.erase(D);
2609 llvm::Type* InitType = Init->getType();
2610 llvm::Constant *Entry =
2611 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2613 // Strip off a bitcast if we got one back.
2614 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2615 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2616 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2617 // All zero index gep.
2618 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2619 Entry = CE->getOperand(0);
2622 // Entry is now either a Function or GlobalVariable.
2623 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2625 // We have a definition after a declaration with the wrong type.
2626 // We must make a new GlobalVariable* and update everything that used OldGV
2627 // (a declaration or tentative definition) with the new GlobalVariable*
2628 // (which will be a definition).
2630 // This happens if there is a prototype for a global (e.g.
2631 // "extern int x[];") and then a definition of a different type (e.g.
2632 // "int x[10];"). This also happens when an initializer has a different type
2633 // from the type of the global (this happens with unions).
2635 GV->getType()->getElementType() != InitType ||
2636 GV->getType()->getAddressSpace() !=
2637 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2639 // Move the old entry aside so that we'll create a new one.
2640 Entry->setName(StringRef());
2642 // Make a new global with the correct type, this is now guaranteed to work.
2643 GV = cast<llvm::GlobalVariable>(
2644 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2646 // Replace all uses of the old global with the new global
2647 llvm::Constant *NewPtrForOldDecl =
2648 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2649 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2651 // Erase the old global, since it is no longer used.
2652 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2655 MaybeHandleStaticInExternC(D, GV);
2657 if (D->hasAttr<AnnotateAttr>())
2658 AddGlobalAnnotations(D, GV);
2660 // Set the llvm linkage type as appropriate.
2661 llvm::GlobalValue::LinkageTypes Linkage =
2662 getLLVMLinkageVarDefinition(D, GV->isConstant());
2664 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2665 // the device. [...]"
2666 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2667 // __device__, declares a variable that: [...]
2668 // Is accessible from all the threads within the grid and from the host
2669 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2670 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2671 if (GV && LangOpts.CUDA) {
2672 if (LangOpts.CUDAIsDevice) {
2673 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2674 GV->setExternallyInitialized(true);
2676 // Host-side shadows of external declarations of device-side
2677 // global variables become internal definitions. These have to
2678 // be internal in order to prevent name conflicts with global
2679 // host variables with the same name in a different TUs.
2680 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2681 Linkage = llvm::GlobalValue::InternalLinkage;
2683 // Shadow variables and their properties must be registered
2684 // with CUDA runtime.
2686 if (!D->hasDefinition())
2687 Flags |= CGCUDARuntime::ExternDeviceVar;
2688 if (D->hasAttr<CUDAConstantAttr>())
2689 Flags |= CGCUDARuntime::ConstantDeviceVar;
2690 getCUDARuntime().registerDeviceVar(*GV, Flags);
2691 } else if (D->hasAttr<CUDASharedAttr>())
2692 // __shared__ variables are odd. Shadows do get created, but
2693 // they are not registered with the CUDA runtime, so they
2694 // can't really be used to access their device-side
2695 // counterparts. It's not clear yet whether it's nvcc's bug or
2696 // a feature, but we've got to do the same for compatibility.
2697 Linkage = llvm::GlobalValue::InternalLinkage;
2700 GV->setInitializer(Init);
2702 // If it is safe to mark the global 'constant', do so now.
2703 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2704 isTypeConstant(D->getType(), true));
2706 // If it is in a read-only section, mark it 'constant'.
2707 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2708 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2709 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2710 GV->setConstant(true);
2713 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2716 // On Darwin, if the normal linkage of a C++ thread_local variable is
2717 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2718 // copies within a linkage unit; otherwise, the backing variable has
2719 // internal linkage and all accesses should just be calls to the
2720 // Itanium-specified entry point, which has the normal linkage of the
2721 // variable. This is to preserve the ability to change the implementation
2722 // behind the scenes.
2723 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2724 Context.getTargetInfo().getTriple().isOSDarwin() &&
2725 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2726 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2727 Linkage = llvm::GlobalValue::InternalLinkage;
2729 GV->setLinkage(Linkage);
2730 if (D->hasAttr<DLLImportAttr>())
2731 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2732 else if (D->hasAttr<DLLExportAttr>())
2733 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2735 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2737 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2738 // common vars aren't constant even if declared const.
2739 GV->setConstant(false);
2740 // Tentative definition of global variables may be initialized with
2741 // non-zero null pointers. In this case they should have weak linkage
2742 // since common linkage must have zero initializer and must not have
2743 // explicit section therefore cannot have non-zero initial value.
2744 if (!GV->getInitializer()->isNullValue())
2745 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2748 setNonAliasAttributes(D, GV);
2750 if (D->getTLSKind() && !GV->isThreadLocal()) {
2751 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2752 CXXThreadLocals.push_back(D);
2756 maybeSetTrivialComdat(*D, *GV);
2758 // Emit the initializer function if necessary.
2759 if (NeedsGlobalCtor || NeedsGlobalDtor)
2760 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2762 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2764 // Emit global variable debug information.
2765 if (CGDebugInfo *DI = getModuleDebugInfo())
2766 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2767 DI->EmitGlobalVariable(GV, D);
2770 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2771 CodeGenModule &CGM, const VarDecl *D,
2773 // Don't give variables common linkage if -fno-common was specified unless it
2774 // was overridden by a NoCommon attribute.
2775 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2779 // A declaration of an identifier for an object that has file scope without
2780 // an initializer, and without a storage-class specifier or with the
2781 // storage-class specifier static, constitutes a tentative definition.
2782 if (D->getInit() || D->hasExternalStorage())
2785 // A variable cannot be both common and exist in a section.
2786 if (D->hasAttr<SectionAttr>())
2789 // Thread local vars aren't considered common linkage.
2790 if (D->getTLSKind())
2793 // Tentative definitions marked with WeakImportAttr are true definitions.
2794 if (D->hasAttr<WeakImportAttr>())
2797 // A variable cannot be both common and exist in a comdat.
2798 if (shouldBeInCOMDAT(CGM, *D))
2801 // Declarations with a required alignment do not have common linkage in MSVC
2803 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2804 if (D->hasAttr<AlignedAttr>())
2806 QualType VarType = D->getType();
2807 if (Context.isAlignmentRequired(VarType))
2810 if (const auto *RT = VarType->getAs<RecordType>()) {
2811 const RecordDecl *RD = RT->getDecl();
2812 for (const FieldDecl *FD : RD->fields()) {
2813 if (FD->isBitField())
2815 if (FD->hasAttr<AlignedAttr>())
2817 if (Context.isAlignmentRequired(FD->getType()))
2826 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2827 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2828 if (Linkage == GVA_Internal)
2829 return llvm::Function::InternalLinkage;
2831 if (D->hasAttr<WeakAttr>()) {
2832 if (IsConstantVariable)
2833 return llvm::GlobalVariable::WeakODRLinkage;
2835 return llvm::GlobalVariable::WeakAnyLinkage;
2838 // We are guaranteed to have a strong definition somewhere else,
2839 // so we can use available_externally linkage.
2840 if (Linkage == GVA_AvailableExternally)
2841 return llvm::GlobalValue::AvailableExternallyLinkage;
2843 // Note that Apple's kernel linker doesn't support symbol
2844 // coalescing, so we need to avoid linkonce and weak linkages there.
2845 // Normally, this means we just map to internal, but for explicit
2846 // instantiations we'll map to external.
2848 // In C++, the compiler has to emit a definition in every translation unit
2849 // that references the function. We should use linkonce_odr because
2850 // a) if all references in this translation unit are optimized away, we
2851 // don't need to codegen it. b) if the function persists, it needs to be
2852 // merged with other definitions. c) C++ has the ODR, so we know the
2853 // definition is dependable.
2854 if (Linkage == GVA_DiscardableODR)
2855 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2856 : llvm::Function::InternalLinkage;
2858 // An explicit instantiation of a template has weak linkage, since
2859 // explicit instantiations can occur in multiple translation units
2860 // and must all be equivalent. However, we are not allowed to
2861 // throw away these explicit instantiations.
2863 // We don't currently support CUDA device code spread out across multiple TUs,
2864 // so say that CUDA templates are either external (for kernels) or internal.
2865 // This lets llvm perform aggressive inter-procedural optimizations.
2866 if (Linkage == GVA_StrongODR) {
2867 if (Context.getLangOpts().AppleKext)
2868 return llvm::Function::ExternalLinkage;
2869 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2870 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2871 : llvm::Function::InternalLinkage;
2872 return llvm::Function::WeakODRLinkage;
2875 // C++ doesn't have tentative definitions and thus cannot have common
2877 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2878 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2879 CodeGenOpts.NoCommon))
2880 return llvm::GlobalVariable::CommonLinkage;
2882 // selectany symbols are externally visible, so use weak instead of
2883 // linkonce. MSVC optimizes away references to const selectany globals, so
2884 // all definitions should be the same and ODR linkage should be used.
2885 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2886 if (D->hasAttr<SelectAnyAttr>())
2887 return llvm::GlobalVariable::WeakODRLinkage;
2889 // Otherwise, we have strong external linkage.
2890 assert(Linkage == GVA_StrongExternal);
2891 return llvm::GlobalVariable::ExternalLinkage;
2894 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2895 const VarDecl *VD, bool IsConstant) {
2896 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2897 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2900 /// Replace the uses of a function that was declared with a non-proto type.
2901 /// We want to silently drop extra arguments from call sites
2902 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2903 llvm::Function *newFn) {
2905 if (old->use_empty()) return;
2907 llvm::Type *newRetTy = newFn->getReturnType();
2908 SmallVector<llvm::Value*, 4> newArgs;
2909 SmallVector<llvm::OperandBundleDef, 1> newBundles;
2911 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2913 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2914 llvm::User *user = use->getUser();
2916 // Recognize and replace uses of bitcasts. Most calls to
2917 // unprototyped functions will use bitcasts.
2918 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2919 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2920 replaceUsesOfNonProtoConstant(bitcast, newFn);
2924 // Recognize calls to the function.
2925 llvm::CallSite callSite(user);
2926 if (!callSite) continue;
2927 if (!callSite.isCallee(&*use)) continue;
2929 // If the return types don't match exactly, then we can't
2930 // transform this call unless it's dead.
2931 if (callSite->getType() != newRetTy && !callSite->use_empty())
2934 // Get the call site's attribute list.
2935 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
2936 llvm::AttributeList oldAttrs = callSite.getAttributes();
2938 // If the function was passed too few arguments, don't transform.
2939 unsigned newNumArgs = newFn->arg_size();
2940 if (callSite.arg_size() < newNumArgs) continue;
2942 // If extra arguments were passed, we silently drop them.
2943 // If any of the types mismatch, we don't transform.
2945 bool dontTransform = false;
2946 for (llvm::Argument &A : newFn->args()) {
2947 if (callSite.getArgument(argNo)->getType() != A.getType()) {
2948 dontTransform = true;
2952 // Add any parameter attributes.
2953 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
2959 // Okay, we can transform this. Create the new call instruction and copy
2960 // over the required information.
2961 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2963 // Copy over any operand bundles.
2964 callSite.getOperandBundlesAsDefs(newBundles);
2966 llvm::CallSite newCall;
2967 if (callSite.isCall()) {
2968 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2969 callSite.getInstruction());
2971 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2972 newCall = llvm::InvokeInst::Create(newFn,
2973 oldInvoke->getNormalDest(),
2974 oldInvoke->getUnwindDest(),
2975 newArgs, newBundles, "",
2976 callSite.getInstruction());
2978 newArgs.clear(); // for the next iteration
2980 if (!newCall->getType()->isVoidTy())
2981 newCall->takeName(callSite.getInstruction());
2982 newCall.setAttributes(llvm::AttributeList::get(
2983 newFn->getContext(), oldAttrs.getFnAttributes(),
2984 oldAttrs.getRetAttributes(), newArgAttrs));
2985 newCall.setCallingConv(callSite.getCallingConv());
2987 // Finally, remove the old call, replacing any uses with the new one.
2988 if (!callSite->use_empty())
2989 callSite->replaceAllUsesWith(newCall.getInstruction());
2991 // Copy debug location attached to CI.
2992 if (callSite->getDebugLoc())
2993 newCall->setDebugLoc(callSite->getDebugLoc());
2995 callSite->eraseFromParent();
2999 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3000 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3001 /// existing call uses of the old function in the module, this adjusts them to
3002 /// call the new function directly.
3004 /// This is not just a cleanup: the always_inline pass requires direct calls to
3005 /// functions to be able to inline them. If there is a bitcast in the way, it
3006 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3008 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3009 llvm::Function *NewFn) {
3010 // If we're redefining a global as a function, don't transform it.
3011 if (!isa<llvm::Function>(Old)) return;
3013 replaceUsesOfNonProtoConstant(Old, NewFn);
3016 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3017 auto DK = VD->isThisDeclarationADefinition();
3018 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3021 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3022 // If we have a definition, this might be a deferred decl. If the
3023 // instantiation is explicit, make sure we emit it at the end.
3024 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3025 GetAddrOfGlobalVar(VD);
3027 EmitTopLevelDecl(VD);
3030 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3031 llvm::GlobalValue *GV) {
3032 const auto *D = cast<FunctionDecl>(GD.getDecl());
3034 // Compute the function info and LLVM type.
3035 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3036 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3038 // Get or create the prototype for the function.
3039 if (!GV || (GV->getType()->getElementType() != Ty))
3040 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3045 if (!GV->isDeclaration())
3048 // We need to set linkage and visibility on the function before
3049 // generating code for it because various parts of IR generation
3050 // want to propagate this information down (e.g. to local static
3052 auto *Fn = cast<llvm::Function>(GV);
3053 setFunctionLinkage(GD, Fn);
3054 setFunctionDLLStorageClass(GD, Fn);
3056 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3057 setGlobalVisibility(Fn, D);
3059 MaybeHandleStaticInExternC(D, Fn);
3061 maybeSetTrivialComdat(*D, *Fn);
3063 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3065 setFunctionDefinitionAttributes(D, Fn);
3066 SetLLVMFunctionAttributesForDefinition(D, Fn);
3068 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3069 AddGlobalCtor(Fn, CA->getPriority());
3070 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3071 AddGlobalDtor(Fn, DA->getPriority());
3072 if (D->hasAttr<AnnotateAttr>())
3073 AddGlobalAnnotations(D, Fn);
3076 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3077 const auto *D = cast<ValueDecl>(GD.getDecl());
3078 const AliasAttr *AA = D->getAttr<AliasAttr>();
3079 assert(AA && "Not an alias?");
3081 StringRef MangledName = getMangledName(GD);
3083 if (AA->getAliasee() == MangledName) {
3084 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3088 // If there is a definition in the module, then it wins over the alias.
3089 // This is dubious, but allow it to be safe. Just ignore the alias.
3090 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3091 if (Entry && !Entry->isDeclaration())
3094 Aliases.push_back(GD);
3096 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3098 // Create a reference to the named value. This ensures that it is emitted
3099 // if a deferred decl.
3100 llvm::Constant *Aliasee;
3101 if (isa<llvm::FunctionType>(DeclTy))
3102 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3103 /*ForVTable=*/false);
3105 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3106 llvm::PointerType::getUnqual(DeclTy),
3109 // Create the new alias itself, but don't set a name yet.
3110 auto *GA = llvm::GlobalAlias::create(
3111 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3114 if (GA->getAliasee() == Entry) {
3115 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3119 assert(Entry->isDeclaration());
3121 // If there is a declaration in the module, then we had an extern followed
3122 // by the alias, as in:
3123 // extern int test6();
3125 // int test6() __attribute__((alias("test7")));
3127 // Remove it and replace uses of it with the alias.
3128 GA->takeName(Entry);
3130 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3132 Entry->eraseFromParent();
3134 GA->setName(MangledName);
3137 // Set attributes which are particular to an alias; this is a
3138 // specialization of the attributes which may be set on a global
3139 // variable/function.
3140 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3141 D->isWeakImported()) {
3142 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3145 if (const auto *VD = dyn_cast<VarDecl>(D))
3146 if (VD->getTLSKind())
3147 setTLSMode(GA, *VD);
3149 setAliasAttributes(D, GA);
3152 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3153 const auto *D = cast<ValueDecl>(GD.getDecl());
3154 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3155 assert(IFA && "Not an ifunc?");
3157 StringRef MangledName = getMangledName(GD);
3159 if (IFA->getResolver() == MangledName) {
3160 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3164 // Report an error if some definition overrides ifunc.
3165 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3166 if (Entry && !Entry->isDeclaration()) {
3168 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3169 DiagnosedConflictingDefinitions.insert(GD).second) {
3170 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3171 Diags.Report(OtherGD.getDecl()->getLocation(),
3172 diag::note_previous_definition);
3177 Aliases.push_back(GD);
3179 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3180 llvm::Constant *Resolver =
3181 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3182 /*ForVTable=*/false);
3183 llvm::GlobalIFunc *GIF =
3184 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3185 "", Resolver, &getModule());
3187 if (GIF->getResolver() == Entry) {
3188 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3191 assert(Entry->isDeclaration());
3193 // If there is a declaration in the module, then we had an extern followed
3194 // by the ifunc, as in:
3195 // extern int test();
3197 // int test() __attribute__((ifunc("resolver")));
3199 // Remove it and replace uses of it with the ifunc.
3200 GIF->takeName(Entry);
3202 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3204 Entry->eraseFromParent();
3206 GIF->setName(MangledName);
3208 SetCommonAttributes(D, GIF);
3211 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3212 ArrayRef<llvm::Type*> Tys) {
3213 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3217 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3218 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3219 const StringLiteral *Literal, bool TargetIsLSB,
3220 bool &IsUTF16, unsigned &StringLength) {
3221 StringRef String = Literal->getString();
3222 unsigned NumBytes = String.size();
3224 // Check for simple case.
3225 if (!Literal->containsNonAsciiOrNull()) {
3226 StringLength = NumBytes;
3227 return *Map.insert(std::make_pair(String, nullptr)).first;
3230 // Otherwise, convert the UTF8 literals into a string of shorts.
3233 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3234 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3235 llvm::UTF16 *ToPtr = &ToBuf[0];
3237 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3238 ToPtr + NumBytes, llvm::strictConversion);
3240 // ConvertUTF8toUTF16 returns the length in ToPtr.
3241 StringLength = ToPtr - &ToBuf[0];
3243 // Add an explicit null.
3245 return *Map.insert(std::make_pair(
3246 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3247 (StringLength + 1) * 2),
3252 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3253 unsigned StringLength = 0;
3254 bool isUTF16 = false;
3255 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3256 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3257 getDataLayout().isLittleEndian(), isUTF16,
3260 if (auto *C = Entry.second)
3261 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3263 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3264 llvm::Constant *Zeros[] = { Zero, Zero };
3266 // If we don't already have it, get __CFConstantStringClassReference.
3267 if (!CFConstantStringClassRef) {
3268 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3269 Ty = llvm::ArrayType::get(Ty, 0);
3270 llvm::Constant *GV =
3271 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3273 if (getTriple().isOSBinFormatCOFF()) {
3274 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3275 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3276 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3277 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3279 const VarDecl *VD = nullptr;
3280 for (const auto &Result : DC->lookup(&II))
3281 if ((VD = dyn_cast<VarDecl>(Result)))
3284 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3285 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3286 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3288 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3289 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3293 // Decay array -> ptr
3294 CFConstantStringClassRef =
3295 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3298 QualType CFTy = getContext().getCFConstantStringType();
3300 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3302 ConstantInitBuilder Builder(*this);
3303 auto Fields = Builder.beginStruct(STy);
3306 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3309 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3312 llvm::Constant *C = nullptr;
3314 auto Arr = llvm::makeArrayRef(
3315 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3316 Entry.first().size() / 2);
3317 C = llvm::ConstantDataArray::get(VMContext, Arr);
3319 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3322 // Note: -fwritable-strings doesn't make the backing store strings of
3323 // CFStrings writable. (See <rdar://problem/10657500>)
3325 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3326 llvm::GlobalValue::PrivateLinkage, C, ".str");
3327 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3328 // Don't enforce the target's minimum global alignment, since the only use
3329 // of the string is via this class initializer.
3330 CharUnits Align = isUTF16
3331 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3332 : getContext().getTypeAlignInChars(getContext().CharTy);
3333 GV->setAlignment(Align.getQuantity());
3335 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3336 // Without it LLVM can merge the string with a non unnamed_addr one during
3337 // LTO. Doing that changes the section it ends in, which surprises ld64.
3338 if (getTriple().isOSBinFormatMachO())
3339 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3340 : "__TEXT,__cstring,cstring_literals");
3343 llvm::Constant *Str =
3344 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3347 // Cast the UTF16 string to the correct type.
3348 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3352 auto Ty = getTypes().ConvertType(getContext().LongTy);
3353 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3355 CharUnits Alignment = getPointerAlign();
3358 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3359 /*isConstant=*/false,
3360 llvm::GlobalVariable::PrivateLinkage);
3361 switch (getTriple().getObjectFormat()) {
3362 case llvm::Triple::UnknownObjectFormat:
3363 llvm_unreachable("unknown file format");
3364 case llvm::Triple::COFF:
3365 case llvm::Triple::ELF:
3366 case llvm::Triple::Wasm:
3367 GV->setSection("cfstring");
3369 case llvm::Triple::MachO:
3370 GV->setSection("__DATA,__cfstring");
3375 return ConstantAddress(GV, Alignment);
3378 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3379 if (ObjCFastEnumerationStateType.isNull()) {
3380 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3381 D->startDefinition();
3383 QualType FieldTypes[] = {
3384 Context.UnsignedLongTy,
3385 Context.getPointerType(Context.getObjCIdType()),
3386 Context.getPointerType(Context.UnsignedLongTy),
3387 Context.getConstantArrayType(Context.UnsignedLongTy,
3388 llvm::APInt(32, 5), ArrayType::Normal, 0)
3391 for (size_t i = 0; i < 4; ++i) {
3392 FieldDecl *Field = FieldDecl::Create(Context,
3395 SourceLocation(), nullptr,
3396 FieldTypes[i], /*TInfo=*/nullptr,
3397 /*BitWidth=*/nullptr,
3400 Field->setAccess(AS_public);
3404 D->completeDefinition();
3405 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3408 return ObjCFastEnumerationStateType;
3412 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3413 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3415 // Don't emit it as the address of the string, emit the string data itself
3416 // as an inline array.
3417 if (E->getCharByteWidth() == 1) {
3418 SmallString<64> Str(E->getString());
3420 // Resize the string to the right size, which is indicated by its type.
3421 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3422 Str.resize(CAT->getSize().getZExtValue());
3423 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3426 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3427 llvm::Type *ElemTy = AType->getElementType();
3428 unsigned NumElements = AType->getNumElements();
3430 // Wide strings have either 2-byte or 4-byte elements.
3431 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3432 SmallVector<uint16_t, 32> Elements;
3433 Elements.reserve(NumElements);
3435 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3436 Elements.push_back(E->getCodeUnit(i));
3437 Elements.resize(NumElements);
3438 return llvm::ConstantDataArray::get(VMContext, Elements);
3441 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3442 SmallVector<uint32_t, 32> Elements;
3443 Elements.reserve(NumElements);
3445 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3446 Elements.push_back(E->getCodeUnit(i));
3447 Elements.resize(NumElements);
3448 return llvm::ConstantDataArray::get(VMContext, Elements);
3451 static llvm::GlobalVariable *
3452 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3453 CodeGenModule &CGM, StringRef GlobalName,
3454 CharUnits Alignment) {
3455 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3456 unsigned AddrSpace = 0;
3457 if (CGM.getLangOpts().OpenCL)
3458 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3460 llvm::Module &M = CGM.getModule();
3461 // Create a global variable for this string
3462 auto *GV = new llvm::GlobalVariable(
3463 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3464 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3465 GV->setAlignment(Alignment.getQuantity());
3466 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3467 if (GV->isWeakForLinker()) {
3468 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3469 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3475 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3476 /// constant array for the given string literal.
3478 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3480 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3482 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3483 llvm::GlobalVariable **Entry = nullptr;
3484 if (!LangOpts.WritableStrings) {
3485 Entry = &ConstantStringMap[C];
3486 if (auto GV = *Entry) {
3487 if (Alignment.getQuantity() > GV->getAlignment())
3488 GV->setAlignment(Alignment.getQuantity());
3489 return ConstantAddress(GV, Alignment);
3493 SmallString<256> MangledNameBuffer;
3494 StringRef GlobalVariableName;
3495 llvm::GlobalValue::LinkageTypes LT;
3497 // Mangle the string literal if the ABI allows for it. However, we cannot
3498 // do this if we are compiling with ASan or -fwritable-strings because they
3499 // rely on strings having normal linkage.
3500 if (!LangOpts.WritableStrings &&
3501 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3502 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3503 llvm::raw_svector_ostream Out(MangledNameBuffer);
3504 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3506 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3507 GlobalVariableName = MangledNameBuffer;
3509 LT = llvm::GlobalValue::PrivateLinkage;
3510 GlobalVariableName = Name;
3513 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3517 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3519 return ConstantAddress(GV, Alignment);
3522 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3523 /// array for the given ObjCEncodeExpr node.
3525 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3527 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3529 return GetAddrOfConstantCString(Str);
3532 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3533 /// the literal and a terminating '\0' character.
3534 /// The result has pointer to array type.
3535 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3536 const std::string &Str, const char *GlobalName) {
3537 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3538 CharUnits Alignment =
3539 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3542 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3544 // Don't share any string literals if strings aren't constant.
3545 llvm::GlobalVariable **Entry = nullptr;
3546 if (!LangOpts.WritableStrings) {
3547 Entry = &ConstantStringMap[C];
3548 if (auto GV = *Entry) {
3549 if (Alignment.getQuantity() > GV->getAlignment())
3550 GV->setAlignment(Alignment.getQuantity());
3551 return ConstantAddress(GV, Alignment);
3555 // Get the default prefix if a name wasn't specified.
3557 GlobalName = ".str";
3558 // Create a global variable for this.
3559 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3560 GlobalName, Alignment);
3563 return ConstantAddress(GV, Alignment);
3566 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3567 const MaterializeTemporaryExpr *E, const Expr *Init) {
3568 assert((E->getStorageDuration() == SD_Static ||
3569 E->getStorageDuration() == SD_Thread) && "not a global temporary");
3570 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3572 // If we're not materializing a subobject of the temporary, keep the
3573 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3574 QualType MaterializedType = Init->getType();
3575 if (Init == E->GetTemporaryExpr())
3576 MaterializedType = E->getType();
3578 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3580 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3581 return ConstantAddress(Slot, Align);
3583 // FIXME: If an externally-visible declaration extends multiple temporaries,
3584 // we need to give each temporary the same name in every translation unit (and
3585 // we also need to make the temporaries externally-visible).
3586 SmallString<256> Name;
3587 llvm::raw_svector_ostream Out(Name);
3588 getCXXABI().getMangleContext().mangleReferenceTemporary(
3589 VD, E->getManglingNumber(), Out);
3591 APValue *Value = nullptr;
3592 if (E->getStorageDuration() == SD_Static) {
3593 // We might have a cached constant initializer for this temporary. Note
3594 // that this might have a different value from the value computed by
3595 // evaluating the initializer if the surrounding constant expression
3596 // modifies the temporary.
3597 Value = getContext().getMaterializedTemporaryValue(E, false);
3598 if (Value && Value->isUninit())
3602 // Try evaluating it now, it might have a constant initializer.
3603 Expr::EvalResult EvalResult;
3604 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3605 !EvalResult.hasSideEffects())
3606 Value = &EvalResult.Val;
3608 llvm::Constant *InitialValue = nullptr;
3609 bool Constant = false;
3612 // The temporary has a constant initializer, use it.
3613 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3614 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3615 Type = InitialValue->getType();
3617 // No initializer, the initialization will be provided when we
3618 // initialize the declaration which performed lifetime extension.
3619 Type = getTypes().ConvertTypeForMem(MaterializedType);
3622 // Create a global variable for this lifetime-extended temporary.
3623 llvm::GlobalValue::LinkageTypes Linkage =
3624 getLLVMLinkageVarDefinition(VD, Constant);
3625 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3626 const VarDecl *InitVD;
3627 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3628 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3629 // Temporaries defined inside a class get linkonce_odr linkage because the
3630 // class can be defined in multipe translation units.
3631 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3633 // There is no need for this temporary to have external linkage if the
3634 // VarDecl has external linkage.
3635 Linkage = llvm::GlobalVariable::InternalLinkage;
3638 unsigned AddrSpace = GetGlobalVarAddressSpace(
3639 VD, getContext().getTargetAddressSpace(MaterializedType));
3640 auto *GV = new llvm::GlobalVariable(
3641 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3642 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3644 setGlobalVisibility(GV, VD);
3645 GV->setAlignment(Align.getQuantity());
3646 if (supportsCOMDAT() && GV->isWeakForLinker())
3647 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3648 if (VD->getTLSKind())
3649 setTLSMode(GV, *VD);
3650 MaterializedGlobalTemporaryMap[E] = GV;
3651 return ConstantAddress(GV, Align);
3654 /// EmitObjCPropertyImplementations - Emit information for synthesized
3655 /// properties for an implementation.
3656 void CodeGenModule::EmitObjCPropertyImplementations(const
3657 ObjCImplementationDecl *D) {
3658 for (const auto *PID : D->property_impls()) {
3659 // Dynamic is just for type-checking.
3660 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3661 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3663 // Determine which methods need to be implemented, some may have
3664 // been overridden. Note that ::isPropertyAccessor is not the method
3665 // we want, that just indicates if the decl came from a
3666 // property. What we want to know is if the method is defined in
3667 // this implementation.
3668 if (!D->getInstanceMethod(PD->getGetterName()))
3669 CodeGenFunction(*this).GenerateObjCGetter(
3670 const_cast<ObjCImplementationDecl *>(D), PID);
3671 if (!PD->isReadOnly() &&
3672 !D->getInstanceMethod(PD->getSetterName()))
3673 CodeGenFunction(*this).GenerateObjCSetter(
3674 const_cast<ObjCImplementationDecl *>(D), PID);
3679 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3680 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3681 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3682 ivar; ivar = ivar->getNextIvar())
3683 if (ivar->getType().isDestructedType())
3689 static bool AllTrivialInitializers(CodeGenModule &CGM,
3690 ObjCImplementationDecl *D) {
3691 CodeGenFunction CGF(CGM);
3692 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3693 E = D->init_end(); B != E; ++B) {
3694 CXXCtorInitializer *CtorInitExp = *B;
3695 Expr *Init = CtorInitExp->getInit();
3696 if (!CGF.isTrivialInitializer(Init))
3702 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3703 /// for an implementation.
3704 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3705 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3706 if (needsDestructMethod(D)) {
3707 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3708 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3709 ObjCMethodDecl *DTORMethod =
3710 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3711 cxxSelector, getContext().VoidTy, nullptr, D,
3712 /*isInstance=*/true, /*isVariadic=*/false,
3713 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3714 /*isDefined=*/false, ObjCMethodDecl::Required);
3715 D->addInstanceMethod(DTORMethod);
3716 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3717 D->setHasDestructors(true);
3720 // If the implementation doesn't have any ivar initializers, we don't need
3721 // a .cxx_construct.
3722 if (D->getNumIvarInitializers() == 0 ||
3723 AllTrivialInitializers(*this, D))
3726 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3727 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3728 // The constructor returns 'self'.
3729 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3733 getContext().getObjCIdType(),
3734 nullptr, D, /*isInstance=*/true,
3735 /*isVariadic=*/false,
3736 /*isPropertyAccessor=*/true,
3737 /*isImplicitlyDeclared=*/true,
3738 /*isDefined=*/false,
3739 ObjCMethodDecl::Required);
3740 D->addInstanceMethod(CTORMethod);
3741 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3742 D->setHasNonZeroConstructors(true);
3745 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3746 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3747 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3748 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3749 ErrorUnsupported(LSD, "linkage spec");
3753 EmitDeclContext(LSD);
3756 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3757 for (auto *I : DC->decls()) {
3758 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3759 // are themselves considered "top-level", so EmitTopLevelDecl on an
3760 // ObjCImplDecl does not recursively visit them. We need to do that in
3761 // case they're nested inside another construct (LinkageSpecDecl /
3762 // ExportDecl) that does stop them from being considered "top-level".
3763 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3764 for (auto *M : OID->methods())
3765 EmitTopLevelDecl(M);
3768 EmitTopLevelDecl(I);
3772 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3773 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3774 // Ignore dependent declarations.
3775 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3778 switch (D->getKind()) {
3779 case Decl::CXXConversion:
3780 case Decl::CXXMethod:
3781 case Decl::Function:
3782 // Skip function templates
3783 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3784 cast<FunctionDecl>(D)->isLateTemplateParsed())
3787 EmitGlobal(cast<FunctionDecl>(D));
3788 // Always provide some coverage mapping
3789 // even for the functions that aren't emitted.
3790 AddDeferredUnusedCoverageMapping(D);
3793 case Decl::CXXDeductionGuide:
3794 // Function-like, but does not result in code emission.
3798 case Decl::Decomposition:
3799 // Skip variable templates
3800 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3802 case Decl::VarTemplateSpecialization:
3803 EmitGlobal(cast<VarDecl>(D));
3804 if (auto *DD = dyn_cast<DecompositionDecl>(D))
3805 for (auto *B : DD->bindings())
3806 if (auto *HD = B->getHoldingVar())
3810 // Indirect fields from global anonymous structs and unions can be
3811 // ignored; only the actual variable requires IR gen support.
3812 case Decl::IndirectField:
3816 case Decl::Namespace:
3817 EmitDeclContext(cast<NamespaceDecl>(D));
3819 case Decl::CXXRecord:
3821 if (auto *ES = D->getASTContext().getExternalSource())
3822 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3823 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3825 // Emit any static data members, they may be definitions.
3826 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3827 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3828 EmitTopLevelDecl(I);
3830 // No code generation needed.
3831 case Decl::UsingShadow:
3832 case Decl::ClassTemplate:
3833 case Decl::VarTemplate:
3834 case Decl::VarTemplatePartialSpecialization:
3835 case Decl::FunctionTemplate:
3836 case Decl::TypeAliasTemplate:
3840 case Decl::Using: // using X; [C++]
3841 if (CGDebugInfo *DI = getModuleDebugInfo())
3842 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3844 case Decl::NamespaceAlias:
3845 if (CGDebugInfo *DI = getModuleDebugInfo())
3846 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3848 case Decl::UsingDirective: // using namespace X; [C++]
3849 if (CGDebugInfo *DI = getModuleDebugInfo())
3850 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3852 case Decl::CXXConstructor:
3853 // Skip function templates
3854 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3855 cast<FunctionDecl>(D)->isLateTemplateParsed())
3858 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3860 case Decl::CXXDestructor:
3861 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3863 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3866 case Decl::StaticAssert:
3870 // Objective-C Decls
3872 // Forward declarations, no (immediate) code generation.
3873 case Decl::ObjCInterface:
3874 case Decl::ObjCCategory:
3877 case Decl::ObjCProtocol: {
3878 auto *Proto = cast<ObjCProtocolDecl>(D);
3879 if (Proto->isThisDeclarationADefinition())
3880 ObjCRuntime->GenerateProtocol(Proto);
3884 case Decl::ObjCCategoryImpl:
3885 // Categories have properties but don't support synthesize so we
3886 // can ignore them here.
3887 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3890 case Decl::ObjCImplementation: {
3891 auto *OMD = cast<ObjCImplementationDecl>(D);
3892 EmitObjCPropertyImplementations(OMD);
3893 EmitObjCIvarInitializations(OMD);
3894 ObjCRuntime->GenerateClass(OMD);
3895 // Emit global variable debug information.
3896 if (CGDebugInfo *DI = getModuleDebugInfo())
3897 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3898 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3899 OMD->getClassInterface()), OMD->getLocation());
3902 case Decl::ObjCMethod: {
3903 auto *OMD = cast<ObjCMethodDecl>(D);
3904 // If this is not a prototype, emit the body.
3906 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3909 case Decl::ObjCCompatibleAlias:
3910 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3913 case Decl::PragmaComment: {
3914 const auto *PCD = cast<PragmaCommentDecl>(D);
3915 switch (PCD->getCommentKind()) {
3917 llvm_unreachable("unexpected pragma comment kind");
3919 AppendLinkerOptions(PCD->getArg());
3922 AddDependentLib(PCD->getArg());
3927 break; // We ignore all of these.
3932 case Decl::PragmaDetectMismatch: {
3933 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3934 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3938 case Decl::LinkageSpec:
3939 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3942 case Decl::FileScopeAsm: {
3943 // File-scope asm is ignored during device-side CUDA compilation.
3944 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3946 // File-scope asm is ignored during device-side OpenMP compilation.
3947 if (LangOpts.OpenMPIsDevice)
3949 auto *AD = cast<FileScopeAsmDecl>(D);
3950 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3954 case Decl::Import: {
3955 auto *Import = cast<ImportDecl>(D);
3957 // If we've already imported this module, we're done.
3958 if (!ImportedModules.insert(Import->getImportedModule()))
3961 // Emit debug information for direct imports.
3962 if (!Import->getImportedOwningModule()) {
3963 if (CGDebugInfo *DI = getModuleDebugInfo())
3964 DI->EmitImportDecl(*Import);
3967 // Find all of the submodules and emit the module initializers.
3968 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3969 SmallVector<clang::Module *, 16> Stack;
3970 Visited.insert(Import->getImportedModule());
3971 Stack.push_back(Import->getImportedModule());
3973 while (!Stack.empty()) {
3974 clang::Module *Mod = Stack.pop_back_val();
3975 if (!EmittedModuleInitializers.insert(Mod).second)
3978 for (auto *D : Context.getModuleInitializers(Mod))
3979 EmitTopLevelDecl(D);
3981 // Visit the submodules of this module.
3982 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
3983 SubEnd = Mod->submodule_end();
3984 Sub != SubEnd; ++Sub) {
3985 // Skip explicit children; they need to be explicitly imported to emit
3986 // the initializers.
3987 if ((*Sub)->IsExplicit)
3990 if (Visited.insert(*Sub).second)
3991 Stack.push_back(*Sub);
3998 EmitDeclContext(cast<ExportDecl>(D));
4001 case Decl::OMPThreadPrivate:
4002 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4005 case Decl::ClassTemplateSpecialization: {
4006 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4008 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4009 Spec->hasDefinition())
4010 DebugInfo->completeTemplateDefinition(*Spec);
4014 case Decl::OMPDeclareReduction:
4015 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4019 // Make sure we handled everything we should, every other kind is a
4020 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4021 // function. Need to recode Decl::Kind to do that easily.
4022 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4027 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4028 // Do we need to generate coverage mapping?
4029 if (!CodeGenOpts.CoverageMapping)
4031 switch (D->getKind()) {
4032 case Decl::CXXConversion:
4033 case Decl::CXXMethod:
4034 case Decl::Function:
4035 case Decl::ObjCMethod:
4036 case Decl::CXXConstructor:
4037 case Decl::CXXDestructor: {
4038 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4040 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4041 if (I == DeferredEmptyCoverageMappingDecls.end())
4042 DeferredEmptyCoverageMappingDecls[D] = true;
4050 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4051 // Do we need to generate coverage mapping?
4052 if (!CodeGenOpts.CoverageMapping)
4054 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4055 if (Fn->isTemplateInstantiation())
4056 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4058 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4059 if (I == DeferredEmptyCoverageMappingDecls.end())
4060 DeferredEmptyCoverageMappingDecls[D] = false;
4065 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4066 std::vector<const Decl *> DeferredDecls;
4067 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4070 DeferredDecls.push_back(I.first);
4072 // Sort the declarations by their location to make sure that the tests get a
4073 // predictable order for the coverage mapping for the unused declarations.
4074 if (CodeGenOpts.DumpCoverageMapping)
4075 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4076 [] (const Decl *LHS, const Decl *RHS) {
4077 return LHS->getLocStart() < RHS->getLocStart();
4079 for (const auto *D : DeferredDecls) {
4080 switch (D->getKind()) {
4081 case Decl::CXXConversion:
4082 case Decl::CXXMethod:
4083 case Decl::Function:
4084 case Decl::ObjCMethod: {
4085 CodeGenPGO PGO(*this);
4086 GlobalDecl GD(cast<FunctionDecl>(D));
4087 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4088 getFunctionLinkage(GD));
4091 case Decl::CXXConstructor: {
4092 CodeGenPGO PGO(*this);
4093 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4094 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4095 getFunctionLinkage(GD));
4098 case Decl::CXXDestructor: {
4099 CodeGenPGO PGO(*this);
4100 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4101 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4102 getFunctionLinkage(GD));
4111 /// Turns the given pointer into a constant.
4112 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4114 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4115 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4116 return llvm::ConstantInt::get(i64, PtrInt);
4119 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4120 llvm::NamedMDNode *&GlobalMetadata,
4122 llvm::GlobalValue *Addr) {
4123 if (!GlobalMetadata)
4125 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4127 // TODO: should we report variant information for ctors/dtors?
4128 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4129 llvm::ConstantAsMetadata::get(GetPointerConstant(
4130 CGM.getLLVMContext(), D.getDecl()))};
4131 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4134 /// For each function which is declared within an extern "C" region and marked
4135 /// as 'used', but has internal linkage, create an alias from the unmangled
4136 /// name to the mangled name if possible. People expect to be able to refer
4137 /// to such functions with an unmangled name from inline assembly within the
4138 /// same translation unit.
4139 void CodeGenModule::EmitStaticExternCAliases() {
4140 // Don't do anything if we're generating CUDA device code -- the NVPTX
4141 // assembly target doesn't support aliases.
4142 if (Context.getTargetInfo().getTriple().isNVPTX())
4144 for (auto &I : StaticExternCValues) {
4145 IdentifierInfo *Name = I.first;
4146 llvm::GlobalValue *Val = I.second;
4147 if (Val && !getModule().getNamedValue(Name->getName()))
4148 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4152 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4153 GlobalDecl &Result) const {
4154 auto Res = Manglings.find(MangledName);
4155 if (Res == Manglings.end())
4157 Result = Res->getValue();
4161 /// Emits metadata nodes associating all the global values in the
4162 /// current module with the Decls they came from. This is useful for
4163 /// projects using IR gen as a subroutine.
4165 /// Since there's currently no way to associate an MDNode directly
4166 /// with an llvm::GlobalValue, we create a global named metadata
4167 /// with the name 'clang.global.decl.ptrs'.
4168 void CodeGenModule::EmitDeclMetadata() {
4169 llvm::NamedMDNode *GlobalMetadata = nullptr;
4171 for (auto &I : MangledDeclNames) {
4172 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4173 // Some mangled names don't necessarily have an associated GlobalValue
4174 // in this module, e.g. if we mangled it for DebugInfo.
4176 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4180 /// Emits metadata nodes for all the local variables in the current
4182 void CodeGenFunction::EmitDeclMetadata() {
4183 if (LocalDeclMap.empty()) return;
4185 llvm::LLVMContext &Context = getLLVMContext();
4187 // Find the unique metadata ID for this name.
4188 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4190 llvm::NamedMDNode *GlobalMetadata = nullptr;
4192 for (auto &I : LocalDeclMap) {
4193 const Decl *D = I.first;
4194 llvm::Value *Addr = I.second.getPointer();
4195 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4196 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4197 Alloca->setMetadata(
4198 DeclPtrKind, llvm::MDNode::get(
4199 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4200 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4201 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4202 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4207 void CodeGenModule::EmitVersionIdentMetadata() {
4208 llvm::NamedMDNode *IdentMetadata =
4209 TheModule.getOrInsertNamedMetadata("llvm.ident");
4210 std::string Version = getClangFullVersion();
4211 llvm::LLVMContext &Ctx = TheModule.getContext();
4213 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4214 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4217 void CodeGenModule::EmitTargetMetadata() {
4218 // Warning, new MangledDeclNames may be appended within this loop.
4219 // We rely on MapVector insertions adding new elements to the end
4220 // of the container.
4221 // FIXME: Move this loop into the one target that needs it, and only
4222 // loop over those declarations for which we couldn't emit the target
4223 // metadata when we emitted the declaration.
4224 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4225 auto Val = *(MangledDeclNames.begin() + I);
4226 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4227 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4228 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4232 void CodeGenModule::EmitCoverageFile() {
4233 if (getCodeGenOpts().CoverageDataFile.empty() &&
4234 getCodeGenOpts().CoverageNotesFile.empty())
4237 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4241 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4242 llvm::LLVMContext &Ctx = TheModule.getContext();
4243 auto *CoverageDataFile =
4244 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4245 auto *CoverageNotesFile =
4246 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4247 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4248 llvm::MDNode *CU = CUNode->getOperand(i);
4249 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4250 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4254 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4255 // Sema has checked that all uuid strings are of the form
4256 // "12345678-1234-1234-1234-1234567890ab".
4257 assert(Uuid.size() == 36);
4258 for (unsigned i = 0; i < 36; ++i) {
4259 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4260 else assert(isHexDigit(Uuid[i]));
4263 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4264 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4266 llvm::Constant *Field3[8];
4267 for (unsigned Idx = 0; Idx < 8; ++Idx)
4268 Field3[Idx] = llvm::ConstantInt::get(
4269 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4271 llvm::Constant *Fields[4] = {
4272 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4273 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4274 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4275 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4278 return llvm::ConstantStruct::getAnon(Fields);
4281 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4283 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4284 // FIXME: should we even be calling this method if RTTI is disabled
4285 // and it's not for EH?
4286 if (!ForEH && !getLangOpts().RTTI)
4287 return llvm::Constant::getNullValue(Int8PtrTy);
4289 if (ForEH && Ty->isObjCObjectPointerType() &&
4290 LangOpts.ObjCRuntime.isGNUFamily())
4291 return ObjCRuntime->GetEHType(Ty);
4293 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4296 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4297 for (auto RefExpr : D->varlists()) {
4298 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4300 VD->getAnyInitializer() &&
4301 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4304 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4305 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4306 VD, Addr, RefExpr->getLocStart(), PerformInit))
4307 CXXGlobalInits.push_back(InitFunction);
4311 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4312 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4316 if (isExternallyVisible(T->getLinkage())) {
4317 std::string OutName;
4318 llvm::raw_string_ostream Out(OutName);
4319 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4321 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4323 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4324 llvm::ArrayRef<llvm::Metadata *>());
4330 /// Returns whether this module needs the "all-vtables" type identifier.
4331 bool CodeGenModule::NeedAllVtablesTypeId() const {
4332 // Returns true if at least one of vtable-based CFI checkers is enabled and
4333 // is not in the trapping mode.
4334 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4335 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4336 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4337 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4338 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4339 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4340 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4341 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4344 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4346 const CXXRecordDecl *RD) {
4347 llvm::Metadata *MD =
4348 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4349 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4351 if (CodeGenOpts.SanitizeCfiCrossDso)
4352 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4353 VTable->addTypeMetadata(Offset.getQuantity(),
4354 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4356 if (NeedAllVtablesTypeId()) {
4357 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4358 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4362 // Fills in the supplied string map with the set of target features for the
4363 // passed in function.
4364 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4365 const FunctionDecl *FD) {
4366 StringRef TargetCPU = Target.getTargetOpts().CPU;
4367 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4368 // If we have a TargetAttr build up the feature map based on that.
4369 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4371 // Make a copy of the features as passed on the command line into the
4372 // beginning of the additional features from the function to override.
4373 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4374 Target.getTargetOpts().FeaturesAsWritten.begin(),
4375 Target.getTargetOpts().FeaturesAsWritten.end());
4377 if (ParsedAttr.second != "")
4378 TargetCPU = ParsedAttr.second;
4380 // Now populate the feature map, first with the TargetCPU which is either
4381 // the default or a new one from the target attribute string. Then we'll use
4382 // the passed in features (FeaturesAsWritten) along with the new ones from
4384 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4386 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4387 Target.getTargetOpts().Features);
4391 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4393 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4398 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4399 CodeGenFunction &CGF) {
4400 llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4401 auto SamplerT = getOpenCLRuntime().getSamplerType();
4402 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4403 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4404 "__translate_sampler_initializer"),