73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/STLExtras.h"
75#include "llvm/ADT/SetVector.h"
76#include "llvm/ADT/SmallPtrSet.h"
77#include "llvm/Support/TimeProfiler.h"
90 std::optional<tok::TokenKind> ExpectedToken) {
93 std::optional<Token> NextToken =
97 if (ExpectedToken && NextToken->getKind() != *ExpectedToken)
113 StringRef Platform) {
115 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
116 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
118 WarnedDarwinSDKInfoMissing =
true;
124 if (CachedDarwinSDKInfo)
125 return CachedDarwinSDKInfo->get();
127 PP.getFileManager().getVirtualFileSystem(),
128 PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
129 if (SDKInfo && *SDKInfo) {
130 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
131 return CachedDarwinSDKInfo->get();
134 llvm::consumeError(SDKInfo.takeError());
135 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
141 std::string InventedName;
142 llvm::raw_string_ostream
OS(InventedName);
145 OS <<
"auto:" << Index + 1;
160 Policy.
Bool = BoolMacro->isObjectLike() &&
161 BoolMacro->getNumTokens() == 1 &&
162 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
192 FileID PrevFID)
override {
200 if (llvm::timeTraceProfilerEnabled()) {
202 ProfilerStack.push_back(llvm::timeTraceAsyncProfilerBegin(
203 "Source", FE ? FE->
getName() : StringRef(
"<unknown>")));
206 IncludeStack.push_back(IncludeLoc);
207 S->DiagnoseNonDefaultPragmaAlignPack(
214 if (!IncludeStack.empty()) {
215 if (llvm::timeTraceProfilerEnabled())
216 llvm::timeTraceProfilerEnd(ProfilerStack.pop_back_val());
218 S->DiagnoseNonDefaultPragmaAlignPack(
220 IncludeStack.pop_back_val());
231 S->AnalysisWarnings.clearPolicyCache();
232 S->clearDocumentationDiagsCache();
241 StringRef Group = Str.substr(2);
243 if (S->PP.getDiagnostics().getDiagnosticIDs()->getDiagnosticsInGroup(
244 Flavor, Group, GroupDiags))
251 S->AnalysisWarnings.getPolicyOverrides();
254 case diag::warn_unreachable:
255 case diag::warn_unreachable_break:
256 case diag::warn_unreachable_return:
257 case diag::warn_unreachable_loop_increment:
258 Override.enableCheckUnreachable =
true;
260 case diag::warn_double_lock:
261 Override.enableThreadSafetyAnalysis =
true;
263 case diag::warn_use_in_invalid_state:
264 Override.enableConsumedAnalysis =
true;
315 LangOpts.getMSPointerToMemberRepresentationMethod()),
325 FullyCheckedComparisonCategories(
335 LoadedExternalKnownNamespaces =
false;
348 Context.setDeclVisibilityCallback(
359 OpenMP().InitDataSharingAttributesStack();
361 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
362 std::make_unique<sema::SemaPPCallbacks>();
363 SemaPPCallbackHandler = Callbacks.get();
364 PP.addPPCallbacks(std::move(Callbacks));
365 SemaPPCallbackHandler->set(*
this);
371void Sema::anchor() {}
383 if (
Context.getTargetInfo().hasBuiltinMSVaList())
384 (void)
Context.getBuiltinMSVaListDecl();
385 if (
Context.getTargetInfo().hasBuiltinZOSVaList())
386 (void)
Context.getBuiltinZOSVaListDecl();
387 (void)
Context.getBuiltinVaListDecl();
390 SC->InitializeSema(*
this);
394 = dyn_cast_or_null<ExternalSemaSource>(
Context.getExternalSource()))
395 ExternalSema->InitializeSema(*
this);
405 if (
Context.getTargetInfo().hasInt128Type() ||
407 Context.getAuxTargetInfo()->hasInt128Type())) {
467 if (OCLCompatibleVersion >= 200) {
496 auto AddPointerSizeDependentTypes = [&]() {
498 auto AtomicIntPtrT =
Context.getAtomicType(
Context.getIntPtrType());
499 auto AtomicUIntPtrT =
Context.getAtomicType(
Context.getUIntPtrType());
500 auto AtomicPtrDiffT =
509 AddPointerSizeDependentTypes();
517 std::vector<QualType> Atomic64BitTypes;
525 Atomic64BitTypes.push_back(AtomicDoubleT);
528 auto AtomicULongT =
Context.getAtomicType(
Context.UnsignedLongTy);
534 AddPointerSizeDependentTypes();
539#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
540 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
541 addImplicitTypedef(#ExtType, Context.Id##Ty); \
543#include "clang/Basic/OpenCLExtensionTypes.def"
546 if (
Context.getTargetInfo().hasAArch64ACLETypes() ||
548 Context.getAuxTargetInfo()->hasAArch64ACLETypes())) {
549#define SVE_TYPE(Name, Id, SingletonId) \
550 addImplicitTypedef(#Name, Context.SingletonId);
551#define NEON_VECTOR_TYPE(Name, BaseType, ElBits, NumEls, VectorKind) \
552 addImplicitTypedef( \
553 #Name, Context.getVectorType(Context.BaseType, NumEls, VectorKind));
554#include "clang/Basic/AArch64ACLETypes.def"
557 if (
Context.getTargetInfo().getTriple().isPPC64()) {
558#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
559 addImplicitTypedef(#Name, Context.Id##Ty);
560#include "clang/Basic/PPCTypes.def"
561#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
562 addImplicitTypedef(#Name, Context.Id##Ty);
563#include "clang/Basic/PPCTypes.def"
566 if (
Context.getTargetInfo().hasRISCVVTypes()) {
567#define RVV_TYPE(Name, Id, SingletonId) \
568 addImplicitTypedef(Name, Context.SingletonId);
569#include "clang/Basic/RISCVVTypes.def"
572 if (
Context.getTargetInfo().getTriple().isWasm() &&
573 Context.getTargetInfo().hasFeature(
"reference-types")) {
574#define WASM_TYPE(Name, Id, SingletonId) \
575 addImplicitTypedef(Name, Context.SingletonId);
576#include "clang/Basic/WebAssemblyReferenceTypes.def"
579 if (
Context.getTargetInfo().hasAMDGPUTypes() ||
581 (
Context.getAuxTargetInfo()->hasAMDGPUTypes()))) {
582#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
583 addImplicitTypedef(Name, Context.SingletonId);
584#include "clang/Basic/AMDGPUTypes.def"
587 if (
Context.getTargetInfo().getTriple().isSPIRV() ||
589 Context.getAuxTargetInfo()->getTriple().isSPIRV())) {
590#define SPIRV_TYPE(Name, Id, SingletonId) \
591 addImplicitTypedef(Name, Context.SingletonId);
592#include "clang/Basic/SPIRVTypes.def"
595 if (
Context.getTargetInfo().hasBuiltinMSVaList()) {
601 if (
Context.getTargetInfo().hasBuiltinZOSVaList()) {
614 "failed to clean up an InstantiatingTemplate?");
628 = dyn_cast_or_null<ExternalSemaSource>(
Context.getExternalSource()))
629 ExternalSema->ForgetSema();
632 Context.setDeclVisibilityCallback(
nullptr);
635 for (
auto [_, Node] : SatisfactionCache)
641 OpenMP().DestroyDataSharingAttributesStack();
645 SemaPPCallbackHandler->reset();
649 llvm::function_ref<
void()> Fn) {
650 StackHandler.runWithSufficientStackSpace(Loc, Fn);
654 UnavailableAttr::ImplicitReason reason) {
657 if (!fn)
return false;
664 if (!
Context.getSourceManager().isInSystemHeader(loc))
668 if (fn->
hasAttr<UnavailableAttr>())
return true;
670 fn->
addAttr(UnavailableAttr::CreateImplicit(
Context,
"", reason, loc));
679 assert(E &&
"Cannot use with NULL ptr");
686 if (
auto *Ex = dyn_cast<MultiplexExternalSemaSource>(
ExternalSource.get()))
687 Ex->AddSource(std::move(E));
689 ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
694 llvm::errs() <<
"\n*** Semantic Analysis Stats:\n";
696 llvm::errs() <<
int(Trap->hasErrorOccurred())
697 <<
" SFINAE diagnostics trapped.\n";
715 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
723 if (SrcFX != DstFX) {
725 if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX))
726 Diag(Loc, diag::warn_invalid_add_func_effects) << Diff.effectName();
736 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
745 if (
Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
767 if (
Diags.getSuppressSystemWarnings() &&
768 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
788 (
"can't implicitly cast glvalue to prvalue with this cast "
793 case CK_LValueToRValue:
794 case CK_ArrayToPointerDecay:
795 case CK_FunctionToPointerDecay:
797 case CK_NonAtomicToAtomic:
798 case CK_HLSLArrayRValue:
799 case CK_HLSLAggregateSplatCast:
804 "can't cast prvalue to glvalue");
810 Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
828 if (Kind == CK_ArrayToPointerDecay) {
837 E = Materialized.
get();
848 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
849 if (
const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
861 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
862 ImpCast->setType(Ty);
863 ImpCast->setValueKind(
VK);
871 if ((Kind == CK_IntegralCast || Kind == CK_IntegralToBoolean ||
875 if (
const auto *SourceOBT = E->
getType()->
getAs<OverflowBehaviorType>()) {
877 Ty =
Context.getOverflowBehaviorType(SourceOBT->getBehaviorKind(), Ty);
899 llvm_unreachable(
"unknown scalar type kind");
910 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
914 for (
const auto *Spec :
Template->specializations())
921 if (FD->hasBody(DeclToCheck))
927 if (DeclToCheck != FD)
931 if (
const VarDecl *VD = dyn_cast<VarDecl>(D)) {
937 if (VD->isReferenced() &&
938 VD->mightBeUsableInConstantExpressions(SemaRef->
Context))
944 for (
const auto *Spec :
Template->specializations())
957 if (DeclToCheck != VD)
965 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
966 return FD->isExternC();
998 if (ND->
hasAttr<WeakRefAttr>())
continue;
1003 if (ND->
hasAttr<DLLImportAttr>() || ND->
hasAttr<DLLExportAttr>()) {
1010 if (
const auto *FD = dyn_cast<FunctionDecl>(ND)) {
1011 if (FD->isDefined())
1013 if (FD->isExternallyVisible() &&
1015 !FD->getMostRecentDecl()->isInlined() &&
1016 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
1018 if (FD->getBuiltinID())
1024 if (VD->isExternallyVisible() &&
1026 !VD->getMostRecentDecl()->isInline() &&
1027 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
1032 if (VD->isKnownToBeDefined())
1036 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
1066 ? diag::ext_undefined_internal_type
1067 : diag::err_undefined_internal_type)
1073 bool IsImplicitBase =
false;
1074 if (
const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
1075 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
1076 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
1077 llvm::omp::TraitProperty::
1078 implementation_extension_disable_implicit_base)) {
1081 IsImplicitBase = BaseD->isImplicit() &&
1082 Func->getIdentifier()->isMangledOpenMPVariantName();
1088 }
else if (
auto *FD = dyn_cast<FunctionDecl>(VD)) {
1090 assert(FD->getMostRecentDecl()->isInlined() &&
1091 "used object requires definition but isn't inline or internal?");
1095 assert(
cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
1096 "used var requires definition but isn't inline or internal?");
1100 S.
Diag(UseLoc, diag::note_used_here);
1110 for (
auto &WeakID : WeakIDs)
1120 for (
auto &ExtnameID : ExtnameIDs)
1133 RecordCompleteMap::iterator
Cache = MNCComplete.find(RD);
1134 if (
Cache != MNCComplete.end())
1135 return Cache->second;
1143 Complete = M->isDefined() || M->isDefaulted() ||
1150 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
1151 F->getTemplatedDecl()->isDefined();
1152 else if (
const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
1153 if (R->isInjectedClassName())
1155 if (R->hasDefinition())
1176 RecordCompleteMap::iterator
Cache = RecordsComplete.find(RD);
1177 if (
Cache != RecordsComplete.end())
1178 return Cache->second;
1187 if (
CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
1194 dyn_cast<FunctionDecl>(
Friend->getFriendDecl()))
1225 if (TD->isReferenced())
1227 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1236 HandleStartOfHeaderUnit();
1243 llvm::TimeTraceScope TimeScope(
"PerformPendingInstantiations");
1280 for (
auto PII : Pending)
1281 if (
auto Func = dyn_cast<FunctionDecl>(PII.first))
1282 Func->setInstantiationIsPending(
true);
1284 Pending.begin(), Pending.end());
1288 llvm::TimeTraceScope TimeScope(
"PerformPendingInstantiations");
1295 "end of TU template instantiation should not create more "
1296 "late-parsed templates");
1301 &&
"reached end of translation unit with a pool attached?");
1305 if (
PP.isCodeCompletionEnabled())
1314 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1331 if (
LangOpts.PCHInstantiateTemplates) {
1332 llvm::TimeTraceScope TimeScope(
"PerformPendingInstantiations");
1358 return ShouldRemoveFromUnused(this, DD);
1364 if (!
PP.isIncrementalProcessingEnabled())
1372 if (WeakIDs.second.empty())
1377 if (PrevDecl !=
nullptr &&
1379 for (
const auto &WI : WeakIDs.second)
1380 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1383 for (
const auto &WI : WeakIDs.second)
1384 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1392 if (!
Diags.hasErrorOccurred()) {
1399 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1401 Diag(ModuleScopes.back().BeginLoc,
1402 diag::err_module_declaration_missing_after_global_module_introducer);
1414 diag::err_module_declaration_missing);
1420 auto DoesModNeedInit = [
this](
Module *M) {
1422 auto *VD = dyn_cast<VarDecl>(D);
1428 (InitDecl && !InitDecl->hasConstantInitialization()) ||
1433 for (
auto [Exported, _] : M->Exports)
1434 if (Exported->isNamedModuleInterfaceHasInit())
1443 CurrentModule->NamedModuleHasInit =
1444 DoesModNeedInit(CurrentModule) ||
1445 llvm::any_of(CurrentModule->submodules(), DoesModNeedInit);
1451 if (
Module *CurrentModule =
PP.getCurrentModule()) {
1452 ModuleMap &ModMap =
PP.getHeaderSearchInfo().getModuleMap();
1455 Stack.push_back(CurrentModule);
1456 while (!Stack.empty()) {
1457 Module *Mod = Stack.pop_back_val();
1469 Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
1481 if (!PendingInlineFuncDecls.empty()) {
1482 for (
auto *FD : PendingInlineFuncDecls) {
1483 bool DefInPMF =
false;
1484 if (
auto *FDD = FD->getDefinition()) {
1485 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1489 Diag(FD->getLocation(), diag::err_export_inline_not_defined) << DefInPMF;
1493 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
1496 PendingInlineFuncDecls.clear();
1511 for (TentativeDefinitionsType::iterator
1527 llvm::APInt One(
Context.getTypeSize(
Context.getSizeType()),
true);
1532 diag::err_tentative_def_incomplete_type))
1543 unsigned DiagID = diag::warn_default_init_const_unsafe;
1546 DiagID = diag::warn_default_init_const;
1548 bool EmitCppCompat = !
Diags.isIgnored(
1549 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
1563 for (
const FieldDecl *FD : RD->fields())
1564 if (FD->hasAttr<ExplicitInitAttr>())
1565 Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
1571 Consumer.CompleteTentativeDefinition(VD);
1577 if (
PP.isIncrementalProcessingEnabled())
1582 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1585 Consumer.CompleteExternalDeclaration(D);
1591 Diag(Exported.NameLoc, diag::warn_failed_to_resolve_pragma) <<
"export";
1606 for (UnusedFileScopedDeclsType::iterator
1613 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1615 if (!FD->hasBody(DiagD))
1622 DiagRange.
setEnd(ASTTAL->RAngleLoc);
1626 << DiagD << DiagRange;
1628 if (FD->getStorageClass() ==
SC_Static &&
1629 !FD->isInlineSpecified() &&
1631 SourceMgr.getExpansionLoc(FD->getLocation())))
1633 diag::warn_unneeded_static_internal_decl)
1634 << DiagD << DiagRange;
1637 << 0 << DiagD << DiagRange;
1639 }
else if (!FD->isTargetMultiVersion() ||
1640 FD->isTargetMultiVersionDefault()) {
1641 if (FD->getDescribedFunctionTemplate())
1643 << 0 << DiagD << DiagRange;
1646 ? diag::warn_unused_member_function
1647 : diag::warn_unused_function)
1648 << DiagD << DiagRange;
1655 if (
const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
1657 VTSD->getTemplateArgsAsWritten())
1658 DiagRange.
setEnd(ASTTAL->RAngleLoc);
1662 << 1 << DiagD << DiagRange;
1665 << 1 << DiagD << DiagRange;
1669 !
PP.getLangOpts().IsHeaderFile)
1671 << DiagD << DiagRange;
1674 << DiagD << DiagRange;
1692 DeclDiags.push_back(LocAndDiag{Loc, std::move(PD)});
1698 const VarDecl *VD = Ref.first;
1706 llvm::sort(DeclDiags,
1707 [](
const LocAndDiag &LHS,
const LocAndDiag &RHS) ->
bool {
1710 return LHS.Loc < RHS.Loc;
1712 for (
const LocAndDiag &D : DeclDiags)
1722 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1723 if (RD && !RD->
isUnion() && !D->hasAttr<UnusedAttr>() &&
1725 Diag(D->getLocation(), diag::warn_unused_private_field)
1726 << D->getDeclName();
1734 for (
const auto &DeletedFieldInfo :
DeleteExprs) {
1736 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first,
DeleteExprLoc.first,
1744 if (
Context.hasAnyFunctionEffects())
1751 "Didn't unmark var as having its initializer parsed");
1753 if (!
PP.isIncrementalProcessingEnabled())
1756 checkExposure(
Context.getTranslationUnitDecl());
1787 return dyn_cast<FunctionDecl>(DC);
1794 return dyn_cast<ObjCMethodDecl>(DC);
1829 Trap->setErrorOccurred();
1838 Diags.setLastDiagnosticIgnored(
true);
1852 Trap->setErrorOccurred();
1861 Diags.setLastDiagnosticIgnored(
true);
1864 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1868 Diags.setLastDiagnosticIgnored(
true);
1883 if (!
Diags.getDiagnosticIDs()->isNote(DiagID))
1890 Diags.setLastDiagnosticIgnored(
true);
1900 if (!
Diags.EmitDiagnostic(DB))
1907 if (!
Diags.getDiagnosticIDs()->isNote(DiagID))
1914 auto *FD = dyn_cast<FunctionDecl>(
CurContext);
1920 for (
auto PDAt : Loc->second) {
1921 if (
Diags.getDiagnosticIDs()->isDefaultMappingAsError(
1922 PDAt.second.getDiagID()))
1937 for (
const auto &CallerInfo : FnIt->second) {
1940 S.
Diags.
Report(CallerInfo.Loc, diag::note_called_by) << CallerInfo.FD;
1946 const auto &
Next = NextIt->second.front();
1982class DeferredDiagnosticsEmitter
1985 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1988 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1991 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1997 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
2002 llvm::SetVector<CanonicalDeclPtr<const FunctionDecl>> FnsToEmit;
2005 bool ShouldEmitRootNode;
2010 unsigned InOMPDeviceContext;
2012 DeferredDiagnosticsEmitter(Sema &S)
2013 : Inherited(S), ShouldEmitRootNode(
false), InOMPDeviceContext(0) {}
2015 bool shouldVisitDiscardedStmt()
const {
return false; }
2017 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
2018 ++InOMPDeviceContext;
2019 Inherited::VisitOMPTargetDirective(Node);
2020 --InOMPDeviceContext;
2023 void visitUsedDecl(SourceLocation Loc, Decl *D) {
2026 if (
auto *FD = dyn_cast<FunctionDecl>(D))
2029 Inherited::visitUsedDecl(Loc, D);
2033 void VisitCalledDestructors(CXXDestructorDecl *DD) {
2034 const CXXRecordDecl *RD = DD->
getParent();
2037 for (
const FieldDecl *FD : RD->
fields()) {
2038 QualType FT = FD->getType();
2041 (ClassDecl->isBeingDefined() || ClassDecl->isCompleteDefinition()))
2042 if (CXXDestructorDecl *MemberDtor = ClassDecl->getDestructor())
2043 asImpl().visitUsedDecl(MemberDtor->getLocation(), MemberDtor);
2047 for (
const auto &Base : RD->
bases()) {
2048 QualType BaseType =
Base.getType();
2051 (BaseDecl->isBeingDefined() || BaseDecl->isCompleteDefinition()))
2052 if (CXXDestructorDecl *BaseDtor = BaseDecl->getDestructor())
2053 asImpl().visitUsedDecl(BaseDtor->getLocation(), BaseDtor);
2057 void VisitDeclStmt(DeclStmt *DS) {
2059 for (
auto *D : DS->
decls())
2060 if (
auto *VD = dyn_cast<VarDecl>(D))
2061 if (VD->isThisDeclarationADefinition() &&
2062 VD->needsDestruction(S.Context)) {
2063 QualType VT = VD->getType();
2065 ClassDecl && (ClassDecl->isBeingDefined() ||
2066 ClassDecl->isCompleteDefinition()))
2067 if (CXXDestructorDecl *Dtor = ClassDecl->getDestructor())
2068 asImpl().visitUsedDecl(
Dtor->getLocation(), Dtor);
2071 Inherited::VisitDeclStmt(DS);
2073 void checkVar(VarDecl *VD) {
2075 "Should only check file-scope variables");
2077 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
2078 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
2079 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
2081 ++InOMPDeviceContext;
2084 --InOMPDeviceContext;
2088 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
2089 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
2090 FunctionDecl *Caller = UsePath.empty() ?
nullptr : UsePath.back();
2091 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
2092 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
2095 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
2096 (ShouldEmitRootNode || InOMPDeviceContext))
2097 S.OpenMP().finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
2099 auto &Callers = S.DeviceKnownEmittedFns[FD];
2100 CanonicalDeclPtr<const FunctionDecl> CanonCaller(Caller);
2101 if (llvm::none_of(Callers, [CanonCaller](
const auto &
C) {
2102 return C.FD == CanonCaller;
2104 Callers.push_back({Caller, Loc});
2106 if (ShouldEmitRootNode || InOMPDeviceContext)
2107 FnsToEmit.insert(FD);
2110 if (!Done.insert(FD).second)
2112 InUsePath.insert(FD);
2113 UsePath.push_back(FD);
2119 if (
auto *Ctor = dyn_cast_or_null<CXXConstructorDecl>(
Definition)) {
2120 for (
auto *
Init : Ctor->inits())
2121 this->Visit(
Init->getInit());
2124 if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(FD))
2125 asImpl().VisitCalledDestructors(Dtor);
2127 InUsePath.erase(FD);
2130 void checkRecordedDecl(Decl *D) {
2131 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2132 ShouldEmitRootNode = S.getEmissionStatus(FD,
true) ==
2133 Sema::FunctionEmissionStatus::Emitted;
2134 checkFunc(SourceLocation(), FD);
2139 void emitDeferredDiags(
const FunctionDecl *FD) {
2140 auto It = S.DeviceDeferredDiags.find(FD);
2141 if (It == S.DeviceDeferredDiags.end())
2143 bool HasWarningOrError =
false;
2145 if (S.Diags.hasFatalErrorOccurred())
2147 const SourceLocation &Loc = PDAt.first;
2148 const PartialDiagnostic &PD = PDAt.second;
2149 HasWarningOrError |=
2150 S.getDiagnostics().getDiagnosticLevel(PD.
getDiagID(), Loc) >=
2153 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.
getDiagID()));
2157 if (HasWarningOrError)
2161 void emitCollectedDiags() {
2162 for (
const auto &FD : FnsToEmit)
2163 emitDeferredDiags(FD);
2175 auto ClassifyImplicitHDExplicitInst = [&]() {
2186 return getDiagnostics().getDiagnosticLevel(PDAt.second.getDiagID(),
2188 DiagnosticsEngine::Error;
2192 Pair.second.clear();
2199 ClassifyImplicitHDExplicitInst();
2203 DeferredDiagnosticsEmitter DDE(*
this);
2205 DDE.checkRecordedDecl(D);
2206 ClassifyImplicitHDExplicitInst();
2207 DDE.emitCollectedDiags();
2234Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K,
SourceLocation Loc,
2238 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
2239 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
2244 case K_ImmediateWithCallStack:
2245 ImmediateDiag.emplace(
2246 ImmediateDiagBuilder(S.
Diags.
Report(Loc, DiagID), S, DiagID));
2249 assert(Fn &&
"Must have a function to attach the deferred diag to.");
2251 PartialDiagId.emplace(
Diags.size());
2257Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
2258 : S(D.S), Loc(D.Loc), DiagID(D.DiagID),
Fn(D.
Fn),
2259 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
2260 PartialDiagId(D.PartialDiagId) {
2262 D.ShowCallStack =
false;
2263 D.ImmediateDiag.reset();
2264 D.PartialDiagId.reset();
2267Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
2268 if (ImmediateDiag) {
2271 ImmediateDiag.reset();
2273 if (ShowCallStack) {
2274 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
2276 if (IsWarningOrError)
2280 assert((!PartialDiagId || ShowCallStack) &&
2281 "Must always show call stack for deferred diags.");
2285Sema::SemaDiagnosticBuilder
2291 return LangOpts.OpenMPIsTargetDevice
2292 ?
OpenMP().diagIfOpenMPDeviceCode(Loc, DiagID, FD)
2293 :
OpenMP().diagIfOpenMPHostCode(Loc, DiagID, FD);
2295 return getLangOpts().CUDAIsDevice ?
CUDA().DiagIfDeviceCode(Loc, DiagID)
2296 :
CUDA().DiagIfHostCode(Loc, DiagID);
2299 return SYCL().DiagIfDeviceCode(Loc, DiagID);
2314 llvm::DenseSet<QualType> Visited;
2315 SYCL().deepTypeCheckForDevice(Loc, Visited, D);
2322 if (
const auto *MD = dyn_cast<CXXMethodDecl>(
C)) {
2323 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
2327 if (
const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
2328 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
2336 : dyn_cast_or_null<FunctionDecl>(D);
2338 auto CheckDeviceType = [&](
QualType Ty) {
2343 if (!
Context.getTargetInfo().hasBitIntType()) {
2350 <<
false << 0 <<
false
2351 << Ty <<
Context.getTargetInfo().getTriple().str();
2358 bool LongDoubleMismatched =
false;
2360 const llvm::fltSemantics &Sem =
Context.getFloatTypeSemantics(Ty);
2361 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
2362 !
Context.getTargetInfo().hasFloat128Type()) ||
2363 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
2364 !
Context.getTargetInfo().hasIbm128Type()))
2365 LongDoubleMismatched =
true;
2372 !
Context.getTargetInfo().hasInt128Type()) ||
2375 LongDoubleMismatched) {
2384 <<
static_cast<unsigned>(
Context.getTypeSize(Ty)) << Ty
2385 <<
false <<
Context.getTargetInfo().getTriple().str()) {
2387 D->setInvalidDecl();
2390 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2394 auto CheckType = [&](
QualType Ty,
bool IsRetTy =
false) {
2398 CheckDeviceType(Ty);
2409 if (
Diag(Loc, PD) <<
false << 0 << Ty
2413 D->setInvalidDecl();
2416 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2419 bool IsDouble = UnqualTy ==
Context.DoubleTy;
2420 bool IsFloat = UnqualTy ==
Context.FloatTy;
2421 if (IsRetTy && !TI.
hasFPReturn() && (IsDouble || IsFloat)) {
2428 if (
Diag(Loc, PD) <<
false << 0 << Ty <<
true
2431 D->setInvalidDecl();
2434 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2438 llvm::StringMap<bool> CallerFeatureMap;
2439 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2440 RISCV().checkRVVTypeSupport(Ty, Loc, D, CallerFeatureMap);
2445 llvm::StringMap<bool> CallerFeatureMap;
2446 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2447 ARM().checkSVETypeSupport(Ty, Loc, FD, CallerFeatureMap);
2451 AMDGPU().checkAMDGPUTypeSupport(Ty, Loc);
2460 Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)
2463 if (FTy->getAArch64SMEAttributes() &
2465 Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)
2473 if (
const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2474 for (
const auto &ParamTy : FPTy->param_types())
2476 CheckType(FPTy->getReturnType(),
true);
2478 if (
const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2479 CheckType(FNPTy->getReturnType(),
true);
2527 OpenMP().pushOpenMPFunctionRegion();
2532 BlockScope,
Block));
2545 LSI->AutoTemplateParameterDepth = Depth;
2549 "Remove assertion if intentionally called in a non-lambda context.");
2576 if (!
Result.isInvalid()) {
2596 VarDecl *VD = BC.getVariable();
2597 if (VD->
hasAttr<BlocksAttr>()) {
2606 QualType CapType = BC.getVariable()->getType();
2647 for (
const auto &PUD :
Scope->PossiblyUnreachableDiags)
2648 Diag(PUD.Loc, PUD.PD);
2655 if (!
Scope->isPlainFunction())
2656 Self->CapturingFunctionScopes--;
2658 if (
Scope->isPlainFunction() && !Self->CachedFunctionScope)
2659 Self->CachedFunctionScope.reset(
Scope);
2671 assert(!CurFunction->
CompoundScopes.empty() &&
"mismatched push/pop");
2705 if (CurBSI && CurBSI->TheDecl &&
2729 if (
auto *CSI = dyn_cast<CapturingScopeInfo>(
Scope)) {
2730 auto *LSI = dyn_cast<LambdaScopeInfo>(CSI);
2731 if (LSI && LSI->Lambda && !LSI->Lambda->Encloses(
CurContext) &&
2732 LSI->AfterParameterList) {
2750 if (IgnoreNonLambdaCapturingScope) {
2757 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2758 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2759 !CurLSI->Lambda->Encloses(
CurContext) && CurLSI->AfterParameterList) {
2772 return (LSI->TemplateParams.size() ||
2773 LSI->GLTemplateParameterList) ? LSI :
nullptr;
2779 if (!
LangOpts.CommentOpts.RetainCommentsFromSystemHeaders &&
2783 if (
LangOpts.CommentOpts.ParseAllComments)
2786 if (
LangOpts.CommentOpts.RetainComments)
2795 if (
PP.isCodeCompletionEnabled())
2806 diag::Group::Documentation, diag::Group::DocumentationPedantic};
2808bool Sema::computeDocumentationDiagsAt(SourceLocation Loc)
const {
2816 DocDiagsStateKey =
nullptr;
2817 DocDiagsExactComputed = 0;
2820bool Sema::areDocumentationDiagsSourceLocationDependent() {
2821 if (DocDiagsInSuppressionMapping)
2822 return *DocDiagsInSuppressionMapping;
2828 Diags.getDiagnosticIDs()->getDiagnosticsInGroup(
2831 DocDiagsInSuppressionMapping = llvm::any_of(DocDiags, [&](
diag::kind D) {
2832 return Diags.hasDiagSuppressionMappingFor(D);
2834 return *DocDiagsInSuppressionMapping;
2840 if (Loc.
isInvalid() || areDocumentationDiagsSourceLocationDependent())
2841 return computeDocumentationDiagsAt(Loc);
2843 const void *StateKey =
Diags.getDiagStateKeyForLoc(Loc);
2844 if (StateKey != DocDiagsStateKey) {
2845 DocDiagsStateKey = StateKey;
2849 DocDiagsEnabledIgnoringSystem = computeDocumentationDiagsAt(Loc);
2851 DocDiagsExactComputed = 0;
2854 if (!DocDiagsEnabledIgnoringSystem)
2861 const unsigned Bit = 1u <<
static_cast<unsigned>(SysClass);
2862 if (!(DocDiagsExactComputed & Bit)) {
2863 DocDiagsExactComputed |= Bit;
2864 if (computeDocumentationDiagsAt(Loc))
2865 DocDiagsExactEnabled |= Bit;
2867 DocDiagsExactEnabled &= ~Bit;
2869 return (DocDiagsExactEnabled & Bit) != 0;
2879 StringRef MagicMarkerText;
2882 MagicMarkerText =
"///<";
2885 MagicMarkerText =
"/**<";
2890 Diag(Comment.
getBegin(), diag::warn_splice_in_doxygen_comment);
2893 llvm_unreachable(
"if this is an almost Doxygen comment, "
2894 "it should be ordinary");
2896 Diag(Comment.
getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2904char ExternalSemaSource::ID;
2914 llvm::MapVector<NamedDecl *, SourceLocation> &
Undefined) {}
2925 bool IsMemExpr =
false;
2935 Overloads = dyn_cast<UnresolvedMemberExpr>(E.
IgnoreParens());
2944 DeclsEnd = Overloads->
decls_end(); it != DeclsEnd; ++it) {
2952 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2953 if (OverloadDecl->getMinRequiredArguments() == 0) {
2955 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2956 OverloadDecl->isCPUSpecificMultiVersion()))) {
2960 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2961 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2962 OverloadDecl->isCPUSpecificMultiVersion();
2970 return !ZeroArgCallReturnTy.
isNull();
2981 ZeroArgCallReturnTy = R.get()->getType();
2987 if (
const auto *DeclRef = dyn_cast<DeclRefExpr>(E.
IgnoreParens())) {
2988 if (
const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2989 if (Fun->getMinRequiredArguments() == 0)
2990 ZeroArgCallReturnTy = Fun->getReturnType();
2999 QualType PointeeTy = ExprTy->getPointeeType();
3005 if (
const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
3006 if (FPT->getNumParams() == 0)
3027 unsigned ShownOverloads = 0;
3028 unsigned SuppressedOverloads = 0;
3030 DeclsEnd = Overloads.
end(); It != DeclsEnd; ++It) {
3032 ++SuppressedOverloads;
3036 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
3038 if (
const auto *FD = Fn->getAsFunction()) {
3040 !FD->
getAttr<TargetAttr>()->isDefaultVersion())
3043 !FD->
getAttr<TargetVersionAttr>()->isDefaultVersion())
3046 S.
Diag(Fn->getLocation(), diag::note_possible_target_of_call);
3052 if (SuppressedOverloads)
3053 S.
Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
3054 << SuppressedOverloads;
3059 bool (*IsPlausibleResult)(
QualType)) {
3060 if (!IsPlausibleResult)
3065 DeclsEnd = Overloads.
end(); It != DeclsEnd; ++It) {
3067 QualType OverloadResultTy = OverloadDecl->getReturnType();
3068 if (IsPlausibleResult(OverloadResultTy))
3069 PlausibleOverloads.
addDecl(It.getDecl());
3087 if (
const auto *UO = dyn_cast<UnaryOperator>(E))
3088 E = UO->getSubExpr();
3090 if (
const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3091 if (ULE->getNumDecls() == 0)
3094 const NamedDecl *ND = *ULE->decls_begin();
3095 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
3103 bool (*IsPlausibleResult)(
QualType)) {
3113 !ZeroArgCallTy.
isNull() &&
3114 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
3121 Diag(Loc, PD) << 1 << IsMV << Range
3132 Range.getEnd().getLocWithOffset(1));
3136 if (!ForceComplain)
return false;
3139 Diag(Loc, PD) << 0 << IsMV << Range;
3148 Ident_super = &
Context.Idents.get(
"super");
3154 unsigned OpenMPCaptureLevel) {
3158 ?
OpenMP().getOpenMPNestingLevel()
3160 OpenMPCaptureLevel);
3161 CSI->ReturnType =
Context.VoidTy;
3173const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
3181 OldEvalMethod(S.
PP.getCurrentFPEvalMethod()),
3182 OldFPPragmaLocation(S.
PP.getLastFPEvalPragmaLocation()) {}
3185 S.CurFPFeatures = OldFPFeaturesState;
3186 S.FpPragmaStack.CurrentValue = OldOverrides;
3187 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
3192 "can only be called for qualified names");
3202 bool Result = llvm::all_of(LR, [](
Decl *Dcl) {
3203 if (
NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
3204 ND = ND->getUnderlyingDecl();
3216 auto *A = AnnotateAttr::Create(
Context, Annot, Args.data(), Args.size(), CI);
3233 for (
unsigned Idx = 1; Idx < AL.
getNumArgs(); Idx++) {
Defines the clang::ASTContext interface.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Result
Implement __builtin_bit_cast and related operations.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to AVR.
This file declares semantic analysis functions specific to BPF.
This file declares semantic analysis for CUDA constructs.
This file declares facilities that support code completion.
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to M68k.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to MSP430.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis for expressions involving.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
static void checkEscapingByref(VarDecl *VD, Sema &S)
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E)
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
static bool IsCallableWithAppend(const Expr *E)
Determine whether the given expression can be called by just putting parentheses after it.
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, RecordCompleteMap &MNCComplete)
Returns true, if all methods and nested classes of the given CXXRecordDecl are defined in this transl...
static constexpr diag::Group DocumentationDiagGroups[]
The diagnostic groups that documentation comments are checked for.
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
static bool isFunctionOrVarDeclExternC(const NamedDecl *ND)
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S)
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
static void emitCallStackNotes(Sema &S, const FunctionDecl *FD)
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline.
static bool IsRecordFullyDefined(const CXXRecordDecl *RD, RecordCompleteMap &RecordsComplete, RecordCompleteMap &MNCComplete)
Returns true, if the given CXXRecordDecl is fully defined in this translation unit,...
Defines the SourceManager interface.
TypePropertyCache< Private > Cache
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
virtual ASTMutationListener * GetASTMutationListener()
If the consumer is interested in entities getting modified after their initial creation,...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Attr - This represents one attribute.
A class which contains all the information about a particular captured value.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
ArrayRef< Capture > captures() const
SourceLocation getCaretLocation() const
bool doesNotEscape() const
Represents a C++ destructor within a class.
Represents a C++26 expansion statement declaration.
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
An iterator over the friend declarations of a class.
Represents a C++ struct/union/class.
friend_iterator friend_begin() const
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
friend_iterator friend_end() const
bool isSet() const
Deprecated.
Represents the body of a CapturedStmt, and serves as its DeclContext.
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
static const char * getCastKindName(CastKind CK)
Abstract interface for a consumer of code-completion information.
The information about the darwin SDK that was used during this compilation.
decl_iterator - Iterates through the declarations stored within this context.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
decl_iterator decls_end() const
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
FriendSpecified isFriendSpecified() const
Decl - This represents one declaration (or definition), e.g.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
bool isReferenced() const
Whether any declaration of this entity was referenced.
bool isInvalidDecl() const
SourceLocation getLocation() const
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Information about one declarator, including the parsed type information and the identifier.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
SourceLocation getBeginLoc() const LLVM_READONLY
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
const IdentifierInfo * getIdentifier() const
A little helper class used to produce diagnostics.
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID)
Determines whether the given built-in diagnostic ID is for an error that is suppressed if it occurs d...
@ SFINAE_SubstitutionFailure
The diagnostic should not be reported, but it should cause template argument deduction to fail.
@ SFINAE_Suppress
The diagnostic should be suppressed entirely.
@ SFINAE_AccessControl
The diagnostic is an access-control diagnostic, which will be substitution failures in some contexts ...
@ SFINAE_Report
The diagnostic should be reported.
static StringRef getWarningOptionForGroup(diag::Group)
Given a group ID, returns the flag that toggles the group.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
const SourceLocation & getLocation() const
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Level
The level of the diagnostic, after it has been through mapping.
bool hasFatalErrorOccurred() const
RAII object that enters a new expression evaluation context.
This represents one expression.
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
An abstract interface that should be implemented by external AST sources that also provide informatio...
virtual void updateOutOfDateSelector(Selector Sel)
Load the contents of the global method pool for a given selector if necessary.
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
virtual void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined)
Load the set of used but not defined functions or variables with internal linkage,...
~ExternalSemaSource() override
virtual void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces)
Load the set of namespaces that are known to the external source, which will be used during typo corr...
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &)
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
StringRef getName() const
The name of this FileEntry.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
RAII class that temporarily forces warnings in system headers and system macros to be shown on a Diag...
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Represents a function declaration or definition.
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool isDeleted() const
Whether this function has been deleted.
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
bool isDefaulted() const
Whether this function is defaulted.
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
static FunctionEffectsRef get(QualType QT)
Extract the effects from a Type if it is a function, block, or member function pointer,...
Represents a prototype with parameter type info, e.g.
Declaration of a template function.
FunctionType - C99 6.7.5.3 - Function Declarators.
@ SME_PStateSMCompatibleMask
QualType getReturnType() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Represents a C array with an unspecified size.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
@ CMK_HeaderUnit
Compiling a module header unit.
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Represents the results of name lookup.
Encapsulates the data about a macro definition (e.g.
Abstract interface for a module loader.
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Describes a module or submodule.
bool isNamedModuleInterfaceHasInit() const
bool isInterfaceOrPartition() const
llvm::iterator_range< submodule_iterator > submodules()
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
static const unsigned NumNSNumberLiteralMethods
This represents a decl that may have a name.
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
NamedDecl * getMostRecentDecl()
bool isExternallyVisible() const
ObjCMethodDecl - Represents an instance or class method declaration.
void addSupport(const llvm::StringMap< bool > &FeaturesMap, const LangOptions &Opts)
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
UnresolvedSetImpl::iterator decls_iterator
decls_iterator decls_begin() const
decls_iterator decls_end() const
This interface provides a way to observe the actions of the preprocessor as it does its thing.
ParsedAttr - Represents a syntactic attribute.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
bool isArgIdent(unsigned Arg) const
Expr * getArgAsExpr(unsigned Arg) const
unsigned getDiagID() const
void Emit(const DiagnosticBuilder &DB) const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
A (possibly-)qualified type.
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
bool isNull() const
Return true if this QualType doesn't point to a type yet.
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
bool isConstQualified() const
Determine whether this type is const-qualified.
Represents a struct/union/class.
field_range fields() const
bool hasUninitializedExplicitInitFields() const
Represents the body of a requires-expression.
Scope - A scope is a transient data structure that is used while parsing the program.
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
@ DeclScope
This is a scope that can contain a declaration.
Smart pointer class that efficiently represents Objective-C method names.
void DiagnoseAnonymousPreserveAIEnums()
A generic diagnostic builder for errors which may or may not be deferred.
@ K_Immediate
Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
static bool isImplicitHDExplicitInstantiation(const FunctionDecl *FD)
Null-tolerant wrapper for FunctionDecl::isImplicitHDExplicitInstantiation.
An abstract interface that should be implemented by clients that read ASTs and then require further s...
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
void DiagnoseUseOfUnimplementedSelectors()
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
void DiagnoseUnterminatedOpenMPDeclareTarget()
Report unterminated 'omp declare target' or 'omp begin declare target' at the end of a compilation un...
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
FPFeaturesStateRAII(Sema &S)
Custom deleter to allow FunctionScopeInfos to be kept alive for a short time after they've been poppe...
void operator()(sema::FunctionScopeInfo *Scope) const
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Sema - This implements semantic analysis and AST building for C.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Scope * getCurScope() const
Retrieve the parser's current scope.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
const Decl * PragmaAttributeCurrentTargetDecl
The declaration that is currently receiving an attribute from the pragma attribute stack.
OpaquePtr< QualType > TypeTy
void addImplicitTypedef(StringRef Name, QualType T)
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
void emitAndClearUnusedLocalTypedefWarnings()
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
bool areDocumentationDiagsEnabled(SourceLocation Loc)
Returns true if any of the documentation warnings is enabled at Loc.
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
void clearDocumentationDiagsCache()
Discard the areDocumentationDiagsEnabled() cache, for when a #pragma clang diagnostic has changed dia...
Preprocessor & getPreprocessor() const
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
PragmaStack< FPOptionsOverride > FpPragmaStack
PragmaStack< StringLiteral * > CodeSegStack
void setFunctionHasBranchIntoScope()
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
void ActOnComment(SourceRange Comment)
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
FPOptionsOverride CurFPFeatureOverrides()
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
IdentifierInfo * getSuperIdentifier() const
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
void DiagnosePrecisionLossInComplexDivision()
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
DiagnosticsEngine & getDiagnostics() const
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags
Diagnostics that are emitted only if we discover that the given function must be codegen'ed.
void CheckDelayedMemberExceptionSpecs()
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
PragmaStack< bool > StrictGuardStackCheckStack
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
ASTContext & getASTContext() const
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
llvm::DenseMap< CanonicalDeclPtr< const FunctionDecl >, llvm::SmallVector< FunctionDeclAndLoc, 1 > > DeviceKnownEmittedFns
An inverse call graph, mapping known-emitted functions to their known-emitted callers (plus the locat...
PragmaStack< StringLiteral * > ConstSegStack
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
InitSegPragmaState CurInitSeg
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
void setFunctionHasIndirectGoto()
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
void PushFunctionScope()
Enter a new function scope.
FPOptions & getCurFPFeatures()
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
sema::LambdaScopeInfo * PushLambdaScope()
api_notes::APINotesManager APINotes
const LangOptions & getLangOpts() const
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ASTConsumer & getASTConsumer() const
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
threadSafety::BeforeSet * ThreadSafetyDeclCache
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
const LangOptions & LangOpts
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
static const uint64_t MaximumAlignment
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool shouldRetainCommentsInAST(SourceLocation Loc)
Returns true if a comment at Loc should be retained in the AST (some consumer such as -Wdocumentation...
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
void performFunctionEffectAnalysis(TranslationUnitDecl *TU)
PragmaStack< AlignPackInfo > AlignPackStack
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
PragmaStack< StringLiteral * > BSSSegStack
DeclContext * getCurLexicalContext() const
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
sema::FunctionScopeInfo * getCurFunction() const
void PushCompoundScope(bool IsStmtExpr)
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
static bool isCast(CheckedConversionKind CCK)
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared.
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
SourceManager & getSourceManager() const
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn when implicitly changing function effects.
void PerformPendingInstantiations(bool LocalOnly=false, bool AtEndOfTU=true)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
CanThrowResult canThrow(const Stmt *E)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
PragmaStack< MSVtorDispMode > VtorDispStack
Whether to insert vtordisps prior to virtual bases in the Microsoft C++ ABI.
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
bool isSFINAEContext() const
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
void setFunctionHasMustTail()
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
void CheckCompleteVariableDeclaration(VarDecl *VD)
void setFunctionHasBranchProtectedScope()
RedeclarationKind forRedeclarationInCurContext() const
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
@ NonDefaultStateAtInclude
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
std::pair< SourceLocation, bool > DeleteExprLoc
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
void DiagnoseUnterminatedPragmaAttribute()
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
LateTemplateParserCB * LateTemplateParser
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit.
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
SourceManager & SourceMgr
DiagnosticsEngine & Diags
void DiagnoseUnterminatedPragmaAlignPack()
OpenCLOptions & getOpenCLOptions()
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
PragmaStack< StringLiteral * > DataSegStack
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
bool isMainFileLoc(SourceLocation Loc) const
Determines whether the given source location is in the main file and we're in a context where we shou...
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
void PrintStats() const
Print out statistics about the semantic analysis.
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
llvm::BumpPtrAllocator BumpAlloc
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
void getSortedUnusedLocalTypedefNameCandidates(SmallVectorImpl< const TypedefNameDecl * > &Sorted) const
Store UnusedLocalTypedefNameCandidates in Sorted in a deterministic order.
void DiagnoseUnusedAPINotesSelectors()
Diagnose exact API notes selectors that were not matched by any declaration processed in this transla...
sema::FunctionScopeInfo * getEnclosingFunction() const
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB)
Cause the built diagnostic to be emitted on the DiagosticsEngine.
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
IdentifierResolver IdResolver
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
llvm::DenseSet< InstantiatingSpecializationsKey > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
ASTMutationListener * getASTMutationListener() const
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
FileID getMainFileID() const
Returns the FileID of the main source file.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void setEnd(SourceLocation e)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Exposes information about the current target.
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool hasAMDGPUTypes() const
Returns whether or not the AMDGPU built-in types are available on this target.
virtual bool hasFPReturn() const
Determine whether return of a floating point value is supported on this target.
bool hasRISCVVTypes() const
Returns whether or not the RISC-V V built-in types are available on this target.
A container of type source information.
The base class of the type hierarchy.
bool isFloat16Type() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
const T * castAs() const
Member-template castAs<specific type>.
bool isFloat128Type() const
bool isBitIntType() const
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
bool isIbm128Type() const
bool isOverflowBehaviorType() const
bool isBFloat16Type() const
bool isStructureOrClassType() const
bool isRealFloatingType() const
Floating point categories.
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Linkage getLinkage() const
Determine the linkage of this type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isNullPtrType() const
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Base class for declarations which introduce a typedef-name.
A set of unresolved declarations.
UnresolvedSetIterator iterator
void addDecl(NamedDecl *D)
A set of unresolved declarations.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
void setType(QualType newType)
Represents a variable declaration or definition.
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isInternalLinkageFileVar() const
Returns true if this is a file-scope variable with internal linkage.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
@ TLS_None
Not a TLS variable.
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
@ DeclarationOnly
This declaration is only a declaration.
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Declaration of a variable template.
Represents a GCC generic vector type.
Retains information about a block that is currently being parsed.
Retains information about a captured region.
Contains information about the compound statement currently being parsed.
Retains information about a function, method, or block that is currently being parsed.
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound statement scopes in the function.
llvm::SmallPtrSet< const BlockDecl *, 1 > Blocks
The set of blocks that are introduced in this function.
llvm::TinyPtrVector< VarDecl * > ByrefBlockVars
The set of __block variables that are introduced in this function.
void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override
Callback invoked whenever a source file is entered or exited.
void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, diag::Severity Mapping, StringRef Str) override
Callback invoked when a #pragma gcc diagnostic directive is read.
Provides information about an attempted template argument deduction, whose success or failure was des...
void addSuppressedDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Add a new diagnostic to the set of diagnostics.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Flavor
Flavors of diagnostics we can emit.
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
@ Remark
A diagnostic that indicates normal progress through compilation.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
void threadSafetyCleanup(BeforeSet *Cache)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
@ ExpectedVariableOrFunction
@ Nullable
Values of this type can be null.
@ NonNull
Values of this type can never be null.
DiagStateSystemClass
Whether a source location is in a system header and/or a system macro.
Expected< std::optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CapturedRegionKind
The different kinds of captured statement.
void inferNoReturnAttr(Sema &S, Decl *D)
@ Undefined
Keep undefined.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
@ Result
The result type of a method or function.
@ Template
We are parsing a template declaration.
@ Private
The private module fragment, between 'module :private;' and the end of the translation unit.
@ Global
The global module fragment, between 'module;' and a module-declaration.
@ Normal
A normal translation unit fragment.
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
@ TU_ClangModule
The translation unit is a clang module.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
void FormatASTNodeDiagnosticArgument(DiagnosticsEngine::ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
DiagnosticsEngine argument formatting function for diagnostics that involve AST nodes.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
bool isExternalFormalLinkage(Linkage L)
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
U cast(CodeGen::Address addr)
@ Class
The "class" keyword introduces the elaborated-type-specifier.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
bool isExternallyVisible(Linkage L)
ActionResult< Expr * > ExprResult
CheckedConversionKind
The kind of conversion being performed.
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
bool HasFormOfMemberPointer
OverloadExpr * Expression
Describes how types, statements, expressions, and declarations should be printed.
unsigned Bool
Whether we can use 'bool' rather than '_Bool' (even if the language doesn't actually have 'bool',...
unsigned EntireContentsOfLargeArray
Whether to print the entire array initializers, especially on non-type template parameters,...
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.