47 #include "llvm/ADT/StringSwitch.h" 48 #include "llvm/ADT/Triple.h" 49 #include "llvm/Analysis/TargetLibraryInfo.h" 50 #include "llvm/IR/CallSite.h" 51 #include "llvm/IR/CallingConv.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/Intrinsics.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/Module.h" 56 #include "llvm/ProfileData/InstrProfReader.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/ConvertUTF.h" 59 #include "llvm/Support/ErrorHandling.h" 60 #include "llvm/Support/MD5.h" 62 using namespace clang;
63 using namespace CodeGen;
66 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
67 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"),
68 llvm::cl::init(
false));
87 llvm_unreachable(
"invalid C++ ABI kind");
95 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
96 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
98 VMContext(M.getContext()), Types(*this), VTables(*this),
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
108 HalfTy = llvm::Type::getHalfTy(LLVMContext);
109 FloatTy = llvm::Type::getFloatTy(LLVMContext);
110 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
119 IntPtrTy = llvm::IntegerType::get(LLVMContext,
124 M.getDataLayout().getAllocaAddrSpace());
132 createOpenCLRuntime();
134 createOpenMPRuntime();
139 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
140 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
147 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
150 Block.GlobalUniqueCount = 0;
158 if (
auto E = ReaderOrErr.takeError()) {
160 "Could not read profile %0: %1");
161 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
166 PGOReader = std::move(ReaderOrErr.get());
171 if (CodeGenOpts.CoverageMapping)
177 void CodeGenModule::createObjCRuntime() {
194 llvm_unreachable(
"bad runtime kind");
197 void CodeGenModule::createOpenCLRuntime() {
201 void CodeGenModule::createOpenMPRuntime() {
205 case llvm::Triple::nvptx:
206 case llvm::Triple::nvptx64:
208 "OpenMP NVPTX is only prepared to deal with device code.");
212 if (LangOpts.OpenMPSimd)
220 void CodeGenModule::createCUDARuntime() {
225 Replacements[Name] = C;
228 void CodeGenModule::applyReplacements() {
229 for (
auto &I : Replacements) {
230 StringRef MangledName = I.first();
231 llvm::Constant *Replacement = I.second;
235 auto *OldF = cast<llvm::Function>(Entry);
236 auto *NewF = dyn_cast<llvm::Function>(Replacement);
238 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
239 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
241 auto *CE = cast<llvm::ConstantExpr>(Replacement);
242 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
243 CE->getOpcode() == llvm::Instruction::GetElementPtr);
244 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
249 OldF->replaceAllUsesWith(Replacement);
251 NewF->removeFromParent();
252 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
255 OldF->eraseFromParent();
260 GlobalValReplacements.push_back(std::make_pair(GV, C));
263 void CodeGenModule::applyGlobalValReplacements() {
264 for (
auto &I : GlobalValReplacements) {
265 llvm::GlobalValue *GV = I.first;
266 llvm::Constant *C = I.second;
268 GV->replaceAllUsesWith(C);
269 GV->eraseFromParent();
276 const llvm::GlobalIndirectSymbol &GIS) {
277 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
278 const llvm::Constant *C = &GIS;
280 C = C->stripPointerCasts();
281 if (
auto *GO = dyn_cast<llvm::GlobalObject>(C))
284 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
287 if (!Visited.insert(GIS2).second)
289 C = GIS2->getIndirectSymbol();
293 void CodeGenModule::checkAliases() {
300 const auto *D = cast<ValueDecl>(GD.getDecl());
302 bool IsIFunc = D->hasAttr<IFuncAttr>();
303 if (
const Attr *A = D->getDefiningAttr())
304 Location = A->getLocation();
306 llvm_unreachable(
"Not an alias or ifunc?");
309 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
313 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
314 }
else if (GV->isDeclaration()) {
316 Diags.
Report(Location, diag::err_alias_to_undefined)
317 << IsIFunc << IsIFunc;
318 }
else if (IsIFunc) {
320 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
321 GV->getType()->getPointerElementType());
323 if (!FTy->getReturnType()->isPointerTy())
324 Diags.
Report(Location, diag::err_ifunc_resolver_return);
327 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
328 llvm::GlobalValue *AliaseeGV;
329 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
332 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
334 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335 StringRef AliasSection = SA->getName();
336 if (AliasSection != AliaseeGV->getSection())
337 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
338 << AliasSection << IsIFunc << IsIFunc;
346 if (
auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
347 if (GA->isInterposable()) {
348 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
349 << GV->getName() << GA->getName() << IsIFunc;
350 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
351 GA->getIndirectSymbol(), Alias->getType());
352 Alias->setIndirectSymbol(Aliasee);
362 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
363 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364 Alias->eraseFromParent();
369 DeferredDeclsToEmit.clear();
371 OpenMPRuntime->clear();
375 StringRef MainFile) {
376 if (!hasDiagnostics())
378 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379 if (MainFile.empty())
380 MainFile =
"<stdin>";
381 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
384 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
387 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
393 EmitVTablesOpportunistically();
394 applyGlobalValReplacements();
397 emitMultiVersionFunctions();
398 EmitCXXGlobalInitFunc();
399 EmitCXXGlobalDtorFunc();
400 registerGlobalDtorsWithAtExit();
401 EmitCXXThreadLocalInitFunc();
403 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
404 AddGlobalCtor(ObjCInitFunction);
407 if (llvm::Function *CudaCtorFunction =
408 CUDARuntime->makeModuleCtorFunction())
409 AddGlobalCtor(CudaCtorFunction);
412 if (llvm::Function *OpenMPRegistrationFunction =
413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction :
nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
418 OpenMPRuntime->clear();
421 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
425 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
426 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
428 EmitStaticExternCAliases();
431 CoverageMapping->emit();
432 if (CodeGenOpts.SanitizeCfiCrossDso) {
436 emitAtAvailableLinkGuard();
441 if (CodeGenOpts.Autolink &&
442 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
443 EmitModuleLinkOptions();
449 CodeGenOpts.NumRegisterParameters);
451 if (CodeGenOpts.DwarfVersion) {
455 CodeGenOpts.DwarfVersion);
457 if (CodeGenOpts.EmitCodeView) {
461 if (CodeGenOpts.CodeViewGHash) {
464 if (CodeGenOpts.ControlFlowGuard) {
468 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
475 llvm::Metadata *Ops[2] = {
476 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
477 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
478 llvm::Type::getInt32Ty(VMContext), 1))};
480 getModule().addModuleFlag(llvm::Module::Require,
481 "StrictVTablePointersRequirement",
482 llvm::MDNode::get(VMContext, Ops));
489 llvm::DEBUG_METADATA_VERSION);
494 uint64_t WCharWidth =
499 if ( Arch == llvm::Triple::arm
500 || Arch == llvm::Triple::armeb
501 || Arch == llvm::Triple::thumb
502 || Arch == llvm::Triple::thumbeb) {
504 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
508 if (CodeGenOpts.SanitizeCfiCrossDso) {
510 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
513 if (CodeGenOpts.CFProtectionReturn &&
516 getModule().addModuleFlag(llvm::Module::Override,
"cf-protection-return",
520 if (CodeGenOpts.CFProtectionBranch &&
523 getModule().addModuleFlag(llvm::Module::Override,
"cf-protection-branch",
527 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
531 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
532 CodeGenOpts.FlushDenorm ? 1 : 0);
536 if (LangOpts.OpenCL) {
537 EmitOpenCLMetadata();
539 if (
getTriple().getArch() == llvm::Triple::spir ||
540 getTriple().getArch() == llvm::Triple::spir64) {
543 llvm::Metadata *SPIRVerElts[] = {
544 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
545 Int32Ty, LangOpts.OpenCLVersion / 100)),
546 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
547 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
548 llvm::NamedMDNode *SPIRVerMD =
549 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
550 llvm::LLVMContext &Ctx = TheModule.getContext();
551 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
555 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
556 assert(PLevel < 3 &&
"Invalid PIC Level");
557 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
559 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
564 .Case(
"tiny", llvm::CodeModel::Tiny)
565 .Case(
"small", llvm::CodeModel::Small)
566 .Case(
"kernel", llvm::CodeModel::Kernel)
567 .Case(
"medium", llvm::CodeModel::Medium)
568 .Case(
"large", llvm::CodeModel::Large)
571 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
576 if (CodeGenOpts.NoPLT)
579 SimplifyPersonality();
588 DebugInfo->finalize();
591 EmitVersionIdentMetadata();
594 EmitCommandLineMetadata();
596 EmitTargetMetadata();
599 void CodeGenModule::EmitOpenCLMetadata() {
602 llvm::Metadata *OCLVerElts[] = {
603 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
604 Int32Ty, LangOpts.OpenCLVersion / 100)),
605 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
606 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
607 llvm::NamedMDNode *OCLVerMD =
608 TheModule.getOrInsertNamedMetadata(
"opencl.ocl.version");
609 llvm::LLVMContext &Ctx = TheModule.getContext();
610 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
626 return TBAA->getTypeInfo(QTy);
632 return TBAA->getAccessInfo(AccessType);
639 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
645 return TBAA->getTBAAStructInfo(QTy);
651 return TBAA->getBaseTypeInfo(QTy);
657 return TBAA->getAccessTagInfo(Info);
664 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
672 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
680 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
686 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
691 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
704 "cannot compile this %0 yet");
705 std::string Msg =
Type;
714 "cannot compile this %0 yet");
715 std::string Msg =
Type;
725 if (GV->hasDLLImportStorageClass())
728 if (GV->hasLocalLinkage()) {
741 llvm::GlobalValue *GV) {
742 if (GV->hasLocalLinkage())
745 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
749 if (GV->hasDLLImportStorageClass())
752 const llvm::Triple &TT = CGM.
getTriple();
753 if (TT.isWindowsGNUEnvironment()) {
757 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
758 !GV->isThreadLocal())
766 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
770 if (!TT.isOSBinFormatELF())
777 if (RM != llvm::Reloc::Static && !LOpts.PIE)
781 if (!GV->isDeclarationForLinker())
787 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
791 llvm::Triple::ArchType Arch = TT.getArch();
792 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
793 Arch == llvm::Triple::ppc64le)
797 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
798 if (!Var->isThreadLocal() &&
799 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
805 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
820 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
830 if (D->
hasAttr<DLLImportAttr>())
831 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
832 else if (D->
hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
833 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
856 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
857 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
858 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
859 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
860 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
867 return llvm::GlobalVariable::GeneralDynamicTLSModel;
869 return llvm::GlobalVariable::LocalDynamicTLSModel;
871 return llvm::GlobalVariable::InitialExecTLSModel;
873 return llvm::GlobalVariable::LocalExecTLSModel;
875 llvm_unreachable(
"Invalid TLS model!");
879 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
881 llvm::GlobalValue::ThreadLocalMode TLM;
885 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
889 GV->setThreadLocalMode(TLM);
899 const CPUSpecificAttr *
Attr,
911 const TargetAttr *
Attr, raw_ostream &Out) {
912 if (Attr->isDefaultVersion())
917 TargetAttr::ParsedTargetAttr Info =
918 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
921 assert(LHS.startswith(
"+") && RHS.startswith(
"+") &&
922 "Features should always have a prefix.");
929 if (!Info.Architecture.empty()) {
931 Out <<
"arch_" << Info.Architecture;
934 for (StringRef Feat : Info.Features) {
938 Out << Feat.substr(1);
944 bool OmitMultiVersionMangling =
false) {
946 llvm::raw_svector_ostream Out(Buffer);
949 llvm::raw_svector_ostream Out(Buffer);
950 if (
const auto *D = dyn_cast<CXXConstructorDecl>(ND))
952 else if (
const auto *D = dyn_cast<CXXDestructorDecl>(ND))
958 assert(II &&
"Attempt to mangle unnamed decl.");
963 llvm::raw_svector_ostream Out(Buffer);
964 Out <<
"__regcall3__" << II->
getName();
970 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
971 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
972 switch (FD->getMultiVersionKind()) {
976 FD->getAttr<CPUSpecificAttr>(),
983 llvm_unreachable(
"None multiversion type isn't valid here");
990 void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
998 std::string NonTargetName =
1006 "Other GD should now be a multiversioned function");
1016 if (OtherName != NonTargetName) {
1019 const auto ExistingRecord = Manglings.find(NonTargetName);
1020 if (ExistingRecord != std::end(Manglings))
1021 Manglings.remove(&(*ExistingRecord));
1022 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1025 Entry->setName(OtherName);
1035 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
1044 auto FoundName = MangledDeclNames.find(CanonicalGD);
1045 if (FoundName != MangledDeclNames.end())
1046 return FoundName->second;
1049 const auto *ND = cast<NamedDecl>(GD.
getDecl());
1052 return MangledDeclNames[CanonicalGD] = Result.first->first();
1061 llvm::raw_svector_ostream Out(Buffer);
1064 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
1065 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1067 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1070 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
1072 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1073 return Result.first->first();
1082 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor,
int Priority,
1083 llvm::Constant *AssociatedData) {
1085 GlobalCtors.push_back(
Structor(Priority, Ctor, AssociatedData));
1090 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor,
int Priority) {
1091 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1092 DtorsUsingAtExit[Priority].push_back(Dtor);
1097 GlobalDtors.push_back(
Structor(Priority, Dtor,
nullptr));
1100 void CodeGenModule::EmitCtorList(
CtorList &Fns,
const char *GlobalName) {
1101 if (Fns.empty())
return;
1104 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
1105 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1106 TheModule.getDataLayout().getProgramAddressSpace());
1109 llvm::StructType *CtorStructTy = llvm::StructType::get(
1114 auto ctors = builder.
beginArray(CtorStructTy);
1115 for (
const auto &I : Fns) {
1116 auto ctor = ctors.beginStruct(CtorStructTy);
1117 ctor.addInt(
Int32Ty, I.Priority);
1118 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1119 if (I.AssociatedData)
1120 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData,
VoidPtrTy));
1123 ctor.finishAndAddTo(ctors);
1129 llvm::GlobalValue::AppendingLinkage);
1133 list->setAlignment(0);
1138 llvm::GlobalValue::LinkageTypes
1140 const auto *D = cast<FunctionDecl>(GD.
getDecl());
1144 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1147 if (isa<CXXConstructorDecl>(D) &&
1148 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1160 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1161 if (!MDS)
return nullptr;
1163 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
1168 llvm::Function *F) {
1170 llvm::AttributeList PAL;
1172 F->setAttributes(PAL);
1173 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1183 if (!LangOpts.Exceptions)
return false;
1186 if (LangOpts.CXXExceptions)
return true;
1189 if (LangOpts.ObjCExceptions) {
1206 !isa<CXXDestructorDecl>(MD);
1209 std::vector<const CXXRecordDecl *>
1211 llvm::SetVector<const CXXRecordDecl *> MostBases;
1213 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1216 MostBases.insert(RD);
1218 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1220 CollectMostBases(RD);
1221 return MostBases.takeVector();
1225 llvm::Function *F) {
1226 llvm::AttrBuilder B;
1228 if (CodeGenOpts.UnwindTables)
1229 B.addAttribute(llvm::Attribute::UWTable);
1232 B.addAttribute(llvm::Attribute::NoUnwind);
1234 if (!D || !D->
hasAttr<NoStackProtectorAttr>()) {
1236 B.addAttribute(llvm::Attribute::StackProtect);
1238 B.addAttribute(llvm::Attribute::StackProtectStrong);
1240 B.addAttribute(llvm::Attribute::StackProtectReq);
1247 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1249 B.addAttribute(llvm::Attribute::NoInline);
1251 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1257 bool ShouldAddOptNone =
1258 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1260 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
1261 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1262 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
1264 if (ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) {
1265 B.addAttribute(llvm::Attribute::OptimizeNone);
1268 B.addAttribute(llvm::Attribute::NoInline);
1269 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1270 "OptimizeNone and AlwaysInline on same function!");
1275 B.addAttribute(llvm::Attribute::Naked);
1278 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1279 F->removeFnAttr(llvm::Attribute::MinSize);
1280 }
else if (D->
hasAttr<NakedAttr>()) {
1282 B.addAttribute(llvm::Attribute::Naked);
1283 B.addAttribute(llvm::Attribute::NoInline);
1284 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
1285 B.addAttribute(llvm::Attribute::NoDuplicate);
1286 }
else if (D->
hasAttr<NoInlineAttr>()) {
1287 B.addAttribute(llvm::Attribute::NoInline);
1288 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
1289 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1291 B.addAttribute(llvm::Attribute::AlwaysInline);
1295 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1296 B.addAttribute(llvm::Attribute::NoInline);
1300 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
1303 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
1304 return Redecl->isInlineSpecified();
1306 if (any_of(FD->
redecls(), CheckRedeclForInline))
1311 return any_of(Pattern->
redecls(), CheckRedeclForInline);
1313 if (CheckForInline(FD)) {
1314 B.addAttribute(llvm::Attribute::InlineHint);
1315 }
else if (CodeGenOpts.getInlining() ==
1318 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1319 B.addAttribute(llvm::Attribute::NoInline);
1326 if (!D->
hasAttr<OptimizeNoneAttr>()) {
1328 if (!ShouldAddOptNone)
1329 B.addAttribute(llvm::Attribute::OptimizeForSize);
1330 B.addAttribute(llvm::Attribute::Cold);
1333 if (D->
hasAttr<MinSizeAttr>())
1334 B.addAttribute(llvm::Attribute::MinSize);
1337 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1341 F->setAlignment(alignment);
1343 if (!D->
hasAttr<AlignedAttr>())
1344 if (LangOpts.FunctionAlignment)
1345 F->setAlignment(1 << LangOpts.FunctionAlignment);
1352 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1357 if (CodeGenOpts.SanitizeCfiCrossDso)
1358 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1367 llvm::Metadata *
Id =
1370 F->addTypeMetadata(0, Id);
1377 if (dyn_cast_or_null<NamedDecl>(D))
1382 if (D && D->
hasAttr<UsedAttr>())
1385 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1386 const auto *VD = cast<VarDecl>(D);
1387 if (VD->getType().isConstQualified() &&
1393 bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
1394 llvm::AttrBuilder &Attrs) {
1399 std::vector<std::string> Features;
1400 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
1402 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
1403 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() :
nullptr;
1404 bool AddedAttr =
false;
1406 llvm::StringMap<bool> FeatureMap;
1410 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1411 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
1418 TargetAttr::ParsedTargetAttr
ParsedAttr = TD->parse();
1419 if (ParsedAttr.Architecture !=
"" &&
1420 getTarget().isValidCPUName(ParsedAttr.Architecture))
1421 TargetCPU = ParsedAttr.Architecture;
1429 if (TargetCPU !=
"") {
1430 Attrs.addAttribute(
"target-cpu", TargetCPU);
1433 if (!Features.empty()) {
1434 llvm::sort(Features);
1435 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
1442 void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
1443 llvm::GlobalObject *GO) {
1448 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1449 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
1450 GV->addAttribute(
"bss-section", SA->getName());
1451 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
1452 GV->addAttribute(
"data-section", SA->getName());
1453 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
1454 GV->addAttribute(
"rodata-section", SA->getName());
1457 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
1458 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
1459 if (!D->
getAttr<SectionAttr>())
1460 F->addFnAttr(
"implicit-section-name", SA->getName());
1462 llvm::AttrBuilder Attrs;
1463 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
1467 F->removeFnAttr(
"target-cpu");
1468 F->removeFnAttr(
"target-features");
1469 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1473 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
1474 GO->setSection(CSA->getName());
1475 else if (
const auto *SA = D->
getAttr<SectionAttr>())
1476 GO->setSection(SA->getName());
1491 setNonAliasAttributes(GD, F);
1502 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1506 llvm::Function *F) {
1508 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
1513 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1517 if (CodeGenOpts.SanitizeCfiCrossDso) {
1525 F->addTypeMetadata(0, MD);
1529 if (CodeGenOpts.SanitizeCfiCrossDso)
1531 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1534 void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
1535 bool IsIncompleteFunction,
1541 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
1545 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1547 if (!IsIncompleteFunction) {
1550 if (F->isDeclaration())
1557 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
1559 assert(!F->arg_empty() &&
1560 F->arg_begin()->getType()
1561 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1562 "unexpected this return");
1563 F->addAttribute(1, llvm::Attribute::Returned);
1572 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
1573 F->setSection(CSA->getName());
1574 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
1575 F->setSection(SA->getName());
1580 F->addAttribute(llvm::AttributeList::FunctionIndex,
1581 llvm::Attribute::NoBuiltin);
1588 (
Kind == OO_New ||
Kind == OO_Array_New))
1589 F->addAttribute(llvm::AttributeList::ReturnIndex,
1590 llvm::Attribute::NoAlias);
1593 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1594 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1595 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1596 if (MD->isVirtual())
1597 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1601 if (!CodeGenOpts.SanitizeCfiCrossDso)
1609 assert(!GV->isDeclaration() &&
1610 "Only globals with definition can force usage.");
1611 LLVMUsed.emplace_back(GV);
1615 assert(!GV->isDeclaration() &&
1616 "Only globals with definition can force usage.");
1617 LLVMCompilerUsed.emplace_back(GV);
1621 std::vector<llvm::WeakTrackingVH> &List) {
1628 UsedArray.resize(List.size());
1629 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
1631 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1632 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
1635 if (UsedArray.empty())
1637 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
1639 auto *GV =
new llvm::GlobalVariable(
1640 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
1641 llvm::ConstantArray::get(ATy, UsedArray), Name);
1643 GV->setSection(
"llvm.metadata");
1646 void CodeGenModule::emitLLVMUsed() {
1647 emitUsed(*
this,
"llvm.used", LLVMUsed);
1648 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
1653 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1660 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1665 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1666 C, {llvm::MDString::get(C,
"lib"), llvm::MDString::get(C, Lib)}));
1673 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1680 llvm::SmallPtrSet<Module *, 16> &Visited) {
1682 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
1687 for (
unsigned I = Mod->
Imports.size(); I > 0; --I) {
1688 if (Visited.insert(Mod->
Imports[I - 1]).second)
1707 llvm::Metadata *Args[2] = {
1708 llvm::MDString::get(Context,
"-framework"),
1709 llvm::MDString::get(Context, Mod->
LinkLibraries[I - 1].Library)};
1711 Metadata.push_back(llvm::MDNode::get(Context, Args));
1716 if (IsELF && !IsPS4) {
1717 llvm::Metadata *Args[2] = {
1718 llvm::MDString::get(Context,
"lib"),
1719 llvm::MDString::get(Context, Mod->
LinkLibraries[I - 1].Library),
1721 Metadata.push_back(llvm::MDNode::get(Context, Args));
1726 auto *OptString = llvm::MDString::get(Context, Opt);
1727 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1732 void CodeGenModule::EmitModuleLinkOptions() {
1736 llvm::SetVector<clang::Module *> LinkModules;
1737 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1741 for (
Module *M : ImportedModules) {
1747 if (Visited.insert(M).second)
1753 while (!Stack.empty()) {
1756 bool AnyChildren =
false;
1765 if (Visited.insert(
SM).second) {
1766 Stack.push_back(
SM);
1774 LinkModules.insert(Mod);
1783 for (
Module *M : LinkModules)
1784 if (Visited.insert(M).second)
1786 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1787 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1790 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
1791 for (
auto *MD : LinkerOptionsMetadata)
1792 NMD->addOperand(MD);
1795 void CodeGenModule::EmitDeferred() {
1804 if (!DeferredVTables.empty()) {
1805 EmitDeferredVTables();
1810 assert(DeferredVTables.empty());
1814 if (DeferredDeclsToEmit.empty())
1819 std::vector<GlobalDecl> CurDeclsToEmit;
1820 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1827 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1845 if (!GV->isDeclaration())
1849 EmitGlobalDefinition(D, GV);
1854 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1856 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1861 void CodeGenModule::EmitVTablesOpportunistically() {
1867 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1868 &&
"Only emit opportunistic vtables with optimizations");
1872 "This queue should only contain external vtables");
1873 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
1876 OpportunisticVTables.clear();
1880 if (Annotations.empty())
1884 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1885 Annotations[0]->getType(), Annotations.size()), Annotations);
1886 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
1887 llvm::GlobalValue::AppendingLinkage,
1888 Array,
"llvm.global.annotations");
1889 gv->setSection(AnnotationSection);
1893 llvm::Constant *&AStr = AnnotationStrings[Str];
1898 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
1900 new llvm::GlobalVariable(
getModule(), s->getType(),
true,
1901 llvm::GlobalValue::PrivateLinkage, s,
".str");
1902 gv->setSection(AnnotationSection);
1903 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1921 return llvm::ConstantInt::get(
Int32Ty, LineNo);
1925 const AnnotateAttr *AA,
1933 llvm::Constant *Fields[4] = {
1934 llvm::ConstantExpr::getBitCast(GV,
Int8PtrTy),
1935 llvm::ConstantExpr::getBitCast(AnnoGV,
Int8PtrTy),
1936 llvm::ConstantExpr::getBitCast(UnitGV,
Int8PtrTy),
1939 return llvm::ConstantStruct::getAnon(Fields);
1943 llvm::GlobalValue *GV) {
1944 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1955 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1964 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1974 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1975 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
1976 if (!EnabledAsanMask)
1979 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(),
Category))
1981 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1987 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
1988 Ty = AT->getElementType();
1993 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
2004 auto Attr = ImbueAttr::NONE;
2006 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2007 if (
Attr == ImbueAttr::NONE)
2008 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2010 case ImbueAttr::NONE:
2012 case ImbueAttr::ALWAYS:
2013 Fn->addFnAttr(
"function-instrument",
"xray-always");
2015 case ImbueAttr::ALWAYS_ARG1:
2016 Fn->addFnAttr(
"function-instrument",
"xray-always");
2017 Fn->addFnAttr(
"xray-log-args",
"1");
2019 case ImbueAttr::NEVER:
2020 Fn->addFnAttr(
"function-instrument",
"xray-never");
2026 bool CodeGenModule::MustBeEmitted(
const ValueDecl *Global) {
2028 if (LangOpts.EmitAllDecls)
2031 if (CodeGenOpts.KeepStaticConsts) {
2032 const auto *VD = dyn_cast<
VarDecl>(Global);
2033 if (VD && VD->getType().isConstQualified() &&
2041 bool CodeGenModule::MayBeEmittedEagerly(
const ValueDecl *Global) {
2042 if (
const auto *FD = dyn_cast<FunctionDecl>(Global))
2047 if (
const auto *VD = dyn_cast<VarDecl>(Global))
2055 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2058 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2069 std::string Name =
"_GUID_" + Uuid.lower();
2070 std::replace(Name.begin(), Name.end(),
'-',
'_');
2076 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
2079 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2080 assert(Init &&
"failed to initialize as constant");
2082 auto *GV =
new llvm::GlobalVariable(
2084 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2086 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2092 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
2093 assert(AA &&
"No alias?");
2102 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2106 llvm::Constant *Aliasee;
2107 if (isa<llvm::FunctionType>(DeclTy))
2108 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2112 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2113 llvm::PointerType::getUnqual(DeclTy),
2116 auto *F = cast<llvm::GlobalValue>(Aliasee);
2117 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2118 WeakRefReferences.insert(F);
2124 const auto *Global = cast<ValueDecl>(GD.
getDecl());
2127 if (Global->
hasAttr<WeakRefAttr>())
2132 if (Global->
hasAttr<AliasAttr>())
2133 return EmitAliasDefinition(GD);
2136 if (Global->
hasAttr<IFuncAttr>())
2137 return emitIFuncDefinition(GD);
2140 if (Global->
hasAttr<CPUDispatchAttr>())
2141 return emitCPUDispatchDefinition(GD);
2144 if (LangOpts.CUDA) {
2145 if (LangOpts.CUDAIsDevice) {
2146 if (!Global->
hasAttr<CUDADeviceAttr>() &&
2147 !Global->
hasAttr<CUDAGlobalAttr>() &&
2148 !Global->
hasAttr<CUDAConstantAttr>() &&
2149 !Global->
hasAttr<CUDASharedAttr>())
2158 if (isa<FunctionDecl>(Global) && !Global->
hasAttr<CUDAHostAttr>() &&
2159 Global->
hasAttr<CUDADeviceAttr>())
2162 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2163 "Expected Variable or Function");
2167 if (LangOpts.OpenMP) {
2170 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2172 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2173 if (MustBeEmitted(Global))
2180 if (
const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2192 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
2197 const auto *VD = cast<VarDecl>(Global);
2198 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
2201 if (LangOpts.OpenMP) {
2204 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2205 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2208 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
2209 "link claue expected.");
2227 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2229 EmitGlobalDefinition(GD);
2236 cast<VarDecl>(Global)->hasInit()) {
2237 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2238 CXXGlobalInits.push_back(
nullptr);
2244 addDeferredDeclToEmit(GD);
2245 }
else if (MustBeEmitted(Global)) {
2247 assert(!MayBeEmittedEagerly(Global));
2248 addDeferredDeclToEmit(GD);
2253 DeferredDecls[MangledName] = GD;
2260 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2261 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2268 struct FunctionIsDirectlyRecursive :
2270 const StringRef Name;
2274 Name(N), BI(C), Result(
false) {
2278 bool TraverseCallExpr(
CallExpr *E) {
2283 if (Attr && Name == Attr->getLabel()) {
2290 StringRef BuiltinName = BI.
getName(BuiltinID);
2291 if (BuiltinName.startswith(
"__builtin_") &&
2292 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
2301 struct DLLImportFunctionVisitor
2303 bool SafeToInline =
true;
2305 bool shouldVisitImplicitCode()
const {
return true; }
2307 bool VisitVarDecl(
VarDecl *VD) {
2310 SafeToInline =
false;
2311 return SafeToInline;
2318 return SafeToInline;
2323 SafeToInline = D->hasAttr<DLLImportAttr>();
2324 return SafeToInline;
2329 if (isa<FunctionDecl>(VD))
2330 SafeToInline = VD->
hasAttr<DLLImportAttr>();
2331 else if (
VarDecl *V = dyn_cast<VarDecl>(VD))
2332 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2333 return SafeToInline;
2338 return SafeToInline;
2345 SafeToInline =
true;
2347 SafeToInline = M->
hasAttr<DLLImportAttr>();
2349 return SafeToInline;
2354 return SafeToInline;
2359 return SafeToInline;
2368 CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
2370 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2375 Name = Attr->getLabel();
2380 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
2381 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2382 return Walker.Result;
2385 bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
2388 const auto *F = cast<FunctionDecl>(GD.
getDecl());
2389 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2392 if (F->hasAttr<DLLImportAttr>()) {
2394 DLLImportFunctionVisitor Visitor;
2395 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2396 if (!Visitor.SafeToInline)
2402 for (
const Decl *Member : Dtor->getParent()->decls())
2403 if (isa<FieldDecl>(Member))
2417 return !isTriviallyRecursive(F);
2420 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2421 return CodeGenOpts.OptimizationLevel > 0;
2424 void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
2425 llvm::GlobalValue *GV) {
2426 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2429 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
2430 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
2434 EmitGlobalFunctionDefinition(GD, GV);
2437 void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
2438 const auto *D = cast<ValueDecl>(GD.
getDecl());
2442 "Generating code for declaration");
2444 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
2447 if (!shouldEmitFunction(GD))
2450 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2453 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2455 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2458 EmitMultiVersionFunctionDefinition(GD, GV);
2460 EmitGlobalFunctionDefinition(GD, GV);
2462 if (Method->isVirtual())
2469 return EmitMultiVersionFunctionDefinition(GD, GV);
2470 return EmitGlobalFunctionDefinition(GD, GV);
2473 if (
const auto *VD = dyn_cast<VarDecl>(D))
2474 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2476 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
2480 llvm::Function *NewFn);
2485 unsigned Priority = 0;
2495 void CodeGenModule::emitMultiVersionFunctions() {
2507 EmitGlobalFunctionDefinition(CurGD,
nullptr);
2516 assert(Func &&
"This should have just been created");
2519 const auto *TA = CurFD->
getAttr<TargetAttr>();
2521 TA->getAddedFeatures(Feats);
2523 Options.emplace_back(cast<llvm::Function>(Func),
2524 TA->getArchitecture(), Feats);
2527 llvm::Function *ResolverFunc;
2531 ResolverFunc = cast<llvm::Function>(
2537 ResolverFunc->setComdat(
2538 getModule().getOrInsertComdat(ResolverFunc->getName()));
2541 Options.begin(), Options.end(),
2547 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2551 void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
2552 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2553 assert(FD &&
"Not a FunctionDecl?");
2554 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
2555 assert(DD &&
"Not a cpu_dispatch Function?");
2559 if (
const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2569 ResolverType = llvm::FunctionType::get(
2570 llvm::PointerType::get(DeclTy,
2574 ResolverType = DeclTy;
2578 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2579 ResolverName, ResolverType, ResolverGD,
false));
2592 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2595 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
2601 Func = GetOrCreateLLVMFunction(
2602 MangledName, DeclTy, ExistingDecl,
2610 llvm::transform(Features, Features.begin(),
2611 [](StringRef Str) {
return Str.substr(1); });
2612 Features.erase(std::remove_if(
2613 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2615 }), Features.end());
2616 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
2631 while (Options.size() > 1 &&
2633 (Options.end() - 2)->Conditions.Features) == 0) {
2634 StringRef LHSName = (Options.end() - 2)->Function->getName();
2635 StringRef RHSName = (Options.end() - 1)->Function->getName();
2636 if (LHSName.compare(RHSName) < 0)
2637 Options.erase(Options.end() - 2);
2639 Options.erase(Options.end() - 1);
2648 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2650 std::string MangledName =
2655 std::string ResolverName = MangledName;
2657 ResolverName +=
".ifunc";
2659 ResolverName +=
".resolver";
2662 if (llvm::GlobalValue *ResolverGV =
GetGlobalValue(ResolverName))
2669 MultiVersionFuncs.push_back(GD);
2672 llvm::Type *ResolverType = llvm::FunctionType::get(
2673 llvm::PointerType::get(
2676 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2677 MangledName +
".resolver", ResolverType,
GlobalDecl{},
2681 GIF->setName(ResolverName);
2687 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2689 assert(isa<llvm::GlobalValue>(Resolver) &&
2690 "Resolver should be created for the first time");
2702 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2704 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
2710 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2712 if (
getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2713 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
2714 !DontDefer && !IsForDefinition) {
2717 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2719 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2728 const auto *TA = FD->
getAttr<TargetAttr>();
2729 if (TA && TA->isDefaultVersion())
2730 UpdateMultiVersionNames(GD, FD);
2731 if (!IsForDefinition)
2732 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
2739 if (WeakRefReferences.erase(Entry)) {
2740 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2741 if (FD && !FD->
hasAttr<WeakAttr>())
2746 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>()) {
2747 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2753 if (IsForDefinition && !Entry->isDeclaration()) {
2760 DiagnosedConflictingDefinitions.insert(GD).second) {
2764 diag::note_previous_definition);
2768 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2769 (Entry->getType()->getElementType() == Ty)) {
2776 if (!IsForDefinition)
2777 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2783 bool IsIncompleteFunction =
false;
2785 llvm::FunctionType *FTy;
2786 if (isa<llvm::FunctionType>(Ty)) {
2787 FTy = cast<llvm::FunctionType>(Ty);
2789 FTy = llvm::FunctionType::get(
VoidTy,
false);
2790 IsIncompleteFunction =
true;
2795 Entry ? StringRef() : MangledName, &
getModule());
2812 if (!Entry->use_empty()) {
2814 Entry->removeDeadConstantUsers();
2817 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2818 F, Entry->getType()->getElementType()->getPointerTo());
2822 assert(F->getName() == MangledName &&
"name was uniqued!");
2824 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2825 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2826 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2827 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2834 if (D && isa<CXXDestructorDecl>(D) &&
2835 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2837 addDeferredDeclToEmit(GD);
2842 auto DDI = DeferredDecls.find(MangledName);
2843 if (DDI != DeferredDecls.end()) {
2847 addDeferredDeclToEmit(DDI->second);
2848 DeferredDecls.erase(DDI);
2863 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2876 if (!IsIncompleteFunction) {
2877 assert(F->getType()->getElementType() == Ty);
2881 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2882 return llvm::ConstantExpr::getBitCast(F, PTy);
2895 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2903 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
2906 DD->getParent()->getNumVBases() == 0)
2911 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2912 false, llvm::AttributeList(),
2922 for (
const auto &Result : DC->
lookup(&CII))
2923 if (
const auto FD = dyn_cast<FunctionDecl>(Result))
2931 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
2935 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
2937 for (
const auto &Result : DC->
lookup(&NS)) {
2939 if (
auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2940 for (
const auto &Result : LSD->lookup(&NS))
2941 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2945 for (
const auto &Result : ND->
lookup(&CXXII))
2946 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
2958 llvm::AttributeList ExtraAttrs,
2961 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2965 if (
auto *F = dyn_cast<llvm::Function>(C)) {
2969 if (!Local &&
getTriple().isOSBinFormatCOFF() &&
2971 !
getTriple().isWindowsGNUEnvironment()) {
2973 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
2974 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2989 llvm::AttributeList ExtraAttrs) {
3006 return ExcludeCtor && !Record->hasMutableFields() &&
3007 Record->hasTrivialDestructor();
3025 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3026 llvm::PointerType *Ty,
3032 if (WeakRefReferences.erase(Entry)) {
3033 if (D && !D->
hasAttr<WeakAttr>())
3038 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
3039 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3041 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3044 if (Entry->getType() == Ty)
3049 if (IsForDefinition && !Entry->isDeclaration()) {
3057 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
3059 DiagnosedConflictingDefinitions.insert(D).second) {
3063 diag::note_previous_definition);
3068 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3069 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3073 if (!IsForDefinition)
3074 return llvm::ConstantExpr::getBitCast(Entry, Ty);
3080 auto *GV =
new llvm::GlobalVariable(
3081 getModule(), Ty->getElementType(),
false,
3083 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3088 GV->takeName(Entry);
3090 if (!Entry->use_empty()) {
3091 llvm::Constant *NewPtrForOldDecl =
3092 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3093 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3096 Entry->eraseFromParent();
3102 auto DDI = DeferredDecls.find(MangledName);
3103 if (DDI != DeferredDecls.end()) {
3106 addDeferredDeclToEmit(DDI->second);
3107 DeferredDecls.erase(DDI);
3112 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3125 CXXThreadLocals.push_back(D);
3133 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
3134 EmitGlobalVarDefinition(D);
3139 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
3140 GV->setSection(SA->getName());
3144 if (
getTriple().getArch() == llvm::Triple::xcore &&
3148 GV->setSection(
".cp.rodata");
3153 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3156 const auto *Record =
3158 bool HasMutableFields = Record && Record->hasMutableFields();
3159 if (!HasMutableFields) {
3166 auto *InitType = Init->getType();
3167 if (GV->getType()->getElementType() != InitType) {
3172 GV->setName(StringRef());
3175 auto *NewGV = cast<llvm::GlobalVariable>(
3179 GV->eraseFromParent();
3182 GV->setInitializer(Init);
3183 GV->setConstant(
true);
3184 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3196 assert(
getContext().getTargetAddressSpace(ExpectedAS) ==
3197 Ty->getPointerAddressSpace());
3198 if (AddrSpace != ExpectedAS)
3209 if (isa<CXXConstructorDecl>(D))
3213 false, IsForDefinition);
3214 else if (isa<CXXDestructorDecl>(D))
3218 false, IsForDefinition);
3219 else if (isa<CXXMethodDecl>(D)) {
3221 cast<CXXMethodDecl>(D));
3225 }
else if (isa<FunctionDecl>(D)) {
3237 unsigned Alignment) {
3238 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
3239 llvm::GlobalVariable *OldGV =
nullptr;
3243 if (GV->getType()->getElementType() == Ty)
3248 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
3253 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
3254 Linkage,
nullptr, Name);
3258 GV->takeName(OldGV);
3260 if (!OldGV->use_empty()) {
3261 llvm::Constant *NewPtrForOldDecl =
3262 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3263 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3266 OldGV->eraseFromParent();
3270 !GV->hasAvailableExternallyLinkage())
3271 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3273 GV->setAlignment(Alignment);
3292 llvm::PointerType *PTy =
3293 llvm::PointerType::get(Ty,
getContext().getTargetAddressSpace(ASTTy));
3296 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3305 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty),
nullptr);
3306 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3311 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
3319 if (GV && !GV->isDeclaration())
3324 if (!MustBeEmitted(D) && !GV) {
3325 DeferredDecls[MangledName] = D;
3330 EmitGlobalVarDefinition(D);
3340 if (LangOpts.OpenCL) {
3349 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3350 if (D && D->
hasAttr<CUDAConstantAttr>())
3352 else if (D && D->
hasAttr<CUDASharedAttr>())
3354 else if (D && D->
hasAttr<CUDADeviceAttr>())
3367 if (LangOpts.OpenCL)
3369 if (
auto AS =
getTarget().getConstantAddressSpace())
3370 return AS.getValue();
3382 static llvm::Constant *
3384 llvm::GlobalVariable *GV) {
3385 llvm::Constant *Cast = GV;
3391 GV->getValueType()->getPointerTo(
3398 template<
typename SomeDecl>
3400 llvm::GlobalValue *GV) {
3406 if (!D->template hasAttr<UsedAttr>())
3415 const SomeDecl *
First = D->getFirstDecl();
3416 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3422 std::pair<StaticExternCMap::iterator, bool> R =
3423 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3428 R.first->second =
nullptr;
3435 if (D.
hasAttr<SelectAnyAttr>())
3439 if (
auto *VD = dyn_cast<VarDecl>(&D))
3453 llvm_unreachable(
"No such linkage");
3457 llvm::GlobalObject &GO) {
3460 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3464 void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
3474 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3475 OpenMPRuntime->emitTargetGlobalVariable(D))
3478 llvm::Constant *Init =
nullptr;
3480 bool NeedsGlobalCtor =
false;
3491 bool IsCUDASharedVar =
3495 bool IsCUDAShadowVar =
3497 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
3498 D->
hasAttr<CUDASharedAttr>());
3499 if (
getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
3500 Init = llvm::UndefValue::get(
getTypes().ConvertType(ASTTy));
3501 else if (!InitExpr) {
3515 emitter.emplace(*
this);
3516 Init = emitter->tryEmitForInitializer(*InitDecl);
3525 NeedsGlobalCtor =
true;
3528 Init = llvm::UndefValue::get(
getTypes().ConvertType(T));
3535 DelayedCXXInitPosition.erase(D);
3540 llvm::Constant *Entry =
3544 if (
auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3545 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3546 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3548 CE->getOpcode() == llvm::Instruction::GetElementPtr);
3549 Entry = CE->getOperand(0);
3553 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3564 if (!GV || GV->getType()->getElementType() != InitType ||
3565 GV->getType()->getAddressSpace() !=
3569 Entry->setName(StringRef());
3572 GV = cast<llvm::GlobalVariable>(
3576 llvm::Constant *NewPtrForOldDecl =
3577 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3578 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3581 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3586 if (D->
hasAttr<AnnotateAttr>())
3590 llvm::GlobalValue::LinkageTypes
Linkage =
3600 if (GV && LangOpts.CUDA) {
3601 if (LangOpts.CUDAIsDevice) {
3602 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>())
3603 GV->setExternallyInitialized(
true);
3609 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>()) {
3617 if (D->
hasAttr<CUDAConstantAttr>())
3623 }
else if (D->
hasAttr<CUDASharedAttr>())
3633 GV->setInitializer(Init);
3634 if (emitter) emitter->finalize(GV);
3637 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3641 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
3644 GV->setConstant(
true);
3659 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3660 !llvm::GlobalVariable::isWeakLinkage(Linkage))
3663 GV->setLinkage(Linkage);
3664 if (D->
hasAttr<DLLImportAttr>())
3665 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3666 else if (D->
hasAttr<DLLExportAttr>())
3667 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3669 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3671 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3673 GV->setConstant(
false);
3678 if (!GV->getInitializer()->isNullValue())
3679 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3682 setNonAliasAttributes(D, GV);
3684 if (D->
getTLSKind() && !GV->isThreadLocal()) {
3686 CXXThreadLocals.push_back(D);
3693 if (NeedsGlobalCtor || NeedsGlobalDtor)
3694 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3696 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3701 DI->EmitGlobalVariable(GV, D);
3709 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
3720 if (D->
hasAttr<SectionAttr>())
3726 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
3727 D->
hasAttr<PragmaClangDataSectionAttr>() ||
3728 D->
hasAttr<PragmaClangRodataSectionAttr>())
3736 if (D->
hasAttr<WeakImportAttr>())
3746 if (D->
hasAttr<AlignedAttr>())
3755 if (FD->isBitField())
3757 if (FD->
hasAttr<AlignedAttr>())
3785 if (IsConstantVariable)
3786 return llvm::GlobalVariable::WeakODRLinkage;
3788 return llvm::GlobalVariable::WeakAnyLinkage;
3793 return llvm::GlobalVariable::LinkOnceAnyLinkage;
3798 return llvm::GlobalValue::AvailableExternallyLinkage;
3812 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3829 return llvm::Function::WeakODRLinkage;
3834 if (!
getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3836 CodeGenOpts.NoCommon))
3837 return llvm::GlobalVariable::CommonLinkage;
3843 if (D->
hasAttr<SelectAnyAttr>())
3844 return llvm::GlobalVariable::WeakODRLinkage;
3852 const VarDecl *VD,
bool IsConstant) {
3860 llvm::Function *newFn) {
3862 if (old->use_empty())
return;
3864 llvm::Type *newRetTy = newFn->getReturnType();
3868 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3870 llvm::Value::use_iterator use = ui++;
3871 llvm::User *user = use->getUser();
3875 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3876 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3882 llvm::CallSite callSite(user);
3883 if (!callSite)
continue;
3884 if (!callSite.isCallee(&*use))
continue;
3888 if (callSite->getType() != newRetTy && !callSite->use_empty())
3893 llvm::AttributeList oldAttrs = callSite.getAttributes();
3896 unsigned newNumArgs = newFn->arg_size();
3897 if (callSite.arg_size() < newNumArgs)
continue;
3902 bool dontTransform =
false;
3903 for (llvm::Argument &A : newFn->args()) {
3904 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3905 dontTransform =
true;
3910 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3918 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3921 callSite.getOperandBundlesAsDefs(newBundles);
3923 llvm::CallSite newCall;
3924 if (callSite.isCall()) {
3926 callSite.getInstruction());
3928 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3930 oldInvoke->getNormalDest(),
3931 oldInvoke->getUnwindDest(),
3932 newArgs, newBundles,
"",
3933 callSite.getInstruction());
3937 if (!newCall->getType()->isVoidTy())
3938 newCall->takeName(callSite.getInstruction());
3939 newCall.setAttributes(llvm::AttributeList::get(
3940 newFn->getContext(), oldAttrs.getFnAttributes(),
3941 oldAttrs.getRetAttributes(), newArgAttrs));
3942 newCall.setCallingConv(callSite.getCallingConv());
3945 if (!callSite->use_empty())
3946 callSite->replaceAllUsesWith(newCall.getInstruction());
3949 if (callSite->getDebugLoc())
3950 newCall->setDebugLoc(callSite->getDebugLoc());
3952 callSite->eraseFromParent();
3966 llvm::Function *NewFn) {
3968 if (!isa<llvm::Function>(Old))
return;
3987 void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
3988 llvm::GlobalValue *GV) {
3989 const auto *D = cast<FunctionDecl>(GD.
getDecl());
3996 if (!GV || (GV->getType()->getElementType() != Ty))
4002 if (!GV->isDeclaration())
4009 auto *Fn = cast<llvm::Function>(GV);
4022 setNonAliasAttributes(GD, Fn);
4025 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
4026 AddGlobalCtor(Fn, CA->getPriority());
4027 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
4028 AddGlobalDtor(Fn, DA->getPriority());
4029 if (D->
hasAttr<AnnotateAttr>())
4033 void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
4034 const auto *D = cast<ValueDecl>(GD.
getDecl());
4035 const AliasAttr *AA = D->
getAttr<AliasAttr>();
4036 assert(AA &&
"Not an alias?");
4040 if (AA->getAliasee() == MangledName) {
4041 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4048 if (Entry && !Entry->isDeclaration())
4051 Aliases.push_back(GD);
4057 llvm::Constant *Aliasee;
4058 if (isa<llvm::FunctionType>(DeclTy))
4059 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4062 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4063 llvm::PointerType::getUnqual(DeclTy),
4071 if (GA->getAliasee() == Entry) {
4072 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4076 assert(Entry->isDeclaration());
4085 GA->takeName(Entry);
4087 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4089 Entry->eraseFromParent();
4091 GA->setName(MangledName);
4099 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4102 if (
const auto *VD = dyn_cast<VarDecl>(D))
4103 if (VD->getTLSKind())
4109 void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
4110 const auto *D = cast<ValueDecl>(GD.
getDecl());
4111 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
4112 assert(IFA &&
"Not an ifunc?");
4116 if (IFA->getResolver() == MangledName) {
4117 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4123 if (Entry && !Entry->isDeclaration()) {
4126 DiagnosedConflictingDefinitions.insert(GD).second) {
4127 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
4130 diag::note_previous_definition);
4135 Aliases.push_back(GD);
4138 llvm::Constant *Resolver =
4139 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4141 llvm::GlobalIFunc *GIF =
4145 if (GIF->getResolver() == Entry) {
4146 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4149 assert(Entry->isDeclaration());
4158 GIF->takeName(Entry);
4160 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4162 Entry->eraseFromParent();
4164 GIF->setName(MangledName);
4175 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4178 bool &IsUTF16,
unsigned &StringLength) {
4179 StringRef String = Literal->
getString();
4180 unsigned NumBytes = String.size();
4184 StringLength = NumBytes;
4185 return *Map.insert(std::make_pair(String,
nullptr)).first;
4192 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
4193 llvm::UTF16 *ToPtr = &ToBuf[0];
4195 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4196 ToPtr + NumBytes, llvm::strictConversion);
4199 StringLength = ToPtr - &ToBuf[0];
4203 return *Map.insert(std::make_pair(
4204 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4205 (StringLength + 1) * 2),
4211 unsigned StringLength = 0;
4212 bool isUTF16 =
false;
4213 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4218 if (
auto *C = Entry.second)
4221 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
4222 llvm::Constant *Zeros[] = { Zero, Zero };
4225 const llvm::Triple &Triple =
getTriple();
4228 const bool IsSwiftABI =
4229 static_cast<unsigned>(CFRuntime) >=
4234 if (!CFConstantStringClassRef) {
4235 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
4237 Ty = llvm::ArrayType::get(Ty, 0);
4239 switch (CFRuntime) {
4243 CFConstantStringClassName =
4244 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN" 4245 :
"$s10Foundation19_NSCFConstantStringCN";
4249 CFConstantStringClassName =
4250 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN" 4251 :
"$S10Foundation19_NSCFConstantStringCN";
4255 CFConstantStringClassName =
4256 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN" 4257 :
"__T010Foundation19_NSCFConstantStringCN";
4264 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4265 llvm::GlobalValue *GV =
nullptr;
4267 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4273 for (
const auto &Result : DC->
lookup(&II))
4274 if ((VD = dyn_cast<VarDecl>(Result)))
4277 if (Triple.isOSBinFormatELF()) {
4282 if (!VD || !VD->
hasAttr<DLLExportAttr>())
4283 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4285 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4293 CFConstantStringClassRef =
4294 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4295 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4303 auto Fields = Builder.beginStruct(STy);
4306 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4310 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4311 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4313 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4317 llvm::Constant *C =
nullptr;
4319 auto Arr = llvm::makeArrayRef(
4320 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4321 Entry.first().size() / 2);
4322 C = llvm::ConstantDataArray::get(VMContext, Arr);
4324 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4330 new llvm::GlobalVariable(
getModule(), C->getType(),
true,
4331 llvm::GlobalValue::PrivateLinkage, C,
".str");
4332 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4342 if (Triple.isOSBinFormatMachO())
4343 GV->setSection(isUTF16 ?
"__TEXT,__ustring" 4344 :
"__TEXT,__cstring,cstring_literals");
4347 else if (Triple.isOSBinFormatELF())
4348 GV->setSection(
".rodata");
4351 llvm::Constant *Str =
4352 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4356 Str = llvm::ConstantExpr::getBitCast(Str,
Int8PtrTy);
4360 llvm::IntegerType *LengthTy =
4370 Fields.addInt(LengthTy, StringLength);
4375 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
4377 llvm::GlobalVariable::PrivateLinkage);
4378 switch (Triple.getObjectFormat()) {
4379 case llvm::Triple::UnknownObjectFormat:
4380 llvm_unreachable(
"unknown file format");
4381 case llvm::Triple::COFF:
4382 case llvm::Triple::ELF:
4383 case llvm::Triple::Wasm:
4384 GV->setSection(
"cfstring");
4386 case llvm::Triple::MachO:
4387 GV->setSection(
"__DATA,__cfstring");
4396 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4400 if (ObjCFastEnumerationStateType.isNull()) {
4412 for (
size_t i = 0; i < 4; ++i) {
4417 FieldTypes[i],
nullptr,
4429 return ObjCFastEnumerationStateType;
4443 Str.resize(CAT->getSize().getZExtValue());
4444 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
4448 llvm::Type *ElemTy = AType->getElementType();
4449 unsigned NumElements = AType->getNumElements();
4452 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4454 Elements.reserve(NumElements);
4456 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
4458 Elements.resize(NumElements);
4459 return llvm::ConstantDataArray::get(VMContext, Elements);
4462 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4464 Elements.reserve(NumElements);
4466 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
4468 Elements.resize(NumElements);
4469 return llvm::ConstantDataArray::get(VMContext, Elements);
4472 static llvm::GlobalVariable *
4481 auto *GV =
new llvm::GlobalVariable(
4482 M, C->getType(), !CGM.
getLangOpts().WritableStrings,
LT, C, GlobalName,
4483 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4485 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4486 if (GV->isWeakForLinker()) {
4487 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
4488 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4503 llvm::GlobalVariable **Entry =
nullptr;
4504 if (!LangOpts.WritableStrings) {
4505 Entry = &ConstantStringMap[C];
4506 if (
auto GV = *Entry) {
4514 StringRef GlobalVariableName;
4515 llvm::GlobalValue::LinkageTypes
LT;
4520 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4521 !LangOpts.WritableStrings) {
4522 llvm::raw_svector_ostream Out(MangledNameBuffer);
4524 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4525 GlobalVariableName = MangledNameBuffer;
4527 LT = llvm::GlobalValue::PrivateLinkage;
4528 GlobalVariableName = Name;
4535 SanitizerMD->reportGlobalToASan(GV, S->
getStrTokenLoc(0),
"<string literal>",
4556 const std::string &Str,
const char *GlobalName) {
4557 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4562 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
4565 llvm::GlobalVariable **Entry =
nullptr;
4566 if (!LangOpts.WritableStrings) {
4567 Entry = &ConstantStringMap[C];
4568 if (
auto GV = *Entry) {
4569 if (Alignment.getQuantity() > GV->getAlignment())
4570 GV->setAlignment(Alignment.getQuantity());
4577 GlobalName =
".str";
4580 GlobalName, Alignment);
4598 MaterializedType = E->
getType();
4602 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4609 llvm::raw_svector_ostream Out(Name);
4611 VD, E->getManglingNumber(), Out);
4614 if (E->getStorageDuration() ==
SD_Static) {
4628 Value = &EvalResult.
Val;
4634 llvm::Constant *InitialValue =
nullptr;
4635 bool Constant =
false;
4639 emitter.emplace(*
this);
4640 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4643 Type = InitialValue->getType();
4651 llvm::GlobalValue::LinkageTypes
Linkage =
4655 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4659 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4667 auto *GV =
new llvm::GlobalVariable(
4668 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4669 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4670 if (emitter) emitter->finalize(GV);
4674 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4675 if (VD->getTLSKind())
4677 llvm::Constant *CV = GV;
4683 MaterializedGlobalTemporaryMap[E] = CV;
4689 void CodeGenModule::EmitObjCPropertyImplementations(
const 4703 const_cast<ObjCImplementationDecl *>(D), PID);
4707 const_cast<ObjCImplementationDecl *>(D), PID);
4716 if (ivar->getType().isDestructedType())
4786 EmitDeclContext(LSD);
4789 void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
4790 for (
auto *I : DC->
decls()) {
4796 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4797 for (
auto *M : OID->methods())
4812 case Decl::CXXConversion:
4813 case Decl::CXXMethod:
4821 case Decl::CXXDeductionGuide:
4826 case Decl::Decomposition:
4827 case Decl::VarTemplateSpecialization:
4829 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
4830 for (
auto *B : DD->bindings())
4831 if (
auto *HD = B->getHoldingVar())
4837 case Decl::IndirectField:
4841 case Decl::Namespace:
4842 EmitDeclContext(cast<NamespaceDecl>(D));
4844 case Decl::ClassTemplateSpecialization: {
4845 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4848 Spec->hasDefinition())
4849 DebugInfo->completeTemplateDefinition(*Spec);
4851 case Decl::CXXRecord:
4855 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4858 for (
auto *I : cast<CXXRecordDecl>(D)->decls())
4859 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4863 case Decl::UsingShadow:
4864 case Decl::ClassTemplate:
4865 case Decl::VarTemplate:
4866 case Decl::VarTemplatePartialSpecialization:
4867 case Decl::FunctionTemplate:
4868 case Decl::TypeAliasTemplate:
4875 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4877 case Decl::NamespaceAlias:
4879 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4881 case Decl::UsingDirective:
4883 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4885 case Decl::CXXConstructor:
4888 case Decl::CXXDestructor:
4892 case Decl::StaticAssert:
4899 case Decl::ObjCInterface:
4900 case Decl::ObjCCategory:
4903 case Decl::ObjCProtocol: {
4904 auto *Proto = cast<ObjCProtocolDecl>(D);
4905 if (Proto->isThisDeclarationADefinition())
4910 case Decl::ObjCCategoryImpl:
4913 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4916 case Decl::ObjCImplementation: {
4917 auto *OMD = cast<ObjCImplementationDecl>(D);
4918 EmitObjCPropertyImplementations(OMD);
4919 EmitObjCIvarInitializations(OMD);
4924 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
4925 OMD->getClassInterface()), OMD->getLocation());
4928 case Decl::ObjCMethod: {
4929 auto *OMD = cast<ObjCMethodDecl>(D);
4935 case Decl::ObjCCompatibleAlias:
4936 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4939 case Decl::PragmaComment: {
4940 const auto *PCD = cast<PragmaCommentDecl>(D);
4941 switch (PCD->getCommentKind()) {
4943 llvm_unreachable(
"unexpected pragma comment kind");
4962 case Decl::PragmaDetectMismatch: {
4963 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4968 case Decl::LinkageSpec:
4969 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4972 case Decl::FileScopeAsm: {
4974 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4977 if (LangOpts.OpenMPIsDevice)
4979 auto *AD = cast<FileScopeAsmDecl>(D);
4980 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4984 case Decl::Import: {
4985 auto *Import = cast<ImportDecl>(D);
4988 if (!ImportedModules.insert(Import->getImportedModule()))
4992 if (!Import->getImportedOwningModule()) {
4994 DI->EmitImportDecl(*Import);
4998 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5000 Visited.insert(Import->getImportedModule());
5001 Stack.push_back(Import->getImportedModule());
5003 while (!Stack.empty()) {
5005 if (!EmittedModuleInitializers.insert(Mod).second)
5014 Sub != SubEnd; ++Sub) {
5017 if ((*Sub)->IsExplicit)
5020 if (Visited.insert(*Sub).second)
5021 Stack.push_back(*Sub);
5028 EmitDeclContext(cast<ExportDecl>(D));
5031 case Decl::OMPThreadPrivate:
5035 case Decl::OMPDeclareReduction:
5039 case Decl::OMPRequires:
5047 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
5054 if (!CodeGenOpts.CoverageMapping)
5057 case Decl::CXXConversion:
5058 case Decl::CXXMethod:
5060 case Decl::ObjCMethod:
5061 case Decl::CXXConstructor:
5062 case Decl::CXXDestructor: {
5063 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5068 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5069 if (I == DeferredEmptyCoverageMappingDecls.end())
5070 DeferredEmptyCoverageMappingDecls[D] =
true;
5080 if (!CodeGenOpts.CoverageMapping)
5082 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5083 if (Fn->isTemplateInstantiation())
5086 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5087 if (I == DeferredEmptyCoverageMappingDecls.end())
5088 DeferredEmptyCoverageMappingDecls[D] =
false;
5098 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5101 const Decl *D = Entry.first;
5103 case Decl::CXXConversion:
5104 case Decl::CXXMethod:
5106 case Decl::ObjCMethod: {
5113 case Decl::CXXConstructor: {
5120 case Decl::CXXDestructor: {
5137 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5138 return llvm::ConstantInt::get(i64, PtrInt);
5142 llvm::NamedMDNode *&GlobalMetadata,
5144 llvm::GlobalValue *Addr) {
5145 if (!GlobalMetadata)
5147 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
5150 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5153 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
5161 void CodeGenModule::EmitStaticExternCAliases() {
5164 for (
auto &I : StaticExternCValues) {
5166 llvm::GlobalValue *Val = I.second;
5174 auto Res = Manglings.find(MangledName);
5175 if (Res == Manglings.end())
5177 Result = Res->getValue();
5188 void CodeGenModule::EmitDeclMetadata() {
5189 llvm::NamedMDNode *GlobalMetadata =
nullptr;
5191 for (
auto &I : MangledDeclNames) {
5192 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
5202 void CodeGenFunction::EmitDeclMetadata() {
5203 if (LocalDeclMap.empty())
return;
5208 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
5210 llvm::NamedMDNode *GlobalMetadata =
nullptr;
5212 for (
auto &I : LocalDeclMap) {
5213 const Decl *D = I.first;
5215 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5217 Alloca->setMetadata(
5218 DeclPtrKind, llvm::MDNode::get(
5219 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5220 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5227 void CodeGenModule::EmitVersionIdentMetadata() {
5228 llvm::NamedMDNode *IdentMetadata =
5229 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
5231 llvm::LLVMContext &Ctx = TheModule.getContext();
5233 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5234 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5237 void CodeGenModule::EmitCommandLineMetadata() {
5238 llvm::NamedMDNode *CommandLineMetadata =
5239 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
5241 llvm::LLVMContext &Ctx = TheModule.getContext();
5243 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5244 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5247 void CodeGenModule::EmitTargetMetadata() {
5254 for (
unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5255 auto Val = *(MangledDeclNames.begin() + I);
5262 void CodeGenModule::EmitCoverageFile() {
5267 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
5271 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
5272 llvm::LLVMContext &Ctx = TheModule.getContext();
5273 auto *CoverageDataFile =
5275 auto *CoverageNotesFile =
5277 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5278 llvm::MDNode *CU = CUNode->getOperand(i);
5279 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5280 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5284 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5287 assert(Uuid.size() == 36);
5288 for (
unsigned i = 0; i < 36; ++i) {
5289 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] ==
'-');
5294 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5296 llvm::Constant *Field3[8];
5297 for (
unsigned Idx = 0; Idx < 8; ++Idx)
5298 Field3[Idx] = llvm::ConstantInt::get(
5299 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5301 llvm::Constant *Fields[4] = {
5302 llvm::ConstantInt::get(
Int32Ty, Uuid.substr(0, 8), 16),
5303 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(9, 4), 16),
5304 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(14, 4), 16),
5305 llvm::ConstantArray::get(llvm::ArrayType::get(
Int8Ty, 8), Field3)
5308 return llvm::ConstantStruct::getAnon(Fields);
5317 return llvm::Constant::getNullValue(
Int8PtrTy);
5320 LangOpts.ObjCRuntime.isGNUFamily())
5328 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5330 for (
auto RefExpr : D->
varlists()) {
5331 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5333 VD->getAnyInitializer() &&
5334 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
5339 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5340 CXXGlobalInits.push_back(InitFunction);
5345 CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
5352 std::string OutName;
5353 llvm::raw_string_ostream Out(OutName);
5367 return CreateMetadataIdentifierImpl(T, MetadataIdMap,
"");
5372 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap,
".virtual");
5392 for (
auto &Param : FnType->param_types())
5397 GeneralizedParams, FnType->getExtProtoInfo());
5404 llvm_unreachable(
"Encountered unknown FunctionType");
5409 GeneralizedMetadataIdMap,
".generalized");
5416 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5417 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5418 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5419 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5420 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5421 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5422 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5423 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5429 llvm::Metadata *MD =
5431 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
5433 if (CodeGenOpts.SanitizeCfiCrossDso)
5436 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5439 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
5440 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
5445 assert(TD !=
nullptr);
5446 TargetAttr::ParsedTargetAttr
ParsedAttr = TD->parse();
5448 ParsedAttr.Features.erase(
5449 llvm::remove_if(ParsedAttr.Features,
5450 [&](
const std::string &Feat) {
5451 return !Target.isValidFeatureName(
5452 StringRef{Feat}.substr(1));
5463 StringRef TargetCPU =
Target.getTargetOpts().CPU;
5465 if (
const auto *TD = FD->
getAttr<TargetAttr>()) {
5470 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5471 Target.getTargetOpts().FeaturesAsWritten.begin(),
5472 Target.getTargetOpts().FeaturesAsWritten.end());
5474 if (ParsedAttr.Architecture !=
"" &&
5475 Target.isValidCPUName(ParsedAttr.Architecture))
5476 TargetCPU = ParsedAttr.Architecture;
5483 ParsedAttr.Features);
5484 }
else if (
const auto *SD = FD->
getAttr<CPUSpecificAttr>()) {
5486 Target.getCPUSpecificCPUDispatchFeatures(
5488 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5489 Target.initFeatureMap(FeatureMap,
getDiags(), TargetCPU, Features);
5492 Target.getTargetOpts().Features);
5498 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&
getModule());
5507 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()},
false);
5509 "__translate_sampler_initializer"),
void setLinkage(Linkage L)
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
llvm::PointerType * Int8PtrPtrTy
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
const llvm::DataLayout & getDataLayout() const
virtual bool checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const
Check if the target supports CFProtection branch.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
Defines the clang::ASTContext interface.
The generic AArch64 ABI is also a modified version of the Itanium ABI, but it has fewer divergences t...
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
FunctionDecl * getDefinition()
Get the definition for this declaration.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const CXXDestructorDecl * getDestructor() const
Represents a function declaration or definition.
llvm::IntegerType * IntTy
int
void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
Expr * getInit() const
Get the initializer.
External linkage, which indicates that the entity can be referred to from other translation units...
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
std::vector< const CXXRecordDecl * > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
A (possibly-)qualified type.
The iOS 64-bit ABI is follows ARM's published 64-bit ABI more closely, but we don't guarantee to foll...
CodeGenTypes & getTypes()
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty)
std::vector< Module * >::iterator submodule_iterator
const CodeGenOptions & getCodeGenOpts() const
GlobalDecl getWithDecl(const Decl *D)
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"), llvm::cl::init(false))
unsigned getNumBases() const
Retrieves the number of base classes of this class.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target...
llvm::LLVMContext & getLLVMContext()
GlobalDecl getWithMultiVersionIndex(unsigned Index)
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
CXXDtorType getDtorType() const
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
submodule_iterator submodule_begin()
bool containsNonAsciiOrNull() const
The standard implementation of ConstantInitBuilder used in Clang.
Stmt - This represents one statement.
FunctionType - C99 6.7.5.3 - Function Declarators.
SanitizerSet Sanitize
Set of enabled sanitizers.
virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, raw_ostream &)=0
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
Defines the SourceManager interface.
CharUnits getAlignOfGlobalVarInChars(QualType T) const
Return the alignment in characters that should be given to a global variable with type T...
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
bool isRecordType() const
unsigned getTypeAlignIfKnown(QualType T) const
Return the ABI-specified alignment of a type, in bits, or 0 if the type is incomplete and we cannot d...
virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, raw_ostream &)=0
Defines the clang::Module class, which describes a module in the source code.
const Type * getTypeForDecl() const
CoreFoundationABI CFRuntime
Decl - This represents one declaration (or definition), e.g.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
SourceLocation getBeginLoc() const LLVM_READONLY
FunctionDecl * getOperatorNew() const
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
Defines the C++ template declaration subclasses.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
GlobalDecl getCanonicalDecl() const
LangAS ASTAllocaAddressSpace
The base class of the type hierarchy.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
Stores additional source code information like skipped ranges which is required by the coverage mappi...
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property...
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
const ABIInfo & getABIInfo() const
getABIInfo() - Returns ABI info helper for the target.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
bool isBlacklistedLocation(SanitizerMask Mask, SourceLocation Loc, StringRef Category=StringRef()) const
Represent a C++ namespace.
Represents a call to a C++ constructor.
virtual void completeDefinition()
Note that the definition of this type is now complete.
const TargetInfo & getTargetInfo() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process...
Interoperability with the latest known version of the Swift runtime.
constexpr XRayInstrMask Function
static const llvm::GlobalObject * getAliasedGlobal(const llvm::GlobalIndirectSymbol &GIS)
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
Linkage getLinkage() const
Determine the linkage of this type.
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
Represents a variable declaration or definition.
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
const T * getAs() const
Member-template getAs<specific type>'.
Visibility getVisibility() const
CGDebugInfo * getModuleDebugInfo()
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
bool supportsCOMDAT() const
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Class supports emissionof SIMD-only code.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
ObjCMethodDecl - Represents an instance or class method declaration.
DiagnosticsEngine & getDiags() const
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool supportsIFunc() const
Identify whether this target supports IFuncs.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Represents a struct/union/class.
LanguageIDs getLanguage() const
Return the language specified by this linkage specification.
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
unsigned getIntAlign() const
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
llvm::IntegerType * Int64Ty
field_range fields() const
SourceLocation getBeginLoc() const LLVM_READONLY
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
The generic Mips ABI is a modified version of the Itanium ABI.
Represents a member of a struct/union/class.
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
llvm::IntegerType * SizeTy
StructorType getFromDtorType(CXXDtorType T)
void startDefinition()
Starts the definition of this tag declaration.
bool isReferenceType() const
Interoperability with the Swift 4.1 runtime.
SanitizerMask Mask
Bitmask of enabled sanitizers.
This declaration is definitely a definition.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
unsigned getCharByteWidth() const
llvm::CallingConv::ID RuntimeCC
std::string CodeModel
The code model to use (-mcmodel).
Describes a module or submodule.
bool shouldMangleDeclName(const NamedDecl *D)
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
static void AppendTargetMangling(const CodeGenModule &CGM, const TargetAttr *Attr, raw_ostream &Out)
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
unsigned getLength() const
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e...
FunctionDecl * getOperatorDelete() const
CharUnits - This is an opaque type for sizes expressed in character units.
APValue Val
Val - This is the value the expression can be folded to.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void setDSOLocal(llvm::GlobalValue *GV) const
The Microsoft ABI is the ABI used by Microsoft Visual Studio (and compatible compilers).
bool hasConstructorVariants() const
Does this ABI have different entrypoints for complete-object and base-subobject constructors?
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type...
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
llvm::PointerType * VoidPtrTy
Concrete class used by the front-end to report problems and issues.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
CXXCtorType getCtorType() const
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
Module * Parent
The parent of this module.
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Defines the Diagnostic-related interfaces.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
void AddELFLibDirective(StringRef Lib)
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality...
submodule_iterator submodule_end()
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Represents binding an expression to a temporary.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
CXXTemporary * getTemporary()
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
CharUnits getPointerAlign() const
void EmitTentativeDefinition(const VarDecl *D)
void addInstanceMethod(ObjCMethodDecl *method)
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
llvm::SanitizerStatReport & getSanStats()
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents an ObjC class declaration.
Represents a linkage specification.
The iOS ABI is a partial implementation of the ARM ABI.
Interoperability with the Swift 5.0 runtime.
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void mangleName(const NamedDecl *D, raw_ostream &)
virtual llvm::Value * performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, llvm::Value *V, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Perform address space cast of an expression of pointer type.
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
bool hasProfileClangUse() const
Check if Clang profile use is on.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
llvm::PointerType * getSamplerType(const Type *T)
Represents a K&R-style 'int foo()' function, which has no information available about its arguments...
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
const XRayFunctionFilter & getXRayFilter() const
'watchos' is a variant of iOS for Apple's watchOS.
llvm::StringMap< SectionInfo > SectionInfos
llvm::Type * HalfTy
float, double
const ValueDecl * getExtendingDecl() const
Get the declaration which triggered the lifetime-extension of this temporary, if any.
StringRef getString() const
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
virtual bool checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const
Check if the target supports CFProtection branch.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Represents a prototype with parameter type info, e.g.
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
The generic ARM ABI is a modified version of the Itanium ABI proposed by ARM for use on ARM-based pla...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
void setHasDestructors(bool val)
const TargetCodeGenInfo & getTargetCodeGenInfo()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
Represents a ValueDecl that came out of a declarator.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
llvm::CallingConv::ID getRuntimeCC() const
Exposes information about the current target.
llvm::SmallVector< StringRef, 8 > Features
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode *> &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
This represents one expression.
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isImplicitlyDeclared=false, bool isDefined=false, ImplementationControl impControl=None, bool HasRelatedResultType=false)
Emit only debug info necessary for generating line number tables (-gline-tables-only).
Selector getSetterName() const
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target, in bits.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
unsigned getLine() const
Return the presumed line number of this location.
Organizes the cross-function state that is used while generating code coverage mapping data...
Represents a C++ destructor within a class.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
Defines version macros and version-related utility functions for Clang.
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty)
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
static uint64_t GetX86CpuSupportsMask(ArrayRef< StringRef > FeatureStrs)
Linkage getLinkage() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint32_t getCodeUnit(size_t i) const
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TLSKind getTLSKind() const
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CGOpenMPRuntime(CodeGenModule &CGM)
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
llvm::IntegerType * Int32Ty
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
virtual bool validateCpuSupports(StringRef Name) const
clang::ObjCRuntime ObjCRuntime
propimpl_range property_impls() const
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
QualType getEncodedType() const
llvm::PointerType * AllocaInt8PtrTy
bool isExternallyVisible(Linkage L)
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
QualType getRecordType(const RecordDecl *Decl) const
Represents an unpacked "presumed" location which can be presented to the user.
CXXMethodDecl * getMethodDecl() const
Retrieves the declaration of the called method.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
virtual void getCPUSpecificCPUDispatchFeatures(StringRef Name, llvm::SmallVectorImpl< StringRef > &Features) const
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
const TargetInfo & getTarget() const
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method...
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, llvm::GlobalValue *GV)
This template specialization was implicitly instantiated from a template.
'gnustep' is the modern non-fragile GNUstep runtime.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
const LangOptions & getLangOpts() const
ASTContext & getContext() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
CallingConv
CallingConv - Specifies the calling convention that a function uses.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
const SanitizerBlacklist & getSanitizerBlacklist() const
GlobalDecl - represents a global declaration.
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue...
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
WatchOS is a modernisation of the iOS ABI, which roughly means it's the iOS64 ABI ported to 32-bits...
bool isConstQualified() const
Determine whether this type is const-qualified.
std::string CPU
If given, the name of the target CPU to generate code for.
The l-value was considered opaque, so the alignment was determined from a type.
const char * getFilename() const
Return the presumed filename of this location.
QualType getWideCharType() const
Return the type of wide characters.
unsigned char IntAlignInBytes
static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD, const NamedDecl *ND, bool OmitMultiVersionMangling=false)
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
SelectorTable & Selectors
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
QualType getCanonicalType() const
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification, prepare to emit an alias for it to the expected name.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Encodes a location in the source.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
LangAS getAddressSpace() const
Return the address space of this type.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D...
'objfw' is the Objective-C runtime included in ObjFW
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Represents the declaration of a struct/union/class/enum.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
Represents a call to a member function that may be written either with member call syntax (e...
ASTContext & getASTContext() const LLVM_READONLY
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
llvm::IntegerType * Int16Ty
const Decl * getDecl() const
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
ParsedAttr - Represents a syntactic attribute.
LangAS getStringLiteralAddressSpace() const
Return the AST address space of string literal, which is used to emit the string literal as global va...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD)
Parses the target attributes passed in, and returns only the ones that are valid feature names...
virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF=nullptr)
Emit a code for initialization of threadprivate variable.
Represents a static or instance method of a struct/union/class.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
Weak for now, might become strong later in this TU.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
llvm::Constant * CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList())
Create a new compiler builtin function with the specified type and name.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings startin...
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded...
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
bool isObjCObjectPointerType() const
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
Represents one property declaration in an Objective-C interface.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
The generic Itanium ABI is the standard ABI of most open-source and Unix-like platforms.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
MangleContext & getMangleContext()
Gets the mangle context.
This template specialization was instantiated from a template due to an explicit instantiation defini...
CGCXXABI * CreateMicrosoftCXXABI(CodeGenModule &CGM)
Creates a Microsoft-family ABI.
static unsigned TargetMVPriority(const TargetInfo &TI, const CodeGenFunction::MultiVersionResolverOption &RO)
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
llvm::CallingConv::ID getRuntimeCC() const
Return the calling convention to use for system runtime functions.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, GlobalDecl GD)
std::vector< Structor > CtorList
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
virtual void mangleTypeName(QualType T, raw_ostream &)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing...
CXXCtorType
C++ constructor types.
The WebAssembly ABI is a modified version of the Itanium ABI.
void addReplacement(StringRef Name, llvm::Constant *C)
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character...
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
StringRef getName() const
Return the actual identifier string.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
ObjCIvarDecl * getNextIvar()
TLS with a dynamic initializer.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
const ObjCInterfaceDecl * getClassInterface() const
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool hasSideEffects() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
virtual char CPUSpecificManglingCharacter(StringRef Name) const
EvalResult is a struct with detailed info about an evaluated expression.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
unsigned char PointerAlignInBytes
bool isVisibilityExplicit() const
The basic abstraction for the target Objective-C runtime.
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
llvm::iterator_range< submodule_iterator > submodules()
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
const Expr * getInit() const
FileID getMainFileID() const
Returns the FileID of the main source file.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
llvm::IntegerType * IntPtrTy
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
void UpdateCompletedType(const TagDecl *TD)
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
llvm::Module & getModule() const
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
virtual void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags)=0
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration...
LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
GVALinkage GetGVALinkageForVariable(const VarDecl *VD)
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
unsigned getMultiVersionIndex() const
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual llvm::Optional< LangAS > getConstantAddressSpace() const
Return an AST address space which can be used opportunistically for constant global memory...
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
StructorType getFromCtorType(CXXCtorType T)
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
void setHasNonZeroConstructors(bool val)
llvm::Type * ConvertFunctionType(QualType FT, const FunctionDecl *FD=nullptr)
Converts the GlobalDecl into an llvm::Type.
Represents a C++ base or member initializer.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
CanQualType UnsignedLongTy
Implements C++ ABI-specific code generation functions.
ObjCEncodeExpr, used for @encode in Objective-C.
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable *> &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
virtual unsigned multiVersionSortPriority(StringRef Name) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
virtual void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
emitTargetMD - Provides a convenient hook to handle extra target-specific metadata for the given glob...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
llvm::PointerType * Int8PtrTy
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
virtual uint64_t getMaxPointerWidth() const
Return the maximum width of pointers on this target.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
StringRef getMangledName(GlobalDecl GD)
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
void addDecl(Decl *D)
Add the declaration D into this context.
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
Represents a base class of a C++ class.
static const char AnnotationSection[]
SourceManager & getSourceManager()
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
QualType withCVRQualifiers(unsigned CVR) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
StringRef getUuidStr() const
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TranslationUnitDecl * getTranslationUnitDecl() const
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
Interoperability with the Swift 4.2 runtime.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Represents a C++ struct/union/class.
CGCXXABI * CreateItaniumCXXABI(CodeGenModule &CGM)
Creates an Itanium-family ABI.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
bool isTLSSupported() const
Whether the target supports thread-local storage.
A specialization of Address that requires the address to be an LLVM Constant.
ObjCIvarDecl - Represents an ObjC instance variable.
static bool HasNonDllImportDtor(QualType T)
void Release()
Finalize LLVM code generation.
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
ASTImporterLookupTable & LT
Builtin::Context & BuiltinInfo
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
void EmitGlobalAnnotations()
Emit all the global annotations.
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
uint64_t getPointerAlign(unsigned AddrSpace) const
StringLiteral - This represents a string literal expression, e.g.
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
void finalize(llvm::GlobalVariable *global)
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class...
void EmitMultiVersionResolver(llvm::Function *Resolver, ArrayRef< MultiVersionResolverOption > Options)
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
CGCXXABI & getCXXABI() const
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, unsigned Alignment)
Will return a global variable of the given type.
__DEVICE__ int max(int __a, int __b)
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for...
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
The top declaration context.
unsigned char SizeSizeInBytes
A reference to a declared variable, function, enum, etc.
NamedDecl * getMostRecentDecl()
GVALinkage
A more specific kind of linkage than enum Linkage.
bool isPointerType() const
struct clang::CodeGen::CodeGenFunction::MultiVersionResolverOption::Conds Conditions
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
CodeGenVTables & getVTables()
This represents a decl that may have a name.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
void setAccess(AccessSpecifier AS)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
bool isConstant(const ASTContext &Ctx) const
unsigned getTargetAddressSpace(QualType T) const
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
Selector getGetterName() const
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
void setGlobalVisibilityAndLocal(llvm::GlobalValue *GV, const NamedDecl *D) const
const LangOptions & getLangOpts() const
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
FullSourceLoc getFullLoc(SourceLocation Loc) const
This represents '#pragma omp threadprivate ...' directive.
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Represents the canonical version of C arrays with a specified constant size.
This class handles loading and caching of source files into memory.
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
Defines enum values for all the target-independent builtin functions.
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the "llvm.linker.options" metadata value.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable)
Returns LLVM linkage for a declarator.
Attr - This represents one attribute.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
SourceLocation getLocation() const
bool isExternallyVisible() const
APValue * getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, bool MayCreate)
Get the storage for the constant value of a materialized temporary of static storage duration...
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, ASTContext &Context)
A helper function to get the alignment of a Decl referred to by DeclRefExpr or MemberExpr.
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const llvm::Triple & getTriple() const