Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaAttr.cpp
35233 views
//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for non-trivial attributes and9// pragmas.10//11//===----------------------------------------------------------------------===//1213#include "clang/AST/ASTConsumer.h"14#include "clang/AST/Attr.h"15#include "clang/AST/Expr.h"16#include "clang/Basic/TargetInfo.h"17#include "clang/Lex/Preprocessor.h"18#include "clang/Sema/Lookup.h"19#include "clang/Sema/SemaInternal.h"20#include <optional>21using namespace clang;2223//===----------------------------------------------------------------------===//24// Pragma 'pack' and 'options align'25//===----------------------------------------------------------------------===//2627Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,28StringRef SlotLabel,29bool ShouldAct)30: S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {31if (ShouldAct) {32S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);33S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);34S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);35S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);36S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);37S.StrictGuardStackCheckStack.SentinelAction(PSK_Push, SlotLabel);38}39}4041Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {42if (ShouldAct) {43S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);44S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);45S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);46S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);47S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);48S.StrictGuardStackCheckStack.SentinelAction(PSK_Pop, SlotLabel);49}50}5152void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {53AlignPackInfo InfoVal = AlignPackStack.CurrentValue;54AlignPackInfo::Mode M = InfoVal.getAlignMode();55bool IsPackSet = InfoVal.IsPackSet();56bool IsXLPragma = getLangOpts().XLPragmaPack;5758// If we are not under mac68k/natural alignment mode and also there is no pack59// value, we don't need any attributes.60if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)61return;6263if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {64RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));65} else if (IsPackSet) {66// Check to see if we need a max field alignment attribute.67RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(68Context, InfoVal.getPackNumber() * 8));69}7071if (IsXLPragma && M == AlignPackInfo::Natural)72RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));7374if (AlignPackIncludeStack.empty())75return;76// The #pragma align/pack affected a record in an included file, so Clang77// should warn when that pragma was written in a file that included the78// included file.79for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack)) {80if (AlignPackedInclude.CurrentPragmaLocation !=81AlignPackStack.CurrentPragmaLocation)82break;83if (AlignPackedInclude.HasNonDefaultValue)84AlignPackedInclude.ShouldWarnOnInclude = true;85}86}8788void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {89if (MSStructPragmaOn)90RD->addAttr(MSStructAttr::CreateImplicit(Context));9192// FIXME: We should merge AddAlignmentAttributesForRecord with93// AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes94// all active pragmas and applies them as attributes to class definitions.95if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())96RD->addAttr(MSVtorDispAttr::CreateImplicit(97Context, unsigned(VtorDispStack.CurrentValue)));98}99100template <typename Attribute>101static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,102CXXRecordDecl *Record) {103if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())104return;105106for (Decl *Redecl : Record->redecls())107Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));108}109110void Sema::inferGslPointerAttribute(NamedDecl *ND,111CXXRecordDecl *UnderlyingRecord) {112if (!UnderlyingRecord)113return;114115const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());116if (!Parent)117return;118119static const llvm::StringSet<> Containers{120"array",121"basic_string",122"deque",123"forward_list",124"vector",125"list",126"map",127"multiset",128"multimap",129"priority_queue",130"queue",131"set",132"stack",133"unordered_set",134"unordered_map",135"unordered_multiset",136"unordered_multimap",137};138139static const llvm::StringSet<> Iterators{"iterator", "const_iterator",140"reverse_iterator",141"const_reverse_iterator"};142143if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&144Containers.count(Parent->getName()))145addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,146UnderlyingRecord);147}148149void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {150151QualType Canonical = TD->getUnderlyingType().getCanonicalType();152153CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();154if (!RD) {155if (auto *TST =156dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {157158RD = dyn_cast_or_null<CXXRecordDecl>(159TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());160}161}162163inferGslPointerAttribute(TD, RD);164}165166void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {167static const llvm::StringSet<> StdOwners{168"any",169"array",170"basic_regex",171"basic_string",172"deque",173"forward_list",174"vector",175"list",176"map",177"multiset",178"multimap",179"optional",180"priority_queue",181"queue",182"set",183"stack",184"unique_ptr",185"unordered_set",186"unordered_map",187"unordered_multiset",188"unordered_multimap",189"variant",190};191static const llvm::StringSet<> StdPointers{192"basic_string_view",193"reference_wrapper",194"regex_iterator",195"span",196};197198if (!Record->getIdentifier())199return;200201// Handle classes that directly appear in std namespace.202if (Record->isInStdNamespace()) {203if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())204return;205206if (StdOwners.count(Record->getName()))207addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);208else if (StdPointers.count(Record->getName()))209addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);210211return;212}213214// Handle nested classes that could be a gsl::Pointer.215inferGslPointerAttribute(Record, Record);216}217218void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {219static const llvm::StringSet<> Nullable{220"auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",221"coroutine_handle", "function", "move_only_function",222};223224if (CRD->isInStdNamespace() && Nullable.count(CRD->getName()) &&225!CRD->hasAttr<TypeNullableAttr>())226for (Decl *Redecl : CRD->redecls())227Redecl->addAttr(TypeNullableAttr::CreateImplicit(Context));228}229230void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,231SourceLocation PragmaLoc) {232PragmaMsStackAction Action = Sema::PSK_Reset;233AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;234235switch (Kind) {236// For most of the platforms we support, native and natural are the same.237// With XL, native is the same as power, natural means something else.238case POAK_Native:239case POAK_Power:240Action = Sema::PSK_Push_Set;241break;242case POAK_Natural:243Action = Sema::PSK_Push_Set;244ModeVal = AlignPackInfo::Natural;245break;246247// Note that '#pragma options align=packed' is not equivalent to attribute248// packed, it has a different precedence relative to attribute aligned.249case POAK_Packed:250Action = Sema::PSK_Push_Set;251ModeVal = AlignPackInfo::Packed;252break;253254case POAK_Mac68k:255// Check if the target supports this.256if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {257Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);258return;259}260Action = Sema::PSK_Push_Set;261ModeVal = AlignPackInfo::Mac68k;262break;263case POAK_Reset:264// Reset just pops the top of the stack, or resets the current alignment to265// default.266Action = Sema::PSK_Pop;267if (AlignPackStack.Stack.empty()) {268if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||269AlignPackStack.CurrentValue.IsPackAttr()) {270Action = Sema::PSK_Reset;271} else {272Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)273<< "stack empty";274return;275}276}277break;278}279280AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);281282AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);283}284285void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,286PragmaClangSectionAction Action,287PragmaClangSectionKind SecKind,288StringRef SecName) {289PragmaClangSection *CSec;290int SectionFlags = ASTContext::PSF_Read;291switch (SecKind) {292case PragmaClangSectionKind::PCSK_BSS:293CSec = &PragmaClangBSSSection;294SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;295break;296case PragmaClangSectionKind::PCSK_Data:297CSec = &PragmaClangDataSection;298SectionFlags |= ASTContext::PSF_Write;299break;300case PragmaClangSectionKind::PCSK_Rodata:301CSec = &PragmaClangRodataSection;302break;303case PragmaClangSectionKind::PCSK_Relro:304CSec = &PragmaClangRelroSection;305break;306case PragmaClangSectionKind::PCSK_Text:307CSec = &PragmaClangTextSection;308SectionFlags |= ASTContext::PSF_Execute;309break;310default:311llvm_unreachable("invalid clang section kind");312}313314if (Action == PragmaClangSectionAction::PCSA_Clear) {315CSec->Valid = false;316return;317}318319if (llvm::Error E = isValidSectionSpecifier(SecName)) {320Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)321<< toString(std::move(E));322CSec->Valid = false;323return;324}325326if (UnifySection(SecName, SectionFlags, PragmaLoc))327return;328329CSec->Valid = true;330CSec->SectionName = std::string(SecName);331CSec->PragmaLocation = PragmaLoc;332}333334void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,335StringRef SlotLabel, Expr *alignment) {336bool IsXLPragma = getLangOpts().XLPragmaPack;337// XL pragma pack does not support identifier syntax.338if (IsXLPragma && !SlotLabel.empty()) {339Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);340return;341}342343const AlignPackInfo CurVal = AlignPackStack.CurrentValue;344Expr *Alignment = static_cast<Expr *>(alignment);345346// If specified then alignment must be a "small" power of two.347unsigned AlignmentVal = 0;348AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();349350if (Alignment) {351std::optional<llvm::APSInt> Val;352Val = Alignment->getIntegerConstantExpr(Context);353354// pack(0) is like pack(), which just works out since that is what355// we use 0 for in PackAttr.356if (Alignment->isTypeDependent() || !Val ||357!(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {358Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);359return; // Ignore360}361362if (IsXLPragma && *Val == 0) {363// pack(0) does not work out with XL.364Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);365return; // Ignore366}367368AlignmentVal = (unsigned)Val->getZExtValue();369}370371if (Action == Sema::PSK_Show) {372// Show the current alignment, making sure to show the right value373// for the default.374// FIXME: This should come from the target.375AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;376if (ModeVal == AlignPackInfo::Mac68k &&377(IsXLPragma || CurVal.IsAlignAttr()))378Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";379else380Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;381}382383// MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:384// "#pragma pack(pop, identifier, n) is undefined"385if (Action & Sema::PSK_Pop) {386if (Alignment && !SlotLabel.empty())387Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);388if (AlignPackStack.Stack.empty()) {389assert(CurVal.getAlignMode() == AlignPackInfo::Native &&390"Empty pack stack can only be at Native alignment mode.");391Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";392}393}394395AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);396397AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);398}399400bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo &CI,401MutableArrayRef<Expr *> Args) {402llvm::SmallVector<PartialDiagnosticAt, 8> Notes;403for (unsigned Idx = 0; Idx < Args.size(); Idx++) {404Expr *&E = Args.begin()[Idx];405assert(E && "error are handled before");406if (E->isValueDependent() || E->isTypeDependent())407continue;408409// FIXME: Use DefaultFunctionArrayLValueConversion() in place of the logic410// that adds implicit casts here.411if (E->getType()->isArrayType())412E = ImpCastExprToType(E, Context.getPointerType(E->getType()),413clang::CK_ArrayToPointerDecay)414.get();415if (E->getType()->isFunctionType())416E = ImplicitCastExpr::Create(Context,417Context.getPointerType(E->getType()),418clang::CK_FunctionToPointerDecay, E, nullptr,419VK_PRValue, FPOptionsOverride());420if (E->isLValue())421E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),422clang::CK_LValueToRValue, E, nullptr,423VK_PRValue, FPOptionsOverride());424425Expr::EvalResult Eval;426Notes.clear();427Eval.Diag = &Notes;428429bool Result = E->EvaluateAsConstantExpr(Eval, Context);430431/// Result means the expression can be folded to a constant.432/// Note.empty() means the expression is a valid constant expression in the433/// current language mode.434if (!Result || !Notes.empty()) {435Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)436<< CI << (Idx + 1) << AANT_ArgumentConstantExpr;437for (auto &Note : Notes)438Diag(Note.first, Note.second);439return false;440}441assert(Eval.Val.hasValue());442E = ConstantExpr::Create(Context, E, Eval.Val);443}444445return true;446}447448void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,449SourceLocation IncludeLoc) {450if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {451SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;452// Warn about non-default alignment at #includes (without redundant453// warnings for the same directive in nested includes).454// The warning is delayed until the end of the file to avoid warnings455// for files that don't have any records that are affected by the modified456// alignment.457bool HasNonDefaultValue =458AlignPackStack.hasValue() &&459(AlignPackIncludeStack.empty() ||460AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);461AlignPackIncludeStack.push_back(462{AlignPackStack.CurrentValue,463AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),464HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});465return;466}467468assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&469"invalid kind");470AlignPackIncludeState PrevAlignPackState =471AlignPackIncludeStack.pop_back_val();472// FIXME: AlignPackStack may contain both #pragma align and #pragma pack473// information, diagnostics below might not be accurate if we have mixed474// pragmas.475if (PrevAlignPackState.ShouldWarnOnInclude) {476// Emit the delayed non-default alignment at #include warning.477Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);478Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);479}480// Warn about modified alignment after #includes.481if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {482Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);483Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);484}485}486487void Sema::DiagnoseUnterminatedPragmaAlignPack() {488if (AlignPackStack.Stack.empty())489return;490bool IsInnermost = true;491492// FIXME: AlignPackStack may contain both #pragma align and #pragma pack493// information, diagnostics below might not be accurate if we have mixed494// pragmas.495for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {496Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);497// The user might have already reset the alignment, so suggest replacing498// the reset with a pop.499if (IsInnermost &&500AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {501auto DB = Diag(AlignPackStack.CurrentPragmaLocation,502diag::note_pragma_pack_pop_instead_reset);503SourceLocation FixItLoc =504Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,505tok::l_paren, SourceMgr, LangOpts,506/*SkipTrailing=*/false);507if (FixItLoc.isValid())508DB << FixItHint::CreateInsertion(FixItLoc, "pop");509}510IsInnermost = false;511}512}513514void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {515MSStructPragmaOn = (Kind == PMSST_ON);516}517518void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,519PragmaMSCommentKind Kind, StringRef Arg) {520auto *PCD = PragmaCommentDecl::Create(521Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);522Context.getTranslationUnitDecl()->addDecl(PCD);523Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));524}525526void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,527StringRef Value) {528auto *PDMD = PragmaDetectMismatchDecl::Create(529Context, Context.getTranslationUnitDecl(), Loc, Name, Value);530Context.getTranslationUnitDecl()->addDecl(PDMD);531Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));532}533534void Sema::ActOnPragmaFPEvalMethod(SourceLocation Loc,535LangOptions::FPEvalMethodKind Value) {536FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();537switch (Value) {538default:539llvm_unreachable("invalid pragma eval_method kind");540case LangOptions::FEM_Source:541NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);542break;543case LangOptions::FEM_Double:544NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);545break;546case LangOptions::FEM_Extended:547NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);548break;549}550if (getLangOpts().ApproxFunc)551Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;552if (getLangOpts().AllowFPReassoc)553Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;554if (getLangOpts().AllowRecip)555Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;556FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);557CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());558PP.setCurrentFPEvalMethod(Loc, Value);559}560561void Sema::ActOnPragmaFloatControl(SourceLocation Loc,562PragmaMsStackAction Action,563PragmaFloatControlKind Value) {564FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();565if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&566!CurContext->getRedeclContext()->isFileContext()) {567// Push and pop can only occur at file or namespace scope, or within a568// language linkage declaration.569Diag(Loc, diag::err_pragma_fc_pp_scope);570return;571}572switch (Value) {573default:574llvm_unreachable("invalid pragma float_control kind");575case PFC_Precise:576NewFPFeatures.setFPPreciseEnabled(true);577FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);578break;579case PFC_NoPrecise:580if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict)581Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);582else if (CurFPFeatures.getAllowFEnvAccess())583Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);584else585NewFPFeatures.setFPPreciseEnabled(false);586FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);587break;588case PFC_Except:589if (!isPreciseFPEnabled())590Diag(Loc, diag::err_pragma_fc_except_requires_precise);591else592NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Strict);593FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);594break;595case PFC_NoExcept:596NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Ignore);597FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);598break;599case PFC_Push:600FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);601break;602case PFC_Pop:603if (FpPragmaStack.Stack.empty()) {604Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"605<< "stack empty";606return;607}608FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);609NewFPFeatures = FpPragmaStack.CurrentValue;610break;611}612CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());613}614615void Sema::ActOnPragmaMSPointersToMembers(616LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,617SourceLocation PragmaLoc) {618MSPointerToMemberRepresentationMethod = RepresentationMethod;619ImplicitMSInheritanceAttrLoc = PragmaLoc;620}621622void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,623SourceLocation PragmaLoc,624MSVtorDispMode Mode) {625if (Action & PSK_Pop && VtorDispStack.Stack.empty())626Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"627<< "stack empty";628VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);629}630631template <>632void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,633PragmaMsStackAction Action,634llvm::StringRef StackSlotLabel,635AlignPackInfo Value) {636if (Action == PSK_Reset) {637CurrentValue = DefaultValue;638CurrentPragmaLocation = PragmaLocation;639return;640}641if (Action & PSK_Push)642Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,643PragmaLocation));644else if (Action & PSK_Pop) {645if (!StackSlotLabel.empty()) {646// If we've got a label, try to find it and jump there.647auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {648return x.StackSlotLabel == StackSlotLabel;649});650// We found the label, so pop from there.651if (I != Stack.rend()) {652CurrentValue = I->Value;653CurrentPragmaLocation = I->PragmaLocation;654Stack.erase(std::prev(I.base()), Stack.end());655}656} else if (Value.IsXLStack() && Value.IsAlignAttr() &&657CurrentValue.IsPackAttr()) {658// XL '#pragma align(reset)' would pop the stack until659// a current in effect pragma align is popped.660auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {661return x.Value.IsAlignAttr();662});663// If we found pragma align so pop from there.664if (I != Stack.rend()) {665Stack.erase(std::prev(I.base()), Stack.end());666if (Stack.empty()) {667CurrentValue = DefaultValue;668CurrentPragmaLocation = PragmaLocation;669} else {670CurrentValue = Stack.back().Value;671CurrentPragmaLocation = Stack.back().PragmaLocation;672Stack.pop_back();673}674}675} else if (!Stack.empty()) {676// xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop677// over the baseline.678if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())679return;680681// We don't have a label, just pop the last entry.682CurrentValue = Stack.back().Value;683CurrentPragmaLocation = Stack.back().PragmaLocation;684Stack.pop_back();685}686}687if (Action & PSK_Set) {688CurrentValue = Value;689CurrentPragmaLocation = PragmaLocation;690}691}692693bool Sema::UnifySection(StringRef SectionName, int SectionFlags,694NamedDecl *Decl) {695SourceLocation PragmaLocation;696if (auto A = Decl->getAttr<SectionAttr>())697if (A->isImplicit())698PragmaLocation = A->getLocation();699auto SectionIt = Context.SectionInfos.find(SectionName);700if (SectionIt == Context.SectionInfos.end()) {701Context.SectionInfos[SectionName] =702ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);703return false;704}705// A pre-declared section takes precedence w/o diagnostic.706const auto &Section = SectionIt->second;707if (Section.SectionFlags == SectionFlags ||708((SectionFlags & ASTContext::PSF_Implicit) &&709!(Section.SectionFlags & ASTContext::PSF_Implicit)))710return false;711Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;712if (Section.Decl)713Diag(Section.Decl->getLocation(), diag::note_declared_at)714<< Section.Decl->getName();715if (PragmaLocation.isValid())716Diag(PragmaLocation, diag::note_pragma_entered_here);717if (Section.PragmaSectionLocation.isValid())718Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);719return true;720}721722bool Sema::UnifySection(StringRef SectionName,723int SectionFlags,724SourceLocation PragmaSectionLocation) {725auto SectionIt = Context.SectionInfos.find(SectionName);726if (SectionIt != Context.SectionInfos.end()) {727const auto &Section = SectionIt->second;728if (Section.SectionFlags == SectionFlags)729return false;730if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {731Diag(PragmaSectionLocation, diag::err_section_conflict)732<< "this" << Section;733if (Section.Decl)734Diag(Section.Decl->getLocation(), diag::note_declared_at)735<< Section.Decl->getName();736if (Section.PragmaSectionLocation.isValid())737Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);738return true;739}740}741Context.SectionInfos[SectionName] =742ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);743return false;744}745746/// Called on well formed \#pragma bss_seg().747void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,748PragmaMsStackAction Action,749llvm::StringRef StackSlotLabel,750StringLiteral *SegmentName,751llvm::StringRef PragmaName) {752PragmaStack<StringLiteral *> *Stack =753llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)754.Case("data_seg", &DataSegStack)755.Case("bss_seg", &BSSSegStack)756.Case("const_seg", &ConstSegStack)757.Case("code_seg", &CodeSegStack);758if (Action & PSK_Pop && Stack->Stack.empty())759Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName760<< "stack empty";761if (SegmentName) {762if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))763return;764765if (SegmentName->getString() == ".drectve" &&766Context.getTargetInfo().getCXXABI().isMicrosoft())767Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;768}769770Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);771}772773/// Called on well formed \#pragma strict_gs_check().774void Sema::ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,775PragmaMsStackAction Action,776bool Value) {777if (Action & PSK_Pop && StrictGuardStackCheckStack.Stack.empty())778Diag(PragmaLocation, diag::warn_pragma_pop_failed) << "strict_gs_check"779<< "stack empty";780781StrictGuardStackCheckStack.Act(PragmaLocation, Action, StringRef(), Value);782}783784/// Called on well formed \#pragma bss_seg().785void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,786int SectionFlags, StringLiteral *SegmentName) {787UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);788}789790void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,791StringLiteral *SegmentName) {792// There's no stack to maintain, so we just have a current section. When we793// see the default section, reset our current section back to null so we stop794// tacking on unnecessary attributes.795CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;796CurInitSegLoc = PragmaLocation;797}798799void Sema::ActOnPragmaMSAllocText(800SourceLocation PragmaLocation, StringRef Section,801const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>802&Functions) {803if (!CurContext->getRedeclContext()->isFileContext()) {804Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";805return;806}807808for (auto &Function : Functions) {809IdentifierInfo *II;810SourceLocation Loc;811std::tie(II, Loc) = Function;812813DeclarationName DN(II);814NamedDecl *ND = LookupSingleName(TUScope, DN, Loc, LookupOrdinaryName);815if (!ND) {816Diag(Loc, diag::err_undeclared_use) << II->getName();817return;818}819820auto *FD = dyn_cast<FunctionDecl>(ND->getCanonicalDecl());821if (!FD) {822Diag(Loc, diag::err_pragma_alloc_text_not_function);823return;824}825826if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {827Diag(Loc, diag::err_pragma_alloc_text_c_linkage);828return;829}830831FunctionToSectionMap[II->getName()] = std::make_tuple(Section, Loc);832}833}834835void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,836SourceLocation PragmaLoc) {837838IdentifierInfo *Name = IdTok.getIdentifierInfo();839LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);840LookupName(Lookup, curScope, /*AllowBuiltinCreation=*/true);841842if (Lookup.empty()) {843Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)844<< Name << SourceRange(IdTok.getLocation());845return;846}847848VarDecl *VD = Lookup.getAsSingle<VarDecl>();849if (!VD) {850Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)851<< Name << SourceRange(IdTok.getLocation());852return;853}854855// Warn if this was used before being marked unused.856if (VD->isUsed())857Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;858859VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),860UnusedAttr::GNU_unused));861}862863namespace {864865std::optional<attr::SubjectMatchRule>866getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {867using namespace attr;868switch (Rule) {869default:870return std::nullopt;871#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)872#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \873case Value: \874return Parent;875#include "clang/Basic/AttrSubMatchRulesList.inc"876}877}878879bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {880using namespace attr;881switch (Rule) {882default:883return false;884#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)885#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \886case Value: \887return IsNegated;888#include "clang/Basic/AttrSubMatchRulesList.inc"889}890}891892CharSourceRange replacementRangeForListElement(const Sema &S,893SourceRange Range) {894// Make sure that the ',' is removed as well.895SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(896Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),897/*SkipTrailingWhitespaceAndNewLine=*/false);898if (AfterCommaLoc.isValid())899return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);900else901return CharSourceRange::getTokenRange(Range);902}903904std::string905attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {906std::string Result;907llvm::raw_string_ostream OS(Result);908for (const auto &I : llvm::enumerate(Rules)) {909if (I.index())910OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");911OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";912}913return Result;914}915916} // end anonymous namespace917918void Sema::ActOnPragmaAttributeAttribute(919ParsedAttr &Attribute, SourceLocation PragmaLoc,920attr::ParsedSubjectMatchRuleSet Rules) {921Attribute.setIsPragmaClangAttribute();922SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;923// Gather the subject match rules that are supported by the attribute.924SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>925StrictSubjectMatchRuleSet;926Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);927928// Figure out which subject matching rules are valid.929if (StrictSubjectMatchRuleSet.empty()) {930// Check for contradicting match rules. Contradicting match rules are931// either:932// - a top-level rule and one of its sub-rules. E.g. variable and933// variable(is_parameter).934// - a sub-rule and a sibling that's negated. E.g.935// variable(is_thread_local) and variable(unless(is_parameter))936llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>937RulesToFirstSpecifiedNegatedSubRule;938for (const auto &Rule : Rules) {939attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);940std::optional<attr::SubjectMatchRule> ParentRule =941getParentAttrMatcherRule(MatchRule);942if (!ParentRule)943continue;944auto It = Rules.find(*ParentRule);945if (It != Rules.end()) {946// A sub-rule contradicts a parent rule.947Diag(Rule.second.getBegin(),948diag::err_pragma_attribute_matcher_subrule_contradicts_rule)949<< attr::getSubjectMatchRuleSpelling(MatchRule)950<< attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second951<< FixItHint::CreateRemoval(952replacementRangeForListElement(*this, Rule.second));953// Keep going without removing this rule as it won't change the set of954// declarations that receive the attribute.955continue;956}957if (isNegatedAttrMatcherSubRule(MatchRule))958RulesToFirstSpecifiedNegatedSubRule.insert(959std::make_pair(*ParentRule, Rule));960}961bool IgnoreNegatedSubRules = false;962for (const auto &Rule : Rules) {963attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);964std::optional<attr::SubjectMatchRule> ParentRule =965getParentAttrMatcherRule(MatchRule);966if (!ParentRule)967continue;968auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);969if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&970It->second != Rule) {971// Negated sub-rule contradicts another sub-rule.972Diag(973It->second.second.getBegin(),974diag::975err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)976<< attr::getSubjectMatchRuleSpelling(977attr::SubjectMatchRule(It->second.first))978<< attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second979<< FixItHint::CreateRemoval(980replacementRangeForListElement(*this, It->second.second));981// Keep going but ignore all of the negated sub-rules.982IgnoreNegatedSubRules = true;983RulesToFirstSpecifiedNegatedSubRule.erase(It);984}985}986987if (!IgnoreNegatedSubRules) {988for (const auto &Rule : Rules)989SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));990} else {991for (const auto &Rule : Rules) {992if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))993SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));994}995}996Rules.clear();997} else {998// Each rule in Rules must be a strict subset of the attribute's999// SubjectMatch rules. I.e. we're allowed to use1000// `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,1001// but should not allow `apply_to=variables` on an attribute which has1002// `SubjectList<[GlobalVar]>`.1003for (const auto &StrictRule : StrictSubjectMatchRuleSet) {1004// First, check for exact match.1005if (Rules.erase(StrictRule.first)) {1006// Add the rule to the set of attribute receivers only if it's supported1007// in the current language mode.1008if (StrictRule.second)1009SubjectMatchRules.push_back(StrictRule.first);1010}1011}1012// Check remaining rules for subset matches.1013auto RulesToCheck = Rules;1014for (const auto &Rule : RulesToCheck) {1015attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);1016if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {1017if (llvm::any_of(StrictSubjectMatchRuleSet,1018[ParentRule](const auto &StrictRule) {1019return StrictRule.first == *ParentRule &&1020StrictRule.second; // IsEnabled1021})) {1022SubjectMatchRules.push_back(MatchRule);1023Rules.erase(MatchRule);1024}1025}1026}1027}10281029if (!Rules.empty()) {1030auto Diagnostic =1031Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)1032<< Attribute;1033SmallVector<attr::SubjectMatchRule, 2> ExtraRules;1034for (const auto &Rule : Rules) {1035ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));1036Diagnostic << FixItHint::CreateRemoval(1037replacementRangeForListElement(*this, Rule.second));1038}1039Diagnostic << attrMatcherRuleListToString(ExtraRules);1040}10411042if (PragmaAttributeStack.empty()) {1043Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);1044return;1045}10461047PragmaAttributeStack.back().Entries.push_back(1048{PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});1049}10501051void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,1052const IdentifierInfo *Namespace) {1053PragmaAttributeStack.emplace_back();1054PragmaAttributeStack.back().Loc = PragmaLoc;1055PragmaAttributeStack.back().Namespace = Namespace;1056}10571058void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,1059const IdentifierInfo *Namespace) {1060if (PragmaAttributeStack.empty()) {1061Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;1062return;1063}10641065// Dig back through the stack trying to find the most recently pushed group1066// that in Namespace. Note that this works fine if no namespace is present,1067// think of push/pops without namespaces as having an implicit "nullptr"1068// namespace.1069for (size_t Index = PragmaAttributeStack.size(); Index;) {1070--Index;1071if (PragmaAttributeStack[Index].Namespace == Namespace) {1072for (const PragmaAttributeEntry &Entry :1073PragmaAttributeStack[Index].Entries) {1074if (!Entry.IsUsed) {1075assert(Entry.Attribute && "Expected an attribute");1076Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)1077<< *Entry.Attribute;1078Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);1079}1080}1081PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);1082return;1083}1084}10851086if (Namespace)1087Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)1088<< 0 << Namespace->getName();1089else1090Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;1091}10921093void Sema::AddPragmaAttributes(Scope *S, Decl *D) {1094if (PragmaAttributeStack.empty())1095return;1096for (auto &Group : PragmaAttributeStack) {1097for (auto &Entry : Group.Entries) {1098ParsedAttr *Attribute = Entry.Attribute;1099assert(Attribute && "Expected an attribute");1100assert(Attribute->isPragmaClangAttribute() &&1101"expected #pragma clang attribute");11021103// Ensure that the attribute can be applied to the given declaration.1104bool Applies = false;1105for (const auto &Rule : Entry.MatchRules) {1106if (Attribute->appliesToDecl(D, Rule)) {1107Applies = true;1108break;1109}1110}1111if (!Applies)1112continue;1113Entry.IsUsed = true;1114PragmaAttributeCurrentTargetDecl = D;1115ParsedAttributesView Attrs;1116Attrs.addAtEnd(Attribute);1117ProcessDeclAttributeList(S, D, Attrs);1118PragmaAttributeCurrentTargetDecl = nullptr;1119}1120}1121}11221123void Sema::PrintPragmaAttributeInstantiationPoint() {1124assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");1125Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),1126diag::note_pragma_attribute_applied_decl_here);1127}11281129void Sema::DiagnoseUnterminatedPragmaAttribute() {1130if (PragmaAttributeStack.empty())1131return;1132Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);1133}11341135void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {1136if(On)1137OptimizeOffPragmaLocation = SourceLocation();1138else1139OptimizeOffPragmaLocation = PragmaLoc;1140}11411142void Sema::ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn) {1143if (!CurContext->getRedeclContext()->isFileContext()) {1144Diag(Loc, diag::err_pragma_expected_file_scope) << "optimize";1145return;1146}11471148MSPragmaOptimizeIsOn = IsOn;1149}11501151void Sema::ActOnPragmaMSFunction(1152SourceLocation Loc, const llvm::SmallVectorImpl<StringRef> &NoBuiltins) {1153if (!CurContext->getRedeclContext()->isFileContext()) {1154Diag(Loc, diag::err_pragma_expected_file_scope) << "function";1155return;1156}11571158MSFunctionNoBuiltins.insert(NoBuiltins.begin(), NoBuiltins.end());1159}11601161void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {1162// In the future, check other pragmas if they're implemented (e.g. pragma1163// optimize 0 will probably map to this functionality too).1164if(OptimizeOffPragmaLocation.isValid())1165AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);1166}11671168void Sema::AddSectionMSAllocText(FunctionDecl *FD) {1169if (!FD->getIdentifier())1170return;11711172StringRef Name = FD->getName();1173auto It = FunctionToSectionMap.find(Name);1174if (It != FunctionToSectionMap.end()) {1175StringRef Section;1176SourceLocation Loc;1177std::tie(Section, Loc) = It->second;11781179if (!FD->hasAttr<SectionAttr>())1180FD->addAttr(SectionAttr::CreateImplicit(Context, Section));1181}1182}11831184void Sema::ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD) {1185// Don't modify the function attributes if it's "on". "on" resets the1186// optimizations to the ones listed on the command line1187if (!MSPragmaOptimizeIsOn)1188AddOptnoneAttributeIfNoConflicts(FD, FD->getBeginLoc());1189}11901191void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,1192SourceLocation Loc) {1193// Don't add a conflicting attribute. No diagnostic is needed.1194if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())1195return;11961197// Add attributes only if required. Optnone requires noinline as well, but if1198// either is already present then don't bother adding them.1199if (!FD->hasAttr<OptimizeNoneAttr>())1200FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));1201if (!FD->hasAttr<NoInlineAttr>())1202FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));1203}12041205void Sema::AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD) {1206SmallVector<StringRef> V(MSFunctionNoBuiltins.begin(),1207MSFunctionNoBuiltins.end());1208if (!MSFunctionNoBuiltins.empty())1209FD->addAttr(NoBuiltinAttr::CreateImplicit(Context, V.data(), V.size()));1210}12111212typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;1213enum : unsigned { NoVisibility = ~0U };12141215void Sema::AddPushedVisibilityAttribute(Decl *D) {1216if (!VisContext)1217return;12181219NamedDecl *ND = dyn_cast<NamedDecl>(D);1220if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))1221return;12221223VisStack *Stack = static_cast<VisStack*>(VisContext);1224unsigned rawType = Stack->back().first;1225if (rawType == NoVisibility) return;12261227VisibilityAttr::VisibilityType type1228= (VisibilityAttr::VisibilityType) rawType;1229SourceLocation loc = Stack->back().second;12301231D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));1232}12331234void Sema::FreeVisContext() {1235delete static_cast<VisStack*>(VisContext);1236VisContext = nullptr;1237}12381239static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {1240// Put visibility on stack.1241if (!S.VisContext)1242S.VisContext = new VisStack;12431244VisStack *Stack = static_cast<VisStack*>(S.VisContext);1245Stack->push_back(std::make_pair(type, loc));1246}12471248void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,1249SourceLocation PragmaLoc) {1250if (VisType) {1251// Compute visibility to use.1252VisibilityAttr::VisibilityType T;1253if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {1254Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;1255return;1256}1257PushPragmaVisibility(*this, T, PragmaLoc);1258} else {1259PopPragmaVisibility(false, PragmaLoc);1260}1261}12621263void Sema::ActOnPragmaFPContract(SourceLocation Loc,1264LangOptions::FPModeKind FPC) {1265FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();1266switch (FPC) {1267case LangOptions::FPM_On:1268NewFPFeatures.setAllowFPContractWithinStatement();1269break;1270case LangOptions::FPM_Fast:1271NewFPFeatures.setAllowFPContractAcrossStatement();1272break;1273case LangOptions::FPM_Off:1274NewFPFeatures.setDisallowFPContract();1275break;1276case LangOptions::FPM_FastHonorPragmas:1277llvm_unreachable("Should not happen");1278}1279FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);1280CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());1281}12821283void Sema::ActOnPragmaFPValueChangingOption(SourceLocation Loc,1284PragmaFPKind Kind, bool IsEnabled) {1285if (IsEnabled) {1286// For value unsafe context, combining this pragma with eval method1287// setting is not recommended. See comment in function FixupInvocation#506.1288int Reason = -1;1289if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)1290// Eval method set using the option 'ffp-eval-method'.1291Reason = 1;1292if (PP.getLastFPEvalPragmaLocation().isValid())1293// Eval method set using the '#pragma clang fp eval_method'.1294// We could have both an option and a pragma used to the set the eval1295// method. The pragma overrides the option in the command line. The Reason1296// of the diagnostic is overriden too.1297Reason = 0;1298if (Reason != -1)1299Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context)1300<< Reason << (Kind == PFK_Reassociate ? 4 : 5);1301}13021303FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();1304switch (Kind) {1305case PFK_Reassociate:1306NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);1307break;1308case PFK_Reciprocal:1309NewFPFeatures.setAllowReciprocalOverride(IsEnabled);1310break;1311default:1312llvm_unreachable("unhandled value changing pragma fp");1313}13141315FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);1316CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());1317}13181319void Sema::ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode FPR) {1320FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();1321NewFPFeatures.setConstRoundingModeOverride(FPR);1322FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);1323CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());1324}13251326void Sema::setExceptionMode(SourceLocation Loc,1327LangOptions::FPExceptionModeKind FPE) {1328FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();1329NewFPFeatures.setSpecifiedExceptionModeOverride(FPE);1330FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);1331CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());1332}13331334void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {1335FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();1336if (IsEnabled) {1337// Verify Microsoft restriction:1338// You can't enable fenv_access unless precise semantics are enabled.1339// Precise semantics can be enabled either by the float_control1340// pragma, or by using the /fp:precise or /fp:strict compiler options1341if (!isPreciseFPEnabled())1342Diag(Loc, diag::err_pragma_fenv_requires_precise);1343}1344NewFPFeatures.setAllowFEnvAccessOverride(IsEnabled);1345NewFPFeatures.setRoundingMathOverride(IsEnabled);1346FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);1347CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());1348}13491350void Sema::ActOnPragmaCXLimitedRange(SourceLocation Loc,1351LangOptions::ComplexRangeKind Range) {1352FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();1353NewFPFeatures.setComplexRangeOverride(Range);1354FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);1355CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());1356}13571358void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,1359LangOptions::FPExceptionModeKind FPE) {1360setExceptionMode(Loc, FPE);1361}13621363void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,1364SourceLocation Loc) {1365// Visibility calculations will consider the namespace's visibility.1366// Here we just want to note that we're in a visibility context1367// which overrides any enclosing #pragma context, but doesn't itself1368// contribute visibility.1369PushPragmaVisibility(*this, NoVisibility, Loc);1370}13711372void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {1373if (!VisContext) {1374Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);1375return;1376}13771378// Pop visibility from stack1379VisStack *Stack = static_cast<VisStack*>(VisContext);13801381const std::pair<unsigned, SourceLocation> *Back = &Stack->back();1382bool StartsWithPragma = Back->first != NoVisibility;1383if (StartsWithPragma && IsNamespaceEnd) {1384Diag(Back->second, diag::err_pragma_push_visibility_mismatch);1385Diag(EndLoc, diag::note_surrounding_namespace_ends_here);13861387// For better error recovery, eat all pushes inside the namespace.1388do {1389Stack->pop_back();1390Back = &Stack->back();1391StartsWithPragma = Back->first != NoVisibility;1392} while (StartsWithPragma);1393} else if (!StartsWithPragma && !IsNamespaceEnd) {1394Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);1395Diag(Back->second, diag::note_surrounding_namespace_starts_here);1396return;1397}13981399Stack->pop_back();1400// To simplify the implementation, never keep around an empty stack.1401if (Stack->empty())1402FreeVisContext();1403}14041405template <typename Ty>1406static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,1407const ParsedAttr &A,1408bool SkipArgCountCheck) {1409// Several attributes carry different semantics than the parsing requires, so1410// those are opted out of the common argument checks.1411//1412// We also bail on unknown and ignored attributes because those are handled1413// as part of the target-specific handling logic.1414if (A.getKind() == ParsedAttr::UnknownAttribute)1415return false;1416// Check whether the attribute requires specific language extensions to be1417// enabled.1418if (!A.diagnoseLangOpts(S))1419return true;1420// Check whether the attribute appertains to the given subject.1421if (!A.diagnoseAppertainsTo(S, Node))1422return true;1423// Check whether the attribute is mutually exclusive with other attributes1424// that have already been applied to the declaration.1425if (!A.diagnoseMutualExclusion(S, Node))1426return true;1427// Check whether the attribute exists in the target architecture.1428if (S.CheckAttrTarget(A))1429return true;14301431if (A.hasCustomParsing())1432return false;14331434if (!SkipArgCountCheck) {1435if (A.getMinArgs() == A.getMaxArgs()) {1436// If there are no optional arguments, then checking for the argument1437// count is trivial.1438if (!A.checkExactlyNumArgs(S, A.getMinArgs()))1439return true;1440} else {1441// There are optional arguments, so checking is slightly more involved.1442if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, A.getMinArgs()))1443return true;1444else if (!A.hasVariadicArg() && A.getMaxArgs() &&1445!A.checkAtMostNumArgs(S, A.getMaxArgs()))1446return true;1447}1448}14491450return false;1451}14521453bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,1454bool SkipArgCountCheck) {1455return ::checkCommonAttributeFeatures(*this, D, A, SkipArgCountCheck);1456}1457bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,1458bool SkipArgCountCheck) {1459return ::checkCommonAttributeFeatures(*this, S, A, SkipArgCountCheck);1460}146114621463