47 #include "llvm/ADT/Triple.h" 48 #include "llvm/Analysis/TargetLibraryInfo.h" 49 #include "llvm/IR/CallSite.h" 50 #include "llvm/IR/CallingConv.h" 51 #include "llvm/IR/DataLayout.h" 52 #include "llvm/IR/Intrinsics.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/IR/Module.h" 55 #include "llvm/ProfileData/InstrProfReader.h" 56 #include "llvm/Support/ConvertUTF.h" 57 #include "llvm/Support/ErrorHandling.h" 58 #include "llvm/Support/MD5.h" 60 using namespace clang;
61 using namespace CodeGen;
64 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
65 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"),
66 llvm::cl::init(
false));
85 llvm_unreachable(
"invalid C++ ABI kind");
93 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
96 VMContext(M.getContext()), Types(*this), VTables(*this),
100 llvm::LLVMContext &LLVMContext = M.getContext();
101 VoidTy = llvm::Type::getVoidTy(LLVMContext);
102 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
106 HalfTy = llvm::Type::getHalfTy(LLVMContext);
107 FloatTy = llvm::Type::getFloatTy(LLVMContext);
108 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
117 IntPtrTy = llvm::IntegerType::get(LLVMContext,
122 M.getDataLayout().getAllocaAddrSpace());
131 createOpenCLRuntime();
133 createOpenMPRuntime();
138 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
139 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
146 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
149 Block.GlobalUniqueCount = 0;
157 if (
auto E = ReaderOrErr.takeError()) {
159 "Could not read profile %0: %1");
160 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
165 PGOReader = std::move(ReaderOrErr.get());
170 if (CodeGenOpts.CoverageMapping)
176 void CodeGenModule::createObjCRuntime() {
193 llvm_unreachable(
"bad runtime kind");
196 void CodeGenModule::createOpenCLRuntime() {
200 void CodeGenModule::createOpenMPRuntime() {
204 case llvm::Triple::nvptx:
205 case llvm::Triple::nvptx64:
207 "OpenMP NVPTX is only prepared to deal with device code.");
211 if (LangOpts.OpenMPSimd)
219 void CodeGenModule::createCUDARuntime() {
224 Replacements[Name] = C;
227 void CodeGenModule::applyReplacements() {
228 for (
auto &I : Replacements) {
229 StringRef MangledName = I.first();
234 auto *OldF = cast<llvm::Function>(Entry);
235 auto *NewF = dyn_cast<llvm::Function>(
Replacement);
237 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
238 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
241 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
242 CE->getOpcode() == llvm::Instruction::GetElementPtr);
243 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
248 OldF->replaceAllUsesWith(Replacement);
250 NewF->removeFromParent();
251 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
254 OldF->eraseFromParent();
259 GlobalValReplacements.push_back(std::make_pair(GV, C));
262 void CodeGenModule::applyGlobalValReplacements() {
263 for (
auto &I : GlobalValReplacements) {
264 llvm::GlobalValue *GV = I.first;
265 llvm::Constant *C = I.second;
267 GV->replaceAllUsesWith(C);
268 GV->eraseFromParent();
275 const llvm::GlobalIndirectSymbol &GIS) {
276 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
277 const llvm::Constant *C = &GIS;
279 C = C->stripPointerCasts();
280 if (
auto *GO = dyn_cast<llvm::GlobalObject>(C))
283 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
286 if (!Visited.insert(GIS2).second)
288 C = GIS2->getIndirectSymbol();
292 void CodeGenModule::checkAliases() {
299 const auto *D = cast<ValueDecl>(GD.getDecl());
301 bool IsIFunc = D->hasAttr<IFuncAttr>();
302 if (
const Attr *A = D->getDefiningAttr())
303 Location = A->getLocation();
305 llvm_unreachable(
"Not an alias or ifunc?");
308 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
312 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
313 }
else if (GV->isDeclaration()) {
315 Diags.
Report(Location, diag::err_alias_to_undefined)
316 << IsIFunc << IsIFunc;
317 }
else if (IsIFunc) {
319 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
320 GV->getType()->getPointerElementType());
322 if (!FTy->getReturnType()->isPointerTy())
323 Diags.
Report(Location, diag::err_ifunc_resolver_return);
324 if (FTy->getNumParams())
325 Diags.
Report(Location, diag::err_ifunc_resolver_params);
328 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
329 llvm::GlobalValue *AliaseeGV;
330 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
331 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
333 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
335 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
336 StringRef AliasSection = SA->getName();
337 if (AliasSection != AliaseeGV->getSection())
338 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
339 << AliasSection << IsIFunc << IsIFunc;
347 if (
auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
348 if (GA->isInterposable()) {
349 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
350 << GV->getName() << GA->getName() << IsIFunc;
351 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
352 GA->getIndirectSymbol(), Alias->getType());
353 Alias->setIndirectSymbol(Aliasee);
363 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
364 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
365 Alias->eraseFromParent();
370 DeferredDeclsToEmit.clear();
372 OpenMPRuntime->clear();
376 StringRef MainFile) {
377 if (!hasDiagnostics())
379 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
380 if (MainFile.empty())
381 MainFile =
"<stdin>";
382 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
385 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
388 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
394 EmitVTablesOpportunistically();
395 applyGlobalValReplacements();
398 EmitCXXGlobalInitFunc();
399 EmitCXXGlobalDtorFunc();
400 EmitCXXThreadLocalInitFunc();
402 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
403 AddGlobalCtor(ObjCInitFunction);
406 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
407 AddGlobalCtor(CudaCtorFunction);
408 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
409 AddGlobalDtor(CudaDtorFunction);
412 if (llvm::Function *OpenMPRegistrationFunction =
413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction :
nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
419 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
423 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
424 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
426 EmitStaticExternCAliases();
429 CoverageMapping->emit();
430 if (CodeGenOpts.SanitizeCfiCrossDso) {
434 emitAtAvailableLinkGuard();
439 if (CodeGenOpts.Autolink &&
440 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
441 EmitModuleLinkOptions();
447 CodeGenOpts.NumRegisterParameters);
449 if (CodeGenOpts.DwarfVersion) {
453 CodeGenOpts.DwarfVersion);
455 if (CodeGenOpts.EmitCodeView) {
459 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
466 llvm::Metadata *Ops[2] = {
467 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
468 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
469 llvm::Type::getInt32Ty(VMContext), 1))};
471 getModule().addModuleFlag(llvm::Module::Require,
472 "StrictVTablePointersRequirement",
473 llvm::MDNode::get(VMContext, Ops));
480 llvm::DEBUG_METADATA_VERSION);
485 uint64_t WCharWidth =
490 if ( Arch == llvm::Triple::arm
491 || Arch == llvm::Triple::armeb
492 || Arch == llvm::Triple::thumb
493 || Arch == llvm::Triple::thumbeb) {
495 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
499 if (CodeGenOpts.SanitizeCfiCrossDso) {
501 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
504 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
508 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
509 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
513 if (LangOpts.OpenCL) {
514 EmitOpenCLMetadata();
516 if (
getTriple().getArch() == llvm::Triple::spir ||
517 getTriple().getArch() == llvm::Triple::spir64) {
520 llvm::Metadata *SPIRVerElts[] = {
521 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
522 Int32Ty, LangOpts.OpenCLVersion / 100)),
523 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
524 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
525 llvm::NamedMDNode *SPIRVerMD =
526 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
527 llvm::LLVMContext &Ctx = TheModule.getContext();
528 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
532 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
533 assert(PLevel < 3 &&
"Invalid PIC Level");
534 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
536 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
539 SimplifyPersonality();
548 DebugInfo->finalize();
550 EmitVersionIdentMetadata();
552 EmitTargetMetadata();
555 void CodeGenModule::EmitOpenCLMetadata() {
558 llvm::Metadata *OCLVerElts[] = {
559 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
560 Int32Ty, LangOpts.OpenCLVersion / 100)),
561 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
562 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
563 llvm::NamedMDNode *OCLVerMD =
564 TheModule.getOrInsertNamedMetadata(
"opencl.ocl.version");
565 llvm::LLVMContext &Ctx = TheModule.getContext();
566 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
582 return TBAA->getTypeInfo(QTy);
599 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
605 return TBAA->getTBAAStructInfo(QTy);
611 return TBAA->getBaseTypeInfo(QTy);
617 return TBAA->getAccessTagInfo(Info);
624 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
632 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
638 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
643 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
656 "cannot compile this %0 yet");
657 std::string Msg =
Type;
666 "cannot compile this %0 yet");
667 std::string Msg =
Type;
679 if (GV->hasLocalLinkage()) {
687 (IsForDefinition && !GV->hasAvailableExternallyLinkage()))
692 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
693 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
694 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
695 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
696 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
703 return llvm::GlobalVariable::GeneralDynamicTLSModel;
705 return llvm::GlobalVariable::LocalDynamicTLSModel;
707 return llvm::GlobalVariable::InitialExecTLSModel;
709 return llvm::GlobalVariable::LocalExecTLSModel;
711 llvm_unreachable(
"Invalid TLS model!");
715 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
717 llvm::GlobalValue::ThreadLocalMode TLM;
721 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
725 GV->setThreadLocalMode(TLM);
733 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
742 auto FoundName = MangledDeclNames.find(CanonicalGD);
743 if (FoundName != MangledDeclNames.end())
744 return FoundName->second;
746 const auto *ND = cast<NamedDecl>(GD.
getDecl());
750 llvm::raw_svector_ostream Out(Buffer);
751 if (
const auto *D = dyn_cast<CXXConstructorDecl>(ND))
753 else if (
const auto *D = dyn_cast<CXXDestructorDecl>(ND))
760 assert(II &&
"Attempt to mangle unnamed decl.");
765 llvm::raw_svector_ostream Out(Buffer);
766 Out <<
"__regcall3__" << II->
getName();
774 auto Result = Manglings.insert(std::make_pair(Str, GD));
775 return MangledDeclNames[CanonicalGD] = Result.first->first();
784 llvm::raw_svector_ostream Out(Buffer);
787 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
788 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
790 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
793 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
795 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
796 return Result.first->first();
805 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor,
int Priority,
806 llvm::Constant *AssociatedData) {
808 GlobalCtors.push_back(
Structor(Priority, Ctor, AssociatedData));
813 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor,
int Priority) {
815 GlobalDtors.push_back(
Structor(Priority, Dtor,
nullptr));
818 void CodeGenModule::EmitCtorList(
CtorList &Fns,
const char *GlobalName) {
819 if (Fns.empty())
return;
822 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
823 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
826 llvm::StructType *CtorStructTy = llvm::StructType::get(
831 auto ctors = builder.
beginArray(CtorStructTy);
832 for (
const auto &I : Fns) {
833 auto ctor = ctors.beginStruct(CtorStructTy);
834 ctor.addInt(
Int32Ty, I.Priority);
835 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
836 if (I.AssociatedData)
837 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData,
VoidPtrTy));
840 ctor.finishAndAddTo(ctors);
846 llvm::GlobalValue::AppendingLinkage);
850 list->setAlignment(0);
855 llvm::GlobalValue::LinkageTypes
857 const auto *D = cast<FunctionDecl>(GD.
getDecl());
861 if (isa<CXXDestructorDecl>(D) &&
862 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
867 : llvm::GlobalValue::LinkOnceODRLinkage;
870 if (isa<CXXConstructorDecl>(D) &&
871 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
883 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
885 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
888 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
893 if (FD->hasAttr<DLLImportAttr>())
894 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
895 else if (FD->hasAttr<DLLExportAttr>())
896 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
898 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
902 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
903 if (!MDS)
return nullptr;
905 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
910 setNonAliasAttributes(D, F);
917 llvm::AttributeList PAL;
919 F->setAttributes(PAL);
920 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
930 if (!LangOpts.Exceptions)
return false;
933 if (LangOpts.CXXExceptions)
return true;
936 if (LangOpts.ObjCExceptions) {
947 if (CodeGenOpts.UnwindTables)
948 B.addAttribute(llvm::Attribute::UWTable);
951 B.addAttribute(llvm::Attribute::NoUnwind);
954 B.addAttribute(llvm::Attribute::StackProtect);
956 B.addAttribute(llvm::Attribute::StackProtectStrong);
958 B.addAttribute(llvm::Attribute::StackProtectReq);
964 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
966 B.addAttribute(llvm::Attribute::NoInline);
968 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
974 bool ShouldAddOptNone =
975 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
977 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
978 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
979 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
981 if (ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) {
982 B.addAttribute(llvm::Attribute::OptimizeNone);
985 B.addAttribute(llvm::Attribute::NoInline);
986 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
987 "OptimizeNone and AlwaysInline on same function!");
992 B.addAttribute(llvm::Attribute::Naked);
995 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
996 F->removeFnAttr(llvm::Attribute::MinSize);
997 }
else if (D->
hasAttr<NakedAttr>()) {
999 B.addAttribute(llvm::Attribute::Naked);
1000 B.addAttribute(llvm::Attribute::NoInline);
1001 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
1002 B.addAttribute(llvm::Attribute::NoDuplicate);
1003 }
else if (D->
hasAttr<NoInlineAttr>()) {
1004 B.addAttribute(llvm::Attribute::NoInline);
1005 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
1006 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1008 B.addAttribute(llvm::Attribute::AlwaysInline);
1012 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1013 B.addAttribute(llvm::Attribute::NoInline);
1017 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
1018 if (any_of(FD->redecls(), [&](
const FunctionDecl *Redecl) {
1019 return Redecl->isInlineSpecified();
1021 B.addAttribute(llvm::Attribute::InlineHint);
1022 }
else if (CodeGenOpts.getInlining() ==
1025 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1026 B.addAttribute(llvm::Attribute::NoInline);
1033 if (!D->
hasAttr<OptimizeNoneAttr>()) {
1035 if (!ShouldAddOptNone)
1036 B.addAttribute(llvm::Attribute::OptimizeForSize);
1037 B.addAttribute(llvm::Attribute::Cold);
1040 if (D->
hasAttr<MinSizeAttr>())
1041 B.addAttribute(llvm::Attribute::MinSize);
1044 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1048 F->setAlignment(alignment);
1055 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1060 if (CodeGenOpts.SanitizeCfiCrossDso)
1061 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1066 llvm::GlobalValue *GV) {
1067 if (
const auto *ND = dyn_cast_or_null<NamedDecl>(D))
1072 if (D && D->
hasAttr<UsedAttr>())
1077 llvm::GlobalValue *GV) {
1082 if (D->
hasAttr<DLLExportAttr>())
1083 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1086 void CodeGenModule::setNonAliasAttributes(
const Decl *D,
1087 llvm::GlobalObject *GO) {
1091 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1092 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
1093 GV->addAttribute(
"bss-section", SA->getName());
1094 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
1095 GV->addAttribute(
"data-section", SA->getName());
1096 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
1097 GV->addAttribute(
"rodata-section", SA->getName());
1100 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
1101 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
1102 if (!D->
getAttr<SectionAttr>())
1103 F->addFnAttr(
"implicit-section-name", SA->getName());
1106 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
1107 GO->setSection(SA->getName());
1121 setNonAliasAttributes(D, F);
1131 if (ND->
hasAttr<DLLImportAttr>()) {
1133 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1134 }
else if (ND->
hasAttr<DLLExportAttr>()) {
1139 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1145 llvm::Function *F) {
1147 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
1151 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1155 if (CodeGenOpts.SanitizeCfiCrossDso) {
1163 F->addTypeMetadata(0, MD);
1167 if (CodeGenOpts.SanitizeCfiCrossDso)
1169 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1172 void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
1173 bool IsIncompleteFunction,
1180 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
1184 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1186 if (!IsIncompleteFunction) {
1189 if (!IsForDefinition)
1197 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
1199 assert(!F->arg_empty() &&
1200 F->arg_begin()->getType()
1201 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1202 "unexpected this return");
1203 F->addAttribute(1, llvm::Attribute::Returned);
1212 if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1213 F->addFnAttr(
"implicit-section-name");
1216 if (
const SectionAttr *SA = FD->getAttr<SectionAttr>())
1217 F->setSection(SA->getName());
1219 if (FD->isReplaceableGlobalAllocationFunction()) {
1222 F->addAttribute(llvm::AttributeList::FunctionIndex,
1223 llvm::Attribute::NoBuiltin);
1228 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1230 (
Kind == OO_New ||
Kind == OO_Array_New))
1231 F->addAttribute(llvm::AttributeList::ReturnIndex,
1232 llvm::Attribute::NoAlias);
1235 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1236 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1237 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1238 if (MD->isVirtual())
1239 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1243 if (!CodeGenOpts.SanitizeCfiCrossDso)
1246 if (
getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1251 assert(!GV->isDeclaration() &&
1252 "Only globals with definition can force usage.");
1253 LLVMUsed.emplace_back(GV);
1257 assert(!GV->isDeclaration() &&
1258 "Only globals with definition can force usage.");
1259 LLVMCompilerUsed.emplace_back(GV);
1263 std::vector<llvm::WeakTrackingVH> &List) {
1270 UsedArray.resize(List.size());
1271 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
1273 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1274 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
1277 if (UsedArray.empty())
1279 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
1281 auto *GV =
new llvm::GlobalVariable(
1282 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
1283 llvm::ConstantArray::get(ATy, UsedArray), Name);
1285 GV->setSection(
"llvm.metadata");
1288 void CodeGenModule::emitLLVMUsed() {
1289 emitUsed(*
this,
"llvm.used", LLVMUsed);
1290 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
1295 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1302 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1309 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1316 llvm::SmallPtrSet<Module *, 16> &Visited) {
1318 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
1323 for (
unsigned I = Mod->
Imports.size(); I > 0; --I) {
1324 if (Visited.insert(Mod->
Imports[I - 1]).second)
1335 llvm::Metadata *Args[2] = {
1336 llvm::MDString::get(Context,
"-framework"),
1337 llvm::MDString::get(Context, Mod->
LinkLibraries[I - 1].Library)};
1339 Metadata.push_back(llvm::MDNode::get(Context, Args));
1347 auto *OptString = llvm::MDString::get(Context, Opt);
1348 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1352 void CodeGenModule::EmitModuleLinkOptions() {
1356 llvm::SetVector<clang::Module *> LinkModules;
1357 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1361 for (
Module *M : ImportedModules) {
1367 if (Visited.insert(M).second)
1373 while (!Stack.empty()) {
1376 bool AnyChildren =
false;
1381 Sub != SubEnd; ++Sub) {
1384 if ((*Sub)->IsExplicit)
1387 if (Visited.insert(*Sub).second) {
1388 Stack.push_back(*Sub);
1396 LinkModules.insert(Mod);
1405 for (
Module *M : LinkModules)
1406 if (Visited.insert(M).second)
1408 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1409 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1412 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
1413 for (
auto *MD : LinkerOptionsMetadata)
1414 NMD->addOperand(MD);
1417 void CodeGenModule::EmitDeferred() {
1422 if (!DeferredVTables.empty()) {
1423 EmitDeferredVTables();
1428 assert(DeferredVTables.empty());
1432 if (DeferredDeclsToEmit.empty())
1437 std::vector<GlobalDecl> CurDeclsToEmit;
1438 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1445 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1463 if (!GV->isDeclaration())
1467 EmitGlobalDefinition(D, GV);
1472 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1474 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1479 void CodeGenModule::EmitVTablesOpportunistically() {
1485 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1486 &&
"Only emit opportunistic vtables with optimizations");
1490 "This queue should only contain external vtables");
1491 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
1494 OpportunisticVTables.clear();
1498 if (Annotations.empty())
1502 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1503 Annotations[0]->getType(), Annotations.size()), Annotations);
1504 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
1505 llvm::GlobalValue::AppendingLinkage,
1506 Array,
"llvm.global.annotations");
1507 gv->setSection(AnnotationSection);
1511 llvm::Constant *&AStr = AnnotationStrings[Str];
1516 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
1518 new llvm::GlobalVariable(
getModule(), s->getType(),
true,
1519 llvm::GlobalValue::PrivateLinkage, s,
".str");
1520 gv->setSection(AnnotationSection);
1521 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1539 return llvm::ConstantInt::get(
Int32Ty, LineNo);
1543 const AnnotateAttr *AA,
1551 llvm::Constant *Fields[4] = {
1552 llvm::ConstantExpr::getBitCast(GV,
Int8PtrTy),
1553 llvm::ConstantExpr::getBitCast(AnnoGV,
Int8PtrTy),
1554 llvm::ConstantExpr::getBitCast(UnitGV,
Int8PtrTy),
1557 return llvm::ConstantStruct::getAnon(Fields);
1561 llvm::GlobalValue *GV) {
1562 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1573 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1582 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1592 (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
1593 if (!EnabledAsanMask)
1596 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(),
Category))
1598 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1604 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
1605 Ty = AT->getElementType();
1610 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
1619 if (!LangOpts.XRayInstrument)
1625 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1626 if (
Attr == ImbueAttr::NONE)
1627 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1629 case ImbueAttr::NONE:
1631 case ImbueAttr::ALWAYS:
1632 Fn->addFnAttr(
"function-instrument",
"xray-always");
1634 case ImbueAttr::ALWAYS_ARG1:
1635 Fn->addFnAttr(
"function-instrument",
"xray-always");
1636 Fn->addFnAttr(
"xray-log-args",
"1");
1638 case ImbueAttr::NEVER:
1639 Fn->addFnAttr(
"function-instrument",
"xray-never");
1645 bool CodeGenModule::MustBeEmitted(
const ValueDecl *Global) {
1647 if (LangOpts.EmitAllDecls)
1653 bool CodeGenModule::MayBeEmittedEagerly(
const ValueDecl *Global) {
1654 if (
const auto *FD = dyn_cast<FunctionDecl>(Global))
1659 if (
const auto *VD = dyn_cast<VarDecl>(Global))
1667 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1679 std::string Name =
"_GUID_" + Uuid.lower();
1680 std::replace(Name.begin(), Name.end(),
'-',
'_');
1686 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
1689 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1690 assert(Init &&
"failed to initialize as constant");
1692 auto *GV =
new llvm::GlobalVariable(
1694 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1696 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1701 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
1702 assert(AA &&
"No alias?");
1711 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1715 llvm::Constant *Aliasee;
1716 if (isa<llvm::FunctionType>(DeclTy))
1717 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1721 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1722 llvm::PointerType::getUnqual(DeclTy),
1725 auto *F = cast<llvm::GlobalValue>(Aliasee);
1726 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1727 WeakRefReferences.insert(F);
1733 const auto *Global = cast<ValueDecl>(GD.
getDecl());
1736 if (Global->
hasAttr<WeakRefAttr>())
1741 if (Global->
hasAttr<AliasAttr>())
1742 return EmitAliasDefinition(GD);
1745 if (Global->
hasAttr<IFuncAttr>())
1746 return emitIFuncDefinition(GD);
1749 if (LangOpts.CUDA) {
1750 if (LangOpts.CUDAIsDevice) {
1751 if (!Global->
hasAttr<CUDADeviceAttr>() &&
1752 !Global->
hasAttr<CUDAGlobalAttr>() &&
1753 !Global->
hasAttr<CUDAConstantAttr>() &&
1754 !Global->
hasAttr<CUDASharedAttr>())
1763 if (isa<FunctionDecl>(Global) && !Global->
hasAttr<CUDAHostAttr>() &&
1764 Global->
hasAttr<CUDADeviceAttr>())
1767 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1768 "Expected Variable or Function");
1772 if (LangOpts.OpenMP) {
1775 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1777 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1778 if (MustBeEmitted(Global))
1785 if (
const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1787 if (!FD->doesThisDeclarationHaveABody()) {
1788 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1797 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
1802 const auto *VD = cast<VarDecl>(Global);
1803 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
1807 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1808 !VD->hasDefinition() &&
1809 (VD->hasAttr<CUDAConstantAttr>() ||
1810 VD->hasAttr<CUDADeviceAttr>());
1811 if (!MustEmitForCuda &&
1826 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1828 EmitGlobalDefinition(GD);
1835 cast<VarDecl>(Global)->hasInit()) {
1836 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1837 CXXGlobalInits.push_back(
nullptr);
1843 addDeferredDeclToEmit(GD);
1844 }
else if (MustBeEmitted(Global)) {
1846 assert(!MayBeEmittedEagerly(Global));
1847 addDeferredDeclToEmit(GD);
1852 DeferredDecls[MangledName] = GD;
1859 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1860 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1867 struct FunctionIsDirectlyRecursive :
1869 const StringRef Name;
1873 Name(N), BI(C), Result(
false) {
1877 bool TraverseCallExpr(
CallExpr *E) {
1882 if (Attr && Name == Attr->getLabel()) {
1889 StringRef BuiltinName = BI.
getName(BuiltinID);
1890 if (BuiltinName.startswith(
"__builtin_") &&
1891 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
1900 struct DLLImportFunctionVisitor
1902 bool SafeToInline =
true;
1904 bool shouldVisitImplicitCode()
const {
return true; }
1906 bool VisitVarDecl(
VarDecl *VD) {
1909 SafeToInline =
false;
1910 return SafeToInline;
1917 return SafeToInline;
1922 SafeToInline = D->
hasAttr<DLLImportAttr>();
1923 return SafeToInline;
1928 if (isa<FunctionDecl>(VD))
1929 SafeToInline = VD->
hasAttr<DLLImportAttr>();
1930 else if (
VarDecl *V = dyn_cast<VarDecl>(VD))
1931 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1932 return SafeToInline;
1937 return SafeToInline;
1944 SafeToInline =
true;
1946 SafeToInline = M->
hasAttr<DLLImportAttr>();
1948 return SafeToInline;
1953 return SafeToInline;
1958 return SafeToInline;
1967 CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
1969 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1974 Name = Attr->getLabel();
1979 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
1980 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1981 return Walker.Result;
1984 bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
1987 const auto *F = cast<FunctionDecl>(GD.
getDecl());
1988 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1991 if (F->hasAttr<DLLImportAttr>()) {
1993 DLLImportFunctionVisitor Visitor;
1994 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1995 if (!Visitor.SafeToInline)
2001 for (
const Decl *Member : Dtor->getParent()->decls())
2002 if (isa<FieldDecl>(Member))
2016 return !isTriviallyRecursive(F);
2019 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2020 return CodeGenOpts.OptimizationLevel > 0;
2023 void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
2024 const auto *D = cast<ValueDecl>(GD.
getDecl());
2028 "Generating code for declaration");
2030 if (isa<FunctionDecl>(D)) {
2033 if (!shouldEmitFunction(GD))
2036 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2039 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2041 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2044 EmitGlobalFunctionDefinition(GD, GV);
2046 if (Method->isVirtual())
2052 return EmitGlobalFunctionDefinition(GD, GV);
2055 if (
const auto *VD = dyn_cast<VarDecl>(D))
2056 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2058 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
2062 llvm::Function *NewFn);
2071 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2073 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
2080 if (WeakRefReferences.erase(Entry)) {
2081 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2082 if (FD && !FD->
hasAttr<WeakAttr>())
2087 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
2088 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2092 if (IsForDefinition && !Entry->isDeclaration()) {
2099 DiagnosedConflictingDefinitions.insert(GD).second) {
2101 diag::err_duplicate_mangled_name);
2103 diag::note_previous_definition);
2107 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2108 (Entry->getType()->getElementType() == Ty)) {
2115 if (!IsForDefinition)
2116 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2122 bool IsIncompleteFunction =
false;
2124 llvm::FunctionType *FTy;
2125 if (isa<llvm::FunctionType>(Ty)) {
2126 FTy = cast<llvm::FunctionType>(Ty);
2128 FTy = llvm::FunctionType::get(
VoidTy,
false);
2129 IsIncompleteFunction =
true;
2134 Entry ? StringRef() : MangledName, &
getModule());
2151 if (!Entry->use_empty()) {
2153 Entry->removeDeadConstantUsers();
2156 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2157 F, Entry->getType()->getElementType()->getPointerTo());
2161 assert(F->getName() == MangledName &&
"name was uniqued!");
2163 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk,
2165 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2166 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2167 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2174 if (D && isa<CXXDestructorDecl>(D) &&
2175 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2177 addDeferredDeclToEmit(GD);
2182 auto DDI = DeferredDecls.find(MangledName);
2183 if (DDI != DeferredDecls.end()) {
2187 addDeferredDeclToEmit(DDI->second);
2188 DeferredDecls.erase(DDI);
2203 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2216 if (!IsIncompleteFunction) {
2217 assert(F->getType()->getElementType() == Ty);
2221 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2222 return llvm::ConstantExpr::getBitCast(F, PTy);
2235 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2241 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2242 false, llvm::AttributeList(),
2252 for (
const auto &Result : DC->
lookup(&CII))
2253 if (
const auto FD = dyn_cast<FunctionDecl>(Result))
2261 (Name ==
"_ZSt9terminatev" || Name ==
"\01?terminate@@YAXXZ")
2265 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
2267 for (
const auto &Result : DC->
lookup(&NS)) {
2269 if (
auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2270 for (
const auto &Result : LSD->lookup(&NS))
2271 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2275 for (
const auto &Result : ND->
lookup(&CXXII))
2276 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
2288 llvm::AttributeList ExtraAttrs,
2291 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2295 if (
auto *F = dyn_cast<llvm::Function>(C)) {
2299 if (!Local &&
getTriple().isOSBinFormatCOFF() &&
2301 !
getTriple().isWindowsGNUEnvironment()) {
2303 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
2304 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2318 llvm::AttributeList ExtraAttrs) {
2320 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2321 false,
false, ExtraAttrs);
2322 if (
auto *F = dyn_cast<llvm::Function>(C))
2341 return ExcludeCtor && !Record->hasMutableFields() &&
2342 Record->hasTrivialDestructor();
2360 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2361 llvm::PointerType *Ty,
2367 if (WeakRefReferences.erase(Entry)) {
2368 if (D && !D->
hasAttr<WeakAttr>())
2373 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
2374 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2376 if (Entry->getType() == Ty)
2381 if (IsForDefinition && !Entry->isDeclaration()) {
2389 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
2391 DiagnosedConflictingDefinitions.insert(D).second) {
2393 diag::err_duplicate_mangled_name);
2395 diag::note_previous_definition);
2400 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2401 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2405 if (!IsForDefinition)
2406 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2412 auto *GV =
new llvm::GlobalVariable(
2413 getModule(), Ty->getElementType(),
false,
2415 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2420 GV->takeName(Entry);
2422 if (!Entry->use_empty()) {
2423 llvm::Constant *NewPtrForOldDecl =
2424 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2425 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2428 Entry->eraseFromParent();
2434 auto DDI = DeferredDecls.find(MangledName);
2435 if (DDI != DeferredDecls.end()) {
2438 addDeferredDeclToEmit(DDI->second);
2439 DeferredDecls.erase(DDI);
2455 CXXThreadLocals.push_back(D);
2461 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
2462 EmitGlobalVarDefinition(D);
2467 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
2468 GV->setSection(SA->getName());
2472 if (
getTriple().getArch() == llvm::Triple::xcore &&
2476 GV->setSection(
".cp.rodata");
2481 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2484 const auto *Record =
2486 bool HasMutableFields = Record && Record->hasMutableFields();
2487 if (!HasMutableFields) {
2494 auto *InitType = Init->getType();
2495 if (GV->getType()->getElementType() != InitType) {
2500 GV->setName(StringRef());
2503 auto *NewGV = cast<llvm::GlobalVariable>(
2507 cast<llvm::GlobalValue>(GV)->eraseFromParent();
2510 GV->setInitializer(Init);
2511 GV->setConstant(
true);
2512 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2524 assert(
getContext().getTargetAddressSpace(ExpectedAS) ==
2525 Ty->getPointerAddressSpace());
2526 if (AddrSpace != ExpectedAS)
2537 if (isa<CXXConstructorDecl>(D))
2541 false, IsForDefinition);
2542 else if (isa<CXXDestructorDecl>(D))
2546 false, IsForDefinition);
2547 else if (isa<CXXMethodDecl>(D)) {
2549 cast<CXXMethodDecl>(D));
2553 }
else if (isa<FunctionDecl>(D)) {
2563 llvm::GlobalVariable *
2566 llvm::GlobalValue::LinkageTypes
Linkage) {
2567 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
2568 llvm::GlobalVariable *OldGV =
nullptr;
2572 if (GV->getType()->getElementType() == Ty)
2577 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
2582 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
2583 Linkage,
nullptr, Name);
2587 GV->takeName(OldGV);
2589 if (!OldGV->use_empty()) {
2590 llvm::Constant *NewPtrForOldDecl =
2591 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2592 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2595 OldGV->eraseFromParent();
2599 !GV->hasAvailableExternallyLinkage())
2600 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2619 llvm::PointerType *PTy =
2620 llvm::PointerType::get(Ty,
getContext().getTargetAddressSpace(ASTTy));
2623 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2631 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty),
nullptr);
2635 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
2643 if (GV && !GV->isDeclaration())
2648 if (!MustBeEmitted(D) && !GV) {
2649 DeferredDecls[MangledName] = D;
2654 EmitGlobalVarDefinition(D);
2664 if (LangOpts.OpenCL) {
2673 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2674 if (D && D->
hasAttr<CUDAConstantAttr>())
2676 else if (D && D->
hasAttr<CUDASharedAttr>())
2685 template<
typename SomeDecl>
2687 llvm::GlobalValue *GV) {
2693 if (!D->template hasAttr<UsedAttr>())
2702 const SomeDecl *First = D->getFirstDecl();
2703 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2709 std::pair<StaticExternCMap::iterator, bool> R =
2710 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2715 R.first->second =
nullptr;
2722 if (D.
hasAttr<SelectAnyAttr>())
2726 if (
auto *VD = dyn_cast<VarDecl>(&D))
2740 llvm_unreachable(
"No such linkage");
2744 llvm::GlobalObject &GO) {
2747 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2751 void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
2759 llvm::Constant *Init =
nullptr;
2761 bool NeedsGlobalCtor =
false;
2774 Init = llvm::UndefValue::get(
getTypes().ConvertType(ASTTy));
2775 else if (!InitExpr) {
2789 emitter.emplace(*
this);
2790 Init = emitter->tryEmitForInitializer(*InitDecl);
2799 NeedsGlobalCtor =
true;
2802 Init = llvm::UndefValue::get(
getTypes().ConvertType(T));
2809 DelayedCXXInitPosition.erase(D);
2814 llvm::Constant *Entry =
2818 if (
auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2819 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2820 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2822 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2823 Entry = CE->getOperand(0);
2827 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2838 if (!GV || GV->getType()->getElementType() != InitType ||
2839 GV->getType()->getAddressSpace() !=
2843 Entry->setName(StringRef());
2846 GV = cast<llvm::GlobalVariable>(
2850 llvm::Constant *NewPtrForOldDecl =
2851 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2852 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2855 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2860 if (D->
hasAttr<AnnotateAttr>())
2864 llvm::GlobalValue::LinkageTypes
Linkage =
2874 if (GV && LangOpts.CUDA) {
2875 if (LangOpts.CUDAIsDevice) {
2876 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>())
2877 GV->setExternallyInitialized(
true);
2883 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>()) {
2891 if (D->
hasAttr<CUDAConstantAttr>())
2894 }
else if (D->
hasAttr<CUDASharedAttr>())
2904 GV->setInitializer(Init);
2905 if (emitter) emitter->finalize(GV);
2908 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2912 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
2915 GV->setConstant(
true);
2930 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2931 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2934 GV->setLinkage(Linkage);
2935 if (D->
hasAttr<DLLImportAttr>())
2936 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2937 else if (D->
hasAttr<DLLExportAttr>())
2938 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2940 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2942 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2944 GV->setConstant(
false);
2949 if (!GV->getInitializer()->isNullValue())
2950 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2953 setNonAliasAttributes(D, GV);
2955 if (D->
getTLSKind() && !GV->isThreadLocal()) {
2957 CXXThreadLocals.push_back(D);
2964 if (NeedsGlobalCtor || NeedsGlobalDtor)
2965 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2967 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2972 DI->EmitGlobalVariable(GV, D);
2980 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
2991 if (D->
hasAttr<SectionAttr>())
2997 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
2998 D->
hasAttr<PragmaClangDataSectionAttr>() ||
2999 D->
hasAttr<PragmaClangRodataSectionAttr>())
3007 if (D->
hasAttr<WeakImportAttr>())
3017 if (D->
hasAttr<AlignedAttr>())
3026 if (FD->isBitField())
3028 if (FD->
hasAttr<AlignedAttr>())
3045 if (IsConstantVariable)
3046 return llvm::GlobalVariable::WeakODRLinkage;
3048 return llvm::GlobalVariable::WeakAnyLinkage;
3054 return llvm::GlobalValue::AvailableExternallyLinkage;
3068 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3085 return llvm::Function::WeakODRLinkage;
3090 if (!
getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3092 CodeGenOpts.NoCommon))
3093 return llvm::GlobalVariable::CommonLinkage;
3099 if (D->
hasAttr<SelectAnyAttr>())
3100 return llvm::GlobalVariable::WeakODRLinkage;
3108 const VarDecl *VD,
bool IsConstant) {
3116 llvm::Function *newFn) {
3118 if (old->use_empty())
return;
3120 llvm::Type *newRetTy = newFn->getReturnType();
3124 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3126 llvm::Value::use_iterator use = ui++;
3127 llvm::User *user = use->getUser();
3131 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3132 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3138 llvm::CallSite callSite(user);
3139 if (!callSite)
continue;
3140 if (!callSite.isCallee(&*use))
continue;
3144 if (callSite->getType() != newRetTy && !callSite->use_empty())
3149 llvm::AttributeList oldAttrs = callSite.getAttributes();
3152 unsigned newNumArgs = newFn->arg_size();
3153 if (callSite.arg_size() < newNumArgs)
continue;
3158 bool dontTransform =
false;
3159 for (llvm::Argument &A : newFn->args()) {
3160 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3161 dontTransform =
true;
3166 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3174 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3177 callSite.getOperandBundlesAsDefs(newBundles);
3179 llvm::CallSite newCall;
3180 if (callSite.isCall()) {
3182 callSite.getInstruction());
3184 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3186 oldInvoke->getNormalDest(),
3187 oldInvoke->getUnwindDest(),
3188 newArgs, newBundles,
"",
3189 callSite.getInstruction());
3193 if (!newCall->getType()->isVoidTy())
3194 newCall->takeName(callSite.getInstruction());
3195 newCall.setAttributes(llvm::AttributeList::get(
3196 newFn->getContext(), oldAttrs.getFnAttributes(),
3197 oldAttrs.getRetAttributes(), newArgAttrs));
3198 newCall.setCallingConv(callSite.getCallingConv());
3201 if (!callSite->use_empty())
3202 callSite->replaceAllUsesWith(newCall.getInstruction());
3205 if (callSite->getDebugLoc())
3206 newCall->setDebugLoc(callSite->getDebugLoc());
3208 callSite->eraseFromParent();
3222 llvm::Function *NewFn) {
3224 if (!isa<llvm::Function>(Old))
return;
3243 void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
3244 llvm::GlobalValue *GV) {
3245 const auto *D = cast<FunctionDecl>(GD.
getDecl());
3252 if (!GV || (GV->getType()->getElementType() != Ty))
3258 if (!GV->isDeclaration())
3265 auto *Fn = cast<llvm::Function>(GV);
3281 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
3282 AddGlobalCtor(Fn, CA->getPriority());
3283 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
3284 AddGlobalDtor(Fn, DA->getPriority());
3285 if (D->
hasAttr<AnnotateAttr>())
3289 void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
3290 const auto *D = cast<ValueDecl>(GD.
getDecl());
3291 const AliasAttr *AA = D->
getAttr<AliasAttr>();
3292 assert(AA &&
"Not an alias?");
3296 if (AA->getAliasee() == MangledName) {
3297 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3304 if (Entry && !Entry->isDeclaration())
3307 Aliases.push_back(GD);
3313 llvm::Constant *Aliasee;
3314 if (isa<llvm::FunctionType>(DeclTy))
3315 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3318 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3319 llvm::PointerType::getUnqual(DeclTy),
3327 if (GA->getAliasee() == Entry) {
3328 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3332 assert(Entry->isDeclaration());
3341 GA->takeName(Entry);
3343 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3345 Entry->eraseFromParent();
3347 GA->setName(MangledName);
3355 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3358 if (
const auto *VD = dyn_cast<VarDecl>(D))
3359 if (VD->getTLSKind())
3365 void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
3366 const auto *D = cast<ValueDecl>(GD.
getDecl());
3367 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
3368 assert(IFA &&
"Not an ifunc?");
3372 if (IFA->getResolver() == MangledName) {
3373 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3379 if (Entry && !Entry->isDeclaration()) {
3382 DiagnosedConflictingDefinitions.insert(GD).second) {
3383 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name);
3385 diag::note_previous_definition);
3390 Aliases.push_back(GD);
3393 llvm::Constant *Resolver =
3394 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3396 llvm::GlobalIFunc *GIF =
3400 if (GIF->getResolver() == Entry) {
3401 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3404 assert(Entry->isDeclaration());
3413 GIF->takeName(Entry);
3415 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3417 Entry->eraseFromParent();
3419 GIF->setName(MangledName);
3430 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3433 bool &IsUTF16,
unsigned &StringLength) {
3434 StringRef String = Literal->
getString();
3435 unsigned NumBytes = String.size();
3439 StringLength = NumBytes;
3440 return *Map.insert(std::make_pair(String,
nullptr)).first;
3447 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
3448 llvm::UTF16 *ToPtr = &ToBuf[0];
3450 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3451 ToPtr + NumBytes, llvm::strictConversion);
3454 StringLength = ToPtr - &ToBuf[0];
3458 return *Map.insert(std::make_pair(
3459 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3460 (StringLength + 1) * 2),
3466 unsigned StringLength = 0;
3467 bool isUTF16 =
false;
3468 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3473 if (
auto *C = Entry.second)
3476 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
3477 llvm::Constant *Zeros[] = { Zero, Zero };
3480 if (!CFConstantStringClassRef) {
3482 Ty = llvm::ArrayType::get(Ty, 0);
3483 llvm::Constant *GV =
3490 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3493 for (
const auto &Result : DC->
lookup(&II))
3494 if ((VD = dyn_cast<VarDecl>(Result)))
3497 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3498 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3501 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3507 CFConstantStringClassRef =
3508 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3516 auto Fields = Builder.beginStruct(STy);
3519 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3522 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3525 llvm::Constant *C =
nullptr;
3527 auto Arr = llvm::makeArrayRef(
3528 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3529 Entry.first().size() / 2);
3530 C = llvm::ConstantDataArray::get(VMContext, Arr);
3532 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3538 new llvm::GlobalVariable(
getModule(), C->getType(),
true,
3539 llvm::GlobalValue::PrivateLinkage, C,
".str");
3540 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3552 GV->setSection(isUTF16 ?
"__TEXT,__ustring" 3553 :
"__TEXT,__cstring,cstring_literals");
3556 llvm::Constant *Str =
3557 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3561 Str = llvm::ConstantExpr::getBitCast(Str,
Int8PtrTy);
3566 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3571 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
3573 llvm::GlobalVariable::PrivateLinkage);
3574 switch (
getTriple().getObjectFormat()) {
3575 case llvm::Triple::UnknownObjectFormat:
3576 llvm_unreachable(
"unknown file format");
3577 case llvm::Triple::COFF:
3578 case llvm::Triple::ELF:
3579 case llvm::Triple::Wasm:
3580 GV->setSection(
"cfstring");
3582 case llvm::Triple::MachO:
3583 GV->setSection(
"__DATA,__cfstring");
3592 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
3596 if (ObjCFastEnumerationStateType.isNull()) {
3608 for (
size_t i = 0; i < 4; ++i) {
3613 FieldTypes[i],
nullptr,
3625 return ObjCFastEnumerationStateType;
3639 Str.resize(CAT->getSize().getZExtValue());
3640 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
3644 llvm::Type *ElemTy = AType->getElementType();
3645 unsigned NumElements = AType->getNumElements();
3648 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3650 Elements.reserve(NumElements);
3652 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3654 Elements.resize(NumElements);
3655 return llvm::ConstantDataArray::get(VMContext, Elements);
3658 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3660 Elements.reserve(NumElements);
3662 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3664 Elements.resize(NumElements);
3665 return llvm::ConstantDataArray::get(VMContext, Elements);
3668 static llvm::GlobalVariable *
3673 unsigned AddrSpace = 0;
3679 auto *GV =
new llvm::GlobalVariable(
3680 M, C->getType(), !CGM.
getLangOpts().WritableStrings, LT, C, GlobalName,
3681 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3683 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3684 if (GV->isWeakForLinker()) {
3685 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
3686 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3700 llvm::GlobalVariable **Entry =
nullptr;
3701 if (!LangOpts.WritableStrings) {
3702 Entry = &ConstantStringMap[C];
3703 if (
auto GV = *Entry) {
3711 StringRef GlobalVariableName;
3712 llvm::GlobalValue::LinkageTypes LT;
3717 if (!LangOpts.WritableStrings &&
3718 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3720 llvm::raw_svector_ostream Out(MangledNameBuffer);
3723 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3724 GlobalVariableName = MangledNameBuffer;
3726 LT = llvm::GlobalValue::PrivateLinkage;
3727 GlobalVariableName = Name;
3734 SanitizerMD->reportGlobalToASan(GV, S->
getStrTokenLoc(0),
"<string literal>",
3753 const std::string &Str,
const char *GlobalName) {
3754 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3759 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
3762 llvm::GlobalVariable **Entry =
nullptr;
3763 if (!LangOpts.WritableStrings) {
3764 Entry = &ConstantStringMap[C];
3765 if (
auto GV = *Entry) {
3766 if (Alignment.getQuantity() > GV->getAlignment())
3767 GV->setAlignment(Alignment.getQuantity());
3774 GlobalName =
".str";
3777 GlobalName, Alignment);
3793 MaterializedType = E->
getType();
3797 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3804 llvm::raw_svector_ostream Out(Name);
3806 VD, E->getManglingNumber(), Out);
3809 if (E->getStorageDuration() ==
SD_Static) {
3823 Value = &EvalResult.
Val;
3829 llvm::Constant *InitialValue =
nullptr;
3830 bool Constant =
false;
3834 emitter.emplace(*
this);
3835 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
3838 Type = InitialValue->getType();
3846 llvm::GlobalValue::LinkageTypes
Linkage =
3850 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3854 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3862 auto *GV =
new llvm::GlobalVariable(
3863 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3864 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
3865 if (emitter) emitter->finalize(GV);
3869 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3870 if (VD->getTLSKind())
3872 llvm::Constant *CV = GV;
3878 MaterializedGlobalTemporaryMap[E] = CV;
3884 void CodeGenModule::EmitObjCPropertyImplementations(
const 3898 const_cast<ObjCImplementationDecl *>(D), PID);
3902 const_cast<ObjCImplementationDecl *>(D), PID);
3911 if (ivar->getType().isDestructedType())
3981 EmitDeclContext(LSD);
3984 void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
3985 for (
auto *I : DC->
decls()) {
3991 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3992 for (
auto *M : OID->methods())
4007 case Decl::CXXConversion:
4008 case Decl::CXXMethod:
4009 case Decl::Function:
4016 case Decl::CXXDeductionGuide:
4021 case Decl::Decomposition:
4022 case Decl::VarTemplateSpecialization:
4024 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
4025 for (
auto *B : DD->bindings())
4026 if (
auto *HD = B->getHoldingVar())
4032 case Decl::IndirectField:
4036 case Decl::Namespace:
4037 EmitDeclContext(cast<NamespaceDecl>(D));
4039 case Decl::ClassTemplateSpecialization: {
4040 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4043 Spec->hasDefinition())
4044 DebugInfo->completeTemplateDefinition(*Spec);
4046 case Decl::CXXRecord:
4050 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4053 for (
auto *I : cast<CXXRecordDecl>(D)->decls())
4054 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4058 case Decl::UsingShadow:
4059 case Decl::ClassTemplate:
4060 case Decl::VarTemplate:
4061 case Decl::VarTemplatePartialSpecialization:
4062 case Decl::FunctionTemplate:
4063 case Decl::TypeAliasTemplate:
4069 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4071 case Decl::NamespaceAlias:
4073 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4075 case Decl::UsingDirective:
4077 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4079 case Decl::CXXConstructor:
4082 case Decl::CXXDestructor:
4086 case Decl::StaticAssert:
4093 case Decl::ObjCInterface:
4094 case Decl::ObjCCategory:
4097 case Decl::ObjCProtocol: {
4098 auto *Proto = cast<ObjCProtocolDecl>(D);
4099 if (Proto->isThisDeclarationADefinition())
4104 case Decl::ObjCCategoryImpl:
4107 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4110 case Decl::ObjCImplementation: {
4111 auto *OMD = cast<ObjCImplementationDecl>(D);
4112 EmitObjCPropertyImplementations(OMD);
4113 EmitObjCIvarInitializations(OMD);
4118 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
4119 OMD->getClassInterface()), OMD->getLocation());
4122 case Decl::ObjCMethod: {
4123 auto *OMD = cast<ObjCMethodDecl>(D);
4129 case Decl::ObjCCompatibleAlias:
4130 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4133 case Decl::PragmaComment: {
4134 const auto *PCD = cast<PragmaCommentDecl>(D);
4135 switch (PCD->getCommentKind()) {
4137 llvm_unreachable(
"unexpected pragma comment kind");
4152 case Decl::PragmaDetectMismatch: {
4153 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4158 case Decl::LinkageSpec:
4159 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4162 case Decl::FileScopeAsm: {
4164 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4167 if (LangOpts.OpenMPIsDevice)
4169 auto *AD = cast<FileScopeAsmDecl>(D);
4170 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4174 case Decl::Import: {
4175 auto *Import = cast<ImportDecl>(D);
4178 if (!ImportedModules.insert(Import->getImportedModule()))
4182 if (!Import->getImportedOwningModule()) {
4184 DI->EmitImportDecl(*Import);
4188 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4190 Visited.insert(Import->getImportedModule());
4191 Stack.push_back(Import->getImportedModule());
4193 while (!Stack.empty()) {
4195 if (!EmittedModuleInitializers.insert(Mod).second)
4204 Sub != SubEnd; ++Sub) {
4207 if ((*Sub)->IsExplicit)
4210 if (Visited.insert(*Sub).second)
4211 Stack.push_back(*Sub);
4218 EmitDeclContext(cast<ExportDecl>(D));
4221 case Decl::OMPThreadPrivate:
4225 case Decl::OMPDeclareReduction:
4233 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
4240 if (!CodeGenOpts.CoverageMapping)
4243 case Decl::CXXConversion:
4244 case Decl::CXXMethod:
4245 case Decl::Function:
4246 case Decl::ObjCMethod:
4247 case Decl::CXXConstructor:
4248 case Decl::CXXDestructor: {
4249 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4254 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4255 if (I == DeferredEmptyCoverageMappingDecls.end())
4256 DeferredEmptyCoverageMappingDecls[D] =
true;
4266 if (!CodeGenOpts.CoverageMapping)
4268 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4269 if (Fn->isTemplateInstantiation())
4272 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4273 if (I == DeferredEmptyCoverageMappingDecls.end())
4274 DeferredEmptyCoverageMappingDecls[D] =
false;
4284 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
4287 const Decl *D = Entry.first;
4289 case Decl::CXXConversion:
4290 case Decl::CXXMethod:
4291 case Decl::Function:
4292 case Decl::ObjCMethod: {
4299 case Decl::CXXConstructor: {
4306 case Decl::CXXDestructor: {
4323 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4324 return llvm::ConstantInt::get(i64, PtrInt);
4328 llvm::NamedMDNode *&GlobalMetadata,
4330 llvm::GlobalValue *Addr) {
4331 if (!GlobalMetadata)
4333 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
4336 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4339 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
4347 void CodeGenModule::EmitStaticExternCAliases() {
4352 for (
auto &I : StaticExternCValues) {
4354 llvm::GlobalValue *Val = I.second;
4362 auto Res = Manglings.find(MangledName);
4363 if (Res == Manglings.end())
4365 Result = Res->getValue();
4376 void CodeGenModule::EmitDeclMetadata() {
4377 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4379 for (
auto &I : MangledDeclNames) {
4380 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
4390 void CodeGenFunction::EmitDeclMetadata() {
4391 if (LocalDeclMap.empty())
return;
4396 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
4398 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4400 for (
auto &I : LocalDeclMap) {
4401 const Decl *D = I.first;
4403 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4405 Alloca->setMetadata(
4406 DeclPtrKind, llvm::MDNode::get(
4407 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4408 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4415 void CodeGenModule::EmitVersionIdentMetadata() {
4416 llvm::NamedMDNode *IdentMetadata =
4417 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
4419 llvm::LLVMContext &Ctx = TheModule.getContext();
4421 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4422 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4425 void CodeGenModule::EmitTargetMetadata() {
4432 for (
unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4433 auto Val = *(MangledDeclNames.begin() + I);
4440 void CodeGenModule::EmitCoverageFile() {
4445 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
4449 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
4450 llvm::LLVMContext &Ctx = TheModule.getContext();
4451 auto *CoverageDataFile =
4453 auto *CoverageNotesFile =
4455 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4456 llvm::MDNode *CU = CUNode->getOperand(i);
4457 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4458 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4462 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4465 assert(Uuid.size() == 36);
4466 for (
unsigned i = 0; i < 36; ++i) {
4467 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] ==
'-');
4472 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4474 llvm::Constant *Field3[8];
4475 for (
unsigned Idx = 0; Idx < 8; ++Idx)
4476 Field3[Idx] = llvm::ConstantInt::get(
4477 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4479 llvm::Constant *Fields[4] = {
4480 llvm::ConstantInt::get(
Int32Ty, Uuid.substr(0, 8), 16),
4481 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(9, 4), 16),
4482 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(14, 4), 16),
4483 llvm::ConstantArray::get(llvm::ArrayType::get(
Int8Ty, 8), Field3)
4486 return llvm::ConstantStruct::getAnon(Fields);
4495 return llvm::Constant::getNullValue(
Int8PtrTy);
4498 LangOpts.ObjCRuntime.isGNUFamily())
4506 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
4508 for (
auto RefExpr : D->
varlists()) {
4509 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4511 VD->getAnyInitializer() &&
4512 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
4517 VD, Addr, RefExpr->getLocStart(), PerformInit))
4518 CXXGlobalInits.push_back(InitFunction);
4528 std::string OutName;
4529 llvm::raw_string_ostream Out(OutName);
4558 for (
auto &Param : FnType->param_types())
4563 GeneralizedParams, FnType->getExtProtoInfo());
4570 llvm_unreachable(
"Encountered unknown FunctionType");
4576 llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.
getCanonicalType()];
4581 std::string OutName;
4582 llvm::raw_string_ostream Out(OutName);
4584 Out <<
".generalized";
4599 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4600 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4601 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4602 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4603 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4604 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4605 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4606 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4612 llvm::Metadata *MD =
4614 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
4616 if (CodeGenOpts.SanitizeCfiCrossDso)
4619 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4622 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
4623 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
4631 StringRef TargetCPU = Target.getTargetOpts().CPU;
4632 if (
const auto *TD = FD->
getAttr<TargetAttr>()) {
4634 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4636 ParsedAttr.Features.erase(
4637 llvm::remove_if(ParsedAttr.Features,
4638 [&](
const std::string &Feat) {
4639 return !Target.isValidFeatureName(
4640 StringRef{Feat}.substr(1));
4642 ParsedAttr.Features.end());
4646 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
4647 Target.getTargetOpts().FeaturesAsWritten.begin(),
4648 Target.getTargetOpts().FeaturesAsWritten.end());
4650 if (ParsedAttr.Architecture !=
"" &&
4651 Target.isValidCPUName(ParsedAttr.Architecture))
4652 TargetCPU = ParsedAttr.Architecture;
4658 Target.initFeatureMap(FeatureMap,
getDiags(), TargetCPU,
4659 ParsedAttr.Features);
4661 Target.initFeatureMap(FeatureMap,
getDiags(), TargetCPU,
4662 Target.getTargetOpts().Features);
4668 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&
getModule());
4677 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()},
false);
4679 "__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
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...
const CXXDestructorDecl * getDestructor() const
An instance of this class is created to represent a function declaration or definition.
llvm::IntegerType * IntTy
int
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.
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
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))
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
llvm::LLVMContext & getLLVMContext()
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
llvm::CallingConv::ID BuiltinCC
The standard implementation of ConstantInitBuilder used in Clang.
llvm::CallingConv::ID getBuiltinCC() const
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...
bool isRecordType() const
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
Decl - This represents one declaration (or definition), e.g.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
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...
void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV)
Set attributes which must be preserved by an alias.
Defines the C++ template declaration subclasses.
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
NamespaceDecl - Represent a C++ namespace.
Represents a call to a C++ constructor.
virtual void completeDefinition()
completeDefinition - Notes 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...
static const llvm::GlobalObject * getAliasedGlobal(const llvm::GlobalIndirectSymbol &GIS)
Linkage getLinkage() const
Determine the linkage of this type.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
const Expr * getAnyInitializer() const
getAnyInitializer - Get the initializer for this variable, no matter which declaration it is attached...
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)
'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.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void setFunctionDefinitionAttributes(const FunctionDecl *D, llvm::Function *F)
Set attributes for a global definition.
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.
void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F)
Set the DLL storage class on F.
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
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
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...
RecordDecl - 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.
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
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.
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
llvm::IntegerType * SizeTy
StructorType getFromDtorType(CXXDtorType T)
void startDefinition()
Starts the definition of this tag declaration.
bool isReferenceType() const
SanitizerMask Mask
Bitmask of enabled sanitizers.
This declaration is definitely a definition.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
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
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.
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
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.
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.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D, ForDefinition_t IsForDefinition) const
Set the visibility for the given LLVM GlobalValue.
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.
submodule_iterator submodule_end()
static TBAAAccessInfo getIncompleteInfo()
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
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.
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
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
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.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M, ForDefinition_t IsForDefinition) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
llvm::CallingConv::ID getRuntimeCC() const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *FD)
Exposes information about the current target.
void SetLLVMFunctionAttributes(const Decl *D, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
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.
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Expr - 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.
const FunctionProtoType * T
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.
llvm::CallingConv::ID getBuiltinCC() const
Return the calling convention to use for compiler builtins.
void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
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.
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...
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
TLSKind getTLSKind() const
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
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.
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)
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.
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
CGOpenMPRuntime(CodeGenModule &CGM)
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::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage)
Will return a global variable of the given type.
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.
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.
SourceLocation getLocStart() const LLVM_READONLY
QualType getWideCharType() const
Return the type of wide characters.
unsigned char IntAlignInBytes
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.
Encodes a location in the source.
virtual bool shouldMangleStringLiteral(const StringLiteral *SL)=0
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)"...
TagDecl - Represents the declaration of a struct/union/class/enum.
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)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
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
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.
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.
void CreateFunctionTypeMetadata(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
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.
std::vector< Structor > CtorList
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...
EvalResult is a struct with detailed info about an evaluated expression.
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
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
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.
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
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
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...
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...
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.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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
isStaticLocal - 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.
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.
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).
TranslationUnitDecl * getTranslationUnitDecl() const
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
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.
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.
void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method...
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...
virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, CXXDtorType DT) const =0
Returns true if the given destructor type should be emitted as a linkonce delegating thunk...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body - that is, if it is a non-delete...
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
CGCXXABI & getCXXABI() const
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for...
TranslationUnitDecl - 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
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()
NamedDecl - This represents a decl with 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)
SourceLocation getLocStart() const LLVM_READONLY
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 singal 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
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...
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