1//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for non-trivial attributes and
10// pragmas.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/Attr.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/Expr.h"
18#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Sema/Lookup.h"
22#include <optional>
23using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// Pragma 'pack' and 'options align'
27//===----------------------------------------------------------------------===//
28
29Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
30 StringRef SlotLabel,
31 bool ShouldAct)
32 : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
33 if (ShouldAct) {
34 S.VtorDispStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
35 S.DataSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
36 S.BSSSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
37 S.ConstSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
38 S.CodeSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
39 S.StrictGuardStackCheckStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
40 }
41}
42
43Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
44 if (ShouldAct) {
45 S.VtorDispStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
46 S.DataSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
47 S.BSSSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
48 S.ConstSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
49 S.CodeSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
50 S.StrictGuardStackCheckStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
51 }
52}
53
54void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
55 AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
56 AlignPackInfo::Mode M = InfoVal.getAlignMode();
57 bool IsPackSet = InfoVal.IsPackSet();
58 bool IsXLPragma = getLangOpts().XLPragmaPack;
59
60 // If we are not under mac68k/natural alignment mode and also there is no pack
61 // value, we don't need any attributes.
62 if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)
63 return;
64
65 if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {
66 RD->addAttr(A: AlignMac68kAttr::CreateImplicit(Ctx&: Context));
67 } else if (IsPackSet) {
68 // Check to see if we need a max field alignment attribute.
69 RD->addAttr(A: MaxFieldAlignmentAttr::CreateImplicit(
70 Ctx&: Context, Alignment: InfoVal.getPackNumber() * 8));
71 }
72
73 if (IsXLPragma && M == AlignPackInfo::Natural)
74 RD->addAttr(A: AlignNaturalAttr::CreateImplicit(Ctx&: Context));
75
76 if (AlignPackIncludeStack.empty())
77 return;
78 // The #pragma align/pack affected a record in an included file, so Clang
79 // should warn when that pragma was written in a file that included the
80 // included file.
81 for (auto &AlignPackedInclude : llvm::reverse(C&: AlignPackIncludeStack)) {
82 if (AlignPackedInclude.CurrentPragmaLocation !=
83 AlignPackStack.CurrentPragmaLocation)
84 break;
85 if (AlignPackedInclude.HasNonDefaultValue)
86 AlignPackedInclude.ShouldWarnOnInclude = true;
87 }
88}
89
90void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
91 if (MSStructPragmaOn)
92 RD->addAttr(A: MSStructAttr::CreateImplicit(Ctx&: Context));
93
94 // FIXME: We should merge AddAlignmentAttributesForRecord with
95 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
96 // all active pragmas and applies them as attributes to class definitions.
97 if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
98 RD->addAttr(A: MSVtorDispAttr::CreateImplicit(
99 Ctx&: Context, Vdm: unsigned(VtorDispStack.CurrentValue)));
100}
101
102template <typename Attribute>
103static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
104 CXXRecordDecl *Record) {
105 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
106 return;
107
108 for (Decl *Redecl : Record->redecls())
109 Redecl->addAttr(A: Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
110}
111
112void Sema::inferGslPointerAttribute(NamedDecl *ND,
113 CXXRecordDecl *UnderlyingRecord) {
114 if (!UnderlyingRecord)
115 return;
116
117 const auto *Parent = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
118 if (!Parent)
119 return;
120
121 static const llvm::StringSet<> Containers{
122 "array",
123 "basic_string",
124 "deque",
125 "forward_list",
126 "vector",
127 "list",
128 "map",
129 "multiset",
130 "multimap",
131 "priority_queue",
132 "queue",
133 "set",
134 "stack",
135 "unordered_set",
136 "unordered_map",
137 "unordered_multiset",
138 "unordered_multimap",
139 "flat_map",
140 "flat_set",
141 };
142
143 static const llvm::StringSet<> Iterators{"iterator", "const_iterator",
144 "reverse_iterator",
145 "const_reverse_iterator"};
146
147 if (Parent->isInStdNamespace() && Iterators.count(Key: ND->getName()) &&
148 Containers.count(Key: Parent->getName()))
149 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
150 Record: UnderlyingRecord);
151}
152
153void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
154
155 QualType Canonical = TD->getUnderlyingType().getCanonicalType();
156
157 CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
158 if (!RD) {
159 if (auto *TST =
160 dyn_cast<TemplateSpecializationType>(Val: Canonical.getTypePtr())) {
161
162 if (const auto *TD = TST->getTemplateName().getAsTemplateDecl())
163 RD = dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl());
164 }
165 }
166
167 inferGslPointerAttribute(ND: TD, UnderlyingRecord: RD);
168}
169
170void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
171 static const llvm::StringSet<> StdOwners{
172 "any",
173 "array",
174 "basic_regex",
175 "basic_string",
176 "deque",
177 "forward_list",
178 "vector",
179 "list",
180 "map",
181 "multiset",
182 "multimap",
183 "optional",
184 "priority_queue",
185 "queue",
186 "set",
187 "stack",
188 "unique_ptr",
189 "unordered_set",
190 "unordered_map",
191 "unordered_multiset",
192 "unordered_multimap",
193 "variant",
194 "flat_map",
195 "flat_set",
196 };
197 static const llvm::StringSet<> StdPointers{
198 "basic_string_view",
199 "reference_wrapper",
200 "regex_iterator",
201 "span",
202 };
203
204 if (!Record->getIdentifier())
205 return;
206
207 // Handle classes that directly appear in std namespace.
208 if (Record->isInStdNamespace()) {
209 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
210 return;
211
212 if (StdOwners.count(Key: Record->getName()))
213 addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
214 else if (StdPointers.count(Key: Record->getName()))
215 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
216
217 return;
218 }
219
220 // Handle nested classes that could be a gsl::Pointer.
221 inferGslPointerAttribute(ND: Record, UnderlyingRecord: Record);
222}
223
224void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
225 if (FD->getNumParams() == 0)
226 return;
227 // Skip void returning functions (except constructors). This can occur in
228 // cases like 'as_const'.
229 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType())
230 return;
231
232 if (unsigned BuiltinID = FD->getBuiltinID()) {
233 // Add lifetime attribute to std::move, std::fowrard et al.
234 switch (BuiltinID) {
235 case Builtin::BIaddressof:
236 case Builtin::BI__addressof:
237 case Builtin::BI__builtin_addressof:
238 case Builtin::BIas_const:
239 case Builtin::BIforward:
240 case Builtin::BIforward_like:
241 case Builtin::BImove:
242 case Builtin::BImove_if_noexcept:
243 if (ParmVarDecl *P = FD->getParamDecl(i: 0u);
244 !P->hasAttr<LifetimeBoundAttr>())
245 P->addAttr(
246 A: LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
247 break;
248 default:
249 break;
250 }
251 return;
252 }
253 if (auto *CMD = dyn_cast<CXXMethodDecl>(Val: FD)) {
254 const auto *CRD = CMD->getParent();
255 if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
256 return;
257
258 if (isa<CXXConstructorDecl>(Val: CMD)) {
259 auto *Param = CMD->getParamDecl(i: 0);
260 if (Param->hasAttr<LifetimeBoundAttr>())
261 return;
262 if (CRD->getName() == "basic_string_view" &&
263 Param->getType()->isPointerType()) {
264 // construct from a char array pointed by a pointer.
265 // basic_string_view(const CharT* s);
266 // basic_string_view(const CharT* s, size_type count);
267 Param->addAttr(
268 A: LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
269 } else if (CRD->getName() == "span") {
270 // construct from a reference of array.
271 // span(std::type_identity_t<element_type> (&arr)[N]);
272 const auto *LRT = Param->getType()->getAs<LValueReferenceType>();
273 if (LRT && LRT->getPointeeType().IgnoreParens()->isArrayType())
274 Param->addAttr(
275 A: LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
276 }
277 }
278 }
279}
280
281void Sema::inferLifetimeCaptureByAttribute(FunctionDecl *FD) {
282 auto *MD = dyn_cast_if_present<CXXMethodDecl>(Val: FD);
283 if (!MD || !MD->getParent()->isInStdNamespace())
284 return;
285 auto Annotate = [this](const FunctionDecl *MD) {
286 // Do not infer if any parameter is explicitly annotated.
287 for (ParmVarDecl *PVD : MD->parameters())
288 if (PVD->hasAttr<LifetimeCaptureByAttr>())
289 return;
290 for (ParmVarDecl *PVD : MD->parameters()) {
291 // Methods in standard containers that capture values typically accept
292 // reference-type parameters, e.g., `void push_back(const T& value)`.
293 // We only apply the lifetime_capture_by attribute to parameters of
294 // pointer-like reference types (`const T&`, `T&&`).
295 if (PVD->getType()->isReferenceType() &&
296 lifetimes::isGslPointerType(QT: PVD->getType().getNonReferenceType())) {
297 int CaptureByThis[] = {LifetimeCaptureByAttr::This};
298 PVD->addAttr(
299 A: LifetimeCaptureByAttr::CreateImplicit(Ctx&: Context, Params: CaptureByThis, ParamsSize: 1));
300 }
301 }
302 };
303
304 if (!MD->getIdentifier()) {
305 static const llvm::StringSet<> MapLikeContainer{
306 "map",
307 "multimap",
308 "unordered_map",
309 "unordered_multimap",
310 };
311 // Infer for the map's operator []:
312 // std::map<string_view, ...> m;
313 // m[ReturnString(..)] = ...; // !dangling references in m.
314 if (MD->getOverloadedOperator() == OO_Subscript &&
315 MapLikeContainer.contains(key: MD->getParent()->getName()))
316 Annotate(MD);
317 return;
318 }
319 static const llvm::StringSet<> CapturingMethods{
320 "insert", "insert_or_assign", "push", "push_front", "push_back"};
321 if (!CapturingMethods.contains(key: MD->getName()))
322 return;
323 if (MD->getName() == "insert" && MD->getParent()->getName() == "basic_string")
324 return;
325 Annotate(MD);
326}
327
328void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
329 static const llvm::StringSet<> Nullable{
330 "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
331 "coroutine_handle", "function", "move_only_function",
332 };
333
334 if (CRD->isInStdNamespace() && Nullable.count(Key: CRD->getName()) &&
335 !CRD->hasAttr<TypeNullableAttr>())
336 for (Decl *Redecl : CRD->redecls())
337 Redecl->addAttr(A: TypeNullableAttr::CreateImplicit(Ctx&: Context));
338}
339
340void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
341 SourceLocation PragmaLoc) {
342 PragmaMsStackAction Action = Sema::PSK_Reset;
343 AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
344
345 switch (Kind) {
346 // For most of the platforms we support, native and natural are the same.
347 // With XL, native is the same as power, natural means something else.
348 case PragmaOptionsAlignKind::Native:
349 case PragmaOptionsAlignKind::Power:
350 Action = Sema::PSK_Push_Set;
351 break;
352 case PragmaOptionsAlignKind::Natural:
353 Action = Sema::PSK_Push_Set;
354 ModeVal = AlignPackInfo::Natural;
355 break;
356
357 // Note that '#pragma options align=packed' is not equivalent to attribute
358 // packed, it has a different precedence relative to attribute aligned.
359 case PragmaOptionsAlignKind::Packed:
360 Action = Sema::PSK_Push_Set;
361 ModeVal = AlignPackInfo::Packed;
362 break;
363
364 case PragmaOptionsAlignKind::Mac68k:
365 // Check if the target supports this.
366 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
367 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_options_align_mac68k_target_unsupported);
368 return;
369 }
370 Action = Sema::PSK_Push_Set;
371 ModeVal = AlignPackInfo::Mac68k;
372 break;
373 case PragmaOptionsAlignKind::Reset:
374 // Reset just pops the top of the stack, or resets the current alignment to
375 // default.
376 Action = Sema::PSK_Pop;
377 if (AlignPackStack.Stack.empty()) {
378 if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
379 AlignPackStack.CurrentValue.IsPackAttr()) {
380 Action = Sema::PSK_Reset;
381 } else {
382 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_options_align_reset_failed)
383 << "stack empty";
384 return;
385 }
386 }
387 break;
388 }
389
390 AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
391
392 AlignPackStack.Act(PragmaLocation: PragmaLoc, Action, StackSlotLabel: StringRef(), Value: Info);
393}
394
395void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
396 PragmaClangSectionAction Action,
397 PragmaClangSectionKind SecKind,
398 StringRef SecName) {
399 PragmaClangSection *CSec;
400 int SectionFlags = ASTContext::PSF_Read;
401 switch (SecKind) {
402 case PragmaClangSectionKind::BSS:
403 CSec = &PragmaClangBSSSection;
404 SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
405 break;
406 case PragmaClangSectionKind::Data:
407 CSec = &PragmaClangDataSection;
408 SectionFlags |= ASTContext::PSF_Write;
409 break;
410 case PragmaClangSectionKind::Rodata:
411 CSec = &PragmaClangRodataSection;
412 break;
413 case PragmaClangSectionKind::Relro:
414 CSec = &PragmaClangRelroSection;
415 break;
416 case PragmaClangSectionKind::Text:
417 CSec = &PragmaClangTextSection;
418 SectionFlags |= ASTContext::PSF_Execute;
419 break;
420 default:
421 llvm_unreachable("invalid clang section kind");
422 }
423
424 if (Action == PragmaClangSectionAction::Clear) {
425 CSec->Valid = false;
426 return;
427 }
428
429 if (llvm::Error E = isValidSectionSpecifier(Str: SecName)) {
430 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_section_invalid_for_target)
431 << toString(E: std::move(E));
432 CSec->Valid = false;
433 return;
434 }
435
436 if (UnifySection(SectionName: SecName, SectionFlags, PragmaSectionLocation: PragmaLoc))
437 return;
438
439 CSec->Valid = true;
440 CSec->SectionName = std::string(SecName);
441 CSec->PragmaLocation = PragmaLoc;
442}
443
444void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
445 StringRef SlotLabel, Expr *Alignment) {
446 bool IsXLPragma = getLangOpts().XLPragmaPack;
447 // XL pragma pack does not support identifier syntax.
448 if (IsXLPragma && !SlotLabel.empty()) {
449 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_pack_identifer_not_supported);
450 return;
451 }
452
453 const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
454
455 // If specified then alignment must be a "small" power of two.
456 unsigned AlignmentVal = 0;
457 AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
458
459 if (Alignment) {
460 std::optional<llvm::APSInt> Val;
461 Val = Alignment->getIntegerConstantExpr(Ctx: Context);
462
463 // pack(0) is like pack(), which just works out since that is what
464 // we use 0 for in PackAttr.
465 if (Alignment->isTypeDependent() || !Val ||
466 !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
467 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_pack_invalid_alignment);
468 return; // Ignore
469 }
470
471 if (IsXLPragma && *Val == 0) {
472 // pack(0) does not work out with XL.
473 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_pack_invalid_alignment);
474 return; // Ignore
475 }
476
477 AlignmentVal = (unsigned)Val->getZExtValue();
478 }
479
480 if (Action == Sema::PSK_Show) {
481 // Show the current alignment, making sure to show the right value
482 // for the default.
483 // FIXME: This should come from the target.
484 AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
485 if (ModeVal == AlignPackInfo::Mac68k &&
486 (IsXLPragma || CurVal.IsAlignAttr()))
487 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_pack_show) << "mac68k";
488 else
489 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_pack_show) << AlignmentVal;
490 }
491
492 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
493 // "#pragma pack(pop, identifier, n) is undefined"
494 if (Action & Sema::PSK_Pop) {
495 if (Alignment && !SlotLabel.empty())
496 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_pack_pop_identifier_and_alignment);
497 if (AlignPackStack.Stack.empty()) {
498 assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
499 "Empty pack stack can only be at Native alignment mode.");
500 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_pop_failed) << "pack" << "stack empty";
501 }
502 }
503
504 AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
505
506 AlignPackStack.Act(PragmaLocation: PragmaLoc, Action, StackSlotLabel: SlotLabel, Value: Info);
507}
508
509bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
510 MutableArrayRef<Expr *> Args) {
511 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
512 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
513 Expr *&E = Args.begin()[Idx];
514 assert(E && "error are handled before");
515 if (E->isValueDependent() || E->isTypeDependent())
516 continue;
517
518 // FIXME: Use DefaultFunctionArrayLValueConversion() in place of the logic
519 // that adds implicit casts here.
520 if (E->getType()->isArrayType())
521 E = ImpCastExprToType(E, Type: Context.getPointerType(T: E->getType()),
522 CK: clang::CK_ArrayToPointerDecay)
523 .get();
524 if (E->getType()->isFunctionType())
525 E = ImplicitCastExpr::Create(Context,
526 T: Context.getPointerType(T: E->getType()),
527 Kind: clang::CK_FunctionToPointerDecay, Operand: E, BasePath: nullptr,
528 Cat: VK_PRValue, FPO: FPOptionsOverride());
529 if (E->isLValue())
530 E = ImplicitCastExpr::Create(Context, T: E->getType().getNonReferenceType(),
531 Kind: clang::CK_LValueToRValue, Operand: E, BasePath: nullptr,
532 Cat: VK_PRValue, FPO: FPOptionsOverride());
533
534 Expr::EvalResult Eval;
535 Notes.clear();
536 Eval.Diag = &Notes;
537
538 bool Result = E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context);
539
540 /// Result means the expression can be folded to a constant.
541 /// Note.empty() means the expression is a valid constant expression in the
542 /// current language mode.
543 if (!Result || !Notes.empty()) {
544 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_attribute_argument_n_type)
545 << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
546 for (auto &Note : Notes)
547 Diag(Loc: Note.first, PD: Note.second);
548 return false;
549 }
550 E = ConstantExpr::Create(Context, E, Result: Eval.Val);
551 }
552
553 return true;
554}
555
556void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
557 SourceLocation IncludeLoc) {
558 if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
559 SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
560 // Warn about non-default alignment at #includes (without redundant
561 // warnings for the same directive in nested includes).
562 // The warning is delayed until the end of the file to avoid warnings
563 // for files that don't have any records that are affected by the modified
564 // alignment.
565 bool HasNonDefaultValue =
566 AlignPackStack.hasValue() &&
567 (AlignPackIncludeStack.empty() ||
568 AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
569 AlignPackIncludeStack.push_back(
570 Elt: {.CurrentValue: AlignPackStack.CurrentValue,
571 .CurrentPragmaLocation: AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
572 .HasNonDefaultValue: HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
573 return;
574 }
575
576 assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
577 "invalid kind");
578 AlignPackIncludeState PrevAlignPackState =
579 AlignPackIncludeStack.pop_back_val();
580 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
581 // information, diagnostics below might not be accurate if we have mixed
582 // pragmas.
583 if (PrevAlignPackState.ShouldWarnOnInclude) {
584 // Emit the delayed non-default alignment at #include warning.
585 Diag(Loc: IncludeLoc, DiagID: diag::warn_pragma_pack_non_default_at_include);
586 Diag(Loc: PrevAlignPackState.CurrentPragmaLocation, DiagID: diag::note_pragma_pack_here);
587 }
588 // Warn about modified alignment after #includes.
589 if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
590 Diag(Loc: IncludeLoc, DiagID: diag::warn_pragma_pack_modified_after_include);
591 Diag(Loc: AlignPackStack.CurrentPragmaLocation, DiagID: diag::note_pragma_pack_here);
592 }
593}
594
595void Sema::DiagnoseUnterminatedPragmaAlignPack() {
596 if (AlignPackStack.Stack.empty())
597 return;
598 bool IsInnermost = true;
599
600 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
601 // information, diagnostics below might not be accurate if we have mixed
602 // pragmas.
603 for (const auto &StackSlot : llvm::reverse(C&: AlignPackStack.Stack)) {
604 Diag(Loc: StackSlot.PragmaPushLocation, DiagID: diag::warn_pragma_pack_no_pop_eof);
605 // The user might have already reset the alignment, so suggest replacing
606 // the reset with a pop.
607 if (IsInnermost &&
608 AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
609 auto DB = Diag(Loc: AlignPackStack.CurrentPragmaLocation,
610 DiagID: diag::note_pragma_pack_pop_instead_reset);
611 SourceLocation FixItLoc =
612 Lexer::findLocationAfterToken(loc: AlignPackStack.CurrentPragmaLocation,
613 TKind: tok::l_paren, SM: SourceMgr, LangOpts,
614 /*SkipTrailing=*/SkipTrailingWhitespaceAndNewLine: false);
615 if (FixItLoc.isValid())
616 DB << FixItHint::CreateInsertion(InsertionLoc: FixItLoc, Code: "pop");
617 }
618 IsInnermost = false;
619 }
620}
621
622void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
623 MSStructPragmaOn = (Kind == PMSST_ON);
624}
625
626void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
627 PragmaMSCommentKind Kind, StringRef Arg) {
628 auto *PCD = PragmaCommentDecl::Create(
629 C: Context, DC: Context.getTranslationUnitDecl(), CommentLoc, CommentKind: Kind, Arg);
630 Context.getTranslationUnitDecl()->addDecl(D: PCD);
631 Consumer.HandleTopLevelDecl(D: DeclGroupRef(PCD));
632}
633
634void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
635 StringRef Value) {
636 auto *PDMD = PragmaDetectMismatchDecl::Create(
637 C: Context, DC: Context.getTranslationUnitDecl(), Loc, Name, Value);
638 Context.getTranslationUnitDecl()->addDecl(D: PDMD);
639 Consumer.HandleTopLevelDecl(D: DeclGroupRef(PDMD));
640}
641
642void Sema::ActOnPragmaFPEvalMethod(SourceLocation Loc,
643 LangOptions::FPEvalMethodKind Value) {
644 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
645 switch (Value) {
646 default:
647 llvm_unreachable("invalid pragma eval_method kind");
648 case LangOptions::FEM_Source:
649 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
650 break;
651 case LangOptions::FEM_Double:
652 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
653 break;
654 case LangOptions::FEM_Extended:
655 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
656 break;
657 }
658 if (getLangOpts().ApproxFunc)
659 Diag(Loc, DiagID: diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
660 if (getLangOpts().AllowFPReassoc)
661 Diag(Loc, DiagID: diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
662 if (getLangOpts().AllowRecip)
663 Diag(Loc, DiagID: diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
664 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
665 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
666 PP.setCurrentFPEvalMethod(PragmaLoc: Loc, Val: Value);
667}
668
669void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
670 PragmaMsStackAction Action,
671 PragmaFloatControlKind Value) {
672 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
673 if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
674 !CurContext->getRedeclContext()->isFileContext()) {
675 // Push and pop can only occur at file or namespace scope, or within a
676 // language linkage declaration.
677 Diag(Loc, DiagID: diag::err_pragma_fc_pp_scope);
678 return;
679 }
680 switch (Value) {
681 default:
682 llvm_unreachable("invalid pragma float_control kind");
683 case PFC_Precise:
684 NewFPFeatures.setFPPreciseEnabled(true);
685 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
686 break;
687 case PFC_NoPrecise:
688 if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict)
689 Diag(Loc, DiagID: diag::err_pragma_fc_noprecise_requires_noexcept);
690 else if (CurFPFeatures.getAllowFEnvAccess())
691 Diag(Loc, DiagID: diag::err_pragma_fc_noprecise_requires_nofenv);
692 else
693 NewFPFeatures.setFPPreciseEnabled(false);
694 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
695 break;
696 case PFC_Except:
697 if (!isPreciseFPEnabled())
698 Diag(Loc, DiagID: diag::err_pragma_fc_except_requires_precise);
699 else
700 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Strict);
701 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
702 break;
703 case PFC_NoExcept:
704 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Ignore);
705 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
706 break;
707 case PFC_Push:
708 FpPragmaStack.Act(PragmaLocation: Loc, Action: Sema::PSK_Push_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
709 break;
710 case PFC_Pop:
711 if (FpPragmaStack.Stack.empty()) {
712 Diag(Loc, DiagID: diag::warn_pragma_pop_failed) << "float_control"
713 << "stack empty";
714 return;
715 }
716 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
717 NewFPFeatures = FpPragmaStack.CurrentValue;
718 break;
719 }
720 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
721}
722
723void Sema::ActOnPragmaMSPointersToMembers(
724 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
725 SourceLocation PragmaLoc) {
726 MSPointerToMemberRepresentationMethod = RepresentationMethod;
727 ImplicitMSInheritanceAttrLoc = PragmaLoc;
728}
729
730void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
731 SourceLocation PragmaLoc,
732 MSVtorDispMode Mode) {
733 if (Action & PSK_Pop && VtorDispStack.Stack.empty())
734 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_pop_failed) << "vtordisp"
735 << "stack empty";
736 VtorDispStack.Act(PragmaLocation: PragmaLoc, Action, StackSlotLabel: StringRef(), Value: Mode);
737}
738
739template <>
740void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
741 PragmaMsStackAction Action,
742 llvm::StringRef StackSlotLabel,
743 AlignPackInfo Value) {
744 if (Action == PSK_Reset) {
745 CurrentValue = DefaultValue;
746 CurrentPragmaLocation = PragmaLocation;
747 return;
748 }
749 if (Action & PSK_Push)
750 Stack.emplace_back(Args: Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
751 PragmaLocation));
752 else if (Action & PSK_Pop) {
753 if (!StackSlotLabel.empty()) {
754 // If we've got a label, try to find it and jump there.
755 auto I = llvm::find_if(Range: llvm::reverse(C&: Stack), P: [&](const Slot &x) {
756 return x.StackSlotLabel == StackSlotLabel;
757 });
758 // We found the label, so pop from there.
759 if (I != Stack.rend()) {
760 CurrentValue = I->Value;
761 CurrentPragmaLocation = I->PragmaLocation;
762 Stack.erase(CS: std::prev(x: I.base()), CE: Stack.end());
763 }
764 } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
765 CurrentValue.IsPackAttr()) {
766 // XL '#pragma align(reset)' would pop the stack until
767 // a current in effect pragma align is popped.
768 auto I = llvm::find_if(Range: llvm::reverse(C&: Stack), P: [&](const Slot &x) {
769 return x.Value.IsAlignAttr();
770 });
771 // If we found pragma align so pop from there.
772 if (I != Stack.rend()) {
773 Stack.erase(CS: std::prev(x: I.base()), CE: Stack.end());
774 if (Stack.empty()) {
775 CurrentValue = DefaultValue;
776 CurrentPragmaLocation = PragmaLocation;
777 } else {
778 CurrentValue = Stack.back().Value;
779 CurrentPragmaLocation = Stack.back().PragmaLocation;
780 Stack.pop_back();
781 }
782 }
783 } else if (!Stack.empty()) {
784 // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
785 // over the baseline.
786 if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
787 return;
788
789 // We don't have a label, just pop the last entry.
790 CurrentValue = Stack.back().Value;
791 CurrentPragmaLocation = Stack.back().PragmaLocation;
792 Stack.pop_back();
793 }
794 }
795 if (Action & PSK_Set) {
796 CurrentValue = Value;
797 CurrentPragmaLocation = PragmaLocation;
798 }
799}
800
801bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
802 NamedDecl *Decl) {
803 SourceLocation PragmaLocation;
804 if (auto A = Decl->getAttr<SectionAttr>())
805 if (A->isImplicit())
806 PragmaLocation = A->getLocation();
807 auto [SectionIt, Inserted] = Context.SectionInfos.try_emplace(
808 Key: SectionName, Args&: Decl, Args&: PragmaLocation, Args&: SectionFlags);
809 if (Inserted)
810 return false;
811 // A pre-declared section takes precedence w/o diagnostic.
812 const auto &Section = SectionIt->second;
813 if (Section.SectionFlags == SectionFlags ||
814 ((SectionFlags & ASTContext::PSF_Implicit) &&
815 !(Section.SectionFlags & ASTContext::PSF_Implicit)))
816 return false;
817 Diag(Loc: Decl->getLocation(), DiagID: diag::err_section_conflict) << Decl << Section;
818 if (Section.Decl)
819 Diag(Loc: Section.Decl->getLocation(), DiagID: diag::note_declared_at)
820 << Section.Decl->getName();
821 if (PragmaLocation.isValid())
822 Diag(Loc: PragmaLocation, DiagID: diag::note_pragma_entered_here);
823 if (Section.PragmaSectionLocation.isValid())
824 Diag(Loc: Section.PragmaSectionLocation, DiagID: diag::note_pragma_entered_here);
825 return true;
826}
827
828bool Sema::UnifySection(StringRef SectionName,
829 int SectionFlags,
830 SourceLocation PragmaSectionLocation) {
831 auto SectionIt = Context.SectionInfos.find(Key: SectionName);
832 if (SectionIt != Context.SectionInfos.end()) {
833 const auto &Section = SectionIt->second;
834 if (Section.SectionFlags == SectionFlags)
835 return false;
836 if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
837 Diag(Loc: PragmaSectionLocation, DiagID: diag::err_section_conflict)
838 << "this" << Section;
839 if (Section.Decl)
840 Diag(Loc: Section.Decl->getLocation(), DiagID: diag::note_declared_at)
841 << Section.Decl->getName();
842 if (Section.PragmaSectionLocation.isValid())
843 Diag(Loc: Section.PragmaSectionLocation, DiagID: diag::note_pragma_entered_here);
844 return true;
845 }
846 }
847 Context.SectionInfos[SectionName] =
848 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
849 return false;
850}
851
852/// Called on well formed \#pragma bss_seg().
853void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
854 PragmaMsStackAction Action,
855 llvm::StringRef StackSlotLabel,
856 StringLiteral *SegmentName,
857 llvm::StringRef PragmaName) {
858 PragmaStack<StringLiteral *> *Stack =
859 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
860 .Case(S: "data_seg", Value: &DataSegStack)
861 .Case(S: "bss_seg", Value: &BSSSegStack)
862 .Case(S: "const_seg", Value: &ConstSegStack)
863 .Case(S: "code_seg", Value: &CodeSegStack);
864 if (Action & PSK_Pop && Stack->Stack.empty())
865 Diag(Loc: PragmaLocation, DiagID: diag::warn_pragma_pop_failed) << PragmaName
866 << "stack empty";
867 if (SegmentName) {
868 if (!checkSectionName(LiteralLoc: SegmentName->getBeginLoc(), Str: SegmentName->getString()))
869 return;
870
871 if (SegmentName->getString() == ".drectve" &&
872 Context.getTargetInfo().getCXXABI().isMicrosoft())
873 Diag(Loc: PragmaLocation, DiagID: diag::warn_attribute_section_drectve) << PragmaName;
874 }
875
876 Stack->Act(PragmaLocation, Action, StackSlotLabel, Value: SegmentName);
877}
878
879/// Called on well formed \#pragma strict_gs_check().
880void Sema::ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
881 PragmaMsStackAction Action,
882 bool Value) {
883 if (Action & PSK_Pop && StrictGuardStackCheckStack.Stack.empty())
884 Diag(Loc: PragmaLocation, DiagID: diag::warn_pragma_pop_failed) << "strict_gs_check"
885 << "stack empty";
886
887 StrictGuardStackCheckStack.Act(PragmaLocation, Action, StackSlotLabel: StringRef(), Value);
888}
889
890/// Called on well formed \#pragma bss_seg().
891void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
892 int SectionFlags, StringLiteral *SegmentName) {
893 UnifySection(SectionName: SegmentName->getString(), SectionFlags, PragmaSectionLocation: PragmaLocation);
894}
895
896void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
897 StringLiteral *SegmentName) {
898 // There's no stack to maintain, so we just have a current section. When we
899 // see the default section, reset our current section back to null so we stop
900 // tacking on unnecessary attributes.
901 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
902 CurInitSegLoc = PragmaLocation;
903}
904
905void Sema::ActOnPragmaMSAllocText(
906 SourceLocation PragmaLocation, StringRef Section,
907 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
908 &Functions) {
909 if (!CurContext->getRedeclContext()->isFileContext()) {
910 Diag(Loc: PragmaLocation, DiagID: diag::err_pragma_expected_file_scope) << "alloc_text";
911 return;
912 }
913
914 for (auto &Function : Functions) {
915 IdentifierInfo *II;
916 SourceLocation Loc;
917 std::tie(args&: II, args&: Loc) = Function;
918
919 DeclarationName DN(II);
920 NamedDecl *ND = LookupSingleName(S: TUScope, Name: DN, Loc, NameKind: LookupOrdinaryName);
921 if (!ND) {
922 Diag(Loc, DiagID: diag::err_undeclared_use) << II->getName();
923 return;
924 }
925
926 auto *FD = dyn_cast<FunctionDecl>(Val: ND->getCanonicalDecl());
927 if (!FD) {
928 Diag(Loc, DiagID: diag::err_pragma_alloc_text_not_function);
929 return;
930 }
931
932 if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {
933 Diag(Loc, DiagID: diag::err_pragma_alloc_text_c_linkage);
934 return;
935 }
936
937 FunctionToSectionMap[II->getName()] = std::make_tuple(args&: Section, args&: Loc);
938 }
939}
940
941void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
942 SourceLocation PragmaLoc) {
943
944 IdentifierInfo *Name = IdTok.getIdentifierInfo();
945 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
946 LookupName(R&: Lookup, S: curScope, /*AllowBuiltinCreation=*/true);
947
948 if (Lookup.empty()) {
949 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_unused_undeclared_var)
950 << Name << SourceRange(IdTok.getLocation());
951 return;
952 }
953
954 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
955 if (!VD) {
956 Diag(Loc: PragmaLoc, DiagID: diag::warn_pragma_unused_expected_var_arg)
957 << Name << SourceRange(IdTok.getLocation());
958 return;
959 }
960
961 // Warn if this was used before being marked unused.
962 if (VD->isUsed())
963 Diag(Loc: PragmaLoc, DiagID: diag::warn_used_but_marked_unused) << Name;
964
965 VD->addAttr(A: UnusedAttr::CreateImplicit(Ctx&: Context, Range: IdTok.getLocation(),
966 S: UnusedAttr::GNU_unused));
967}
968
969namespace {
970
971std::optional<attr::SubjectMatchRule>
972getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
973 using namespace attr;
974 switch (Rule) {
975 default:
976 return std::nullopt;
977#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
978#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
979 case Value: \
980 return Parent;
981#include "clang/Basic/AttrSubMatchRulesList.inc"
982 }
983}
984
985bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
986 using namespace attr;
987 switch (Rule) {
988 default:
989 return false;
990#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
991#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
992 case Value: \
993 return IsNegated;
994#include "clang/Basic/AttrSubMatchRulesList.inc"
995 }
996}
997
998CharSourceRange replacementRangeForListElement(const Sema &S,
999 SourceRange Range) {
1000 // Make sure that the ',' is removed as well.
1001 SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
1002 loc: Range.getEnd(), TKind: tok::comma, SM: S.getSourceManager(), LangOpts: S.getLangOpts(),
1003 /*SkipTrailingWhitespaceAndNewLine=*/false);
1004 if (AfterCommaLoc.isValid())
1005 return CharSourceRange::getCharRange(B: Range.getBegin(), E: AfterCommaLoc);
1006 else
1007 return CharSourceRange::getTokenRange(R: Range);
1008}
1009
1010std::string
1011attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
1012 std::string Result;
1013 llvm::raw_string_ostream OS(Result);
1014 for (const auto &I : llvm::enumerate(First&: Rules)) {
1015 if (I.index())
1016 OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
1017 OS << "'" << attr::getSubjectMatchRuleSpelling(Rule: I.value()) << "'";
1018 }
1019 return Result;
1020}
1021
1022} // end anonymous namespace
1023
1024void Sema::ActOnPragmaAttributeAttribute(
1025 ParsedAttr &Attribute, SourceLocation PragmaLoc,
1026 attr::ParsedSubjectMatchRuleSet Rules) {
1027 Attribute.setIsPragmaClangAttribute();
1028 SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
1029 // Gather the subject match rules that are supported by the attribute.
1030 SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
1031 StrictSubjectMatchRuleSet;
1032 Attribute.getMatchRules(LangOpts, MatchRules&: StrictSubjectMatchRuleSet);
1033
1034 // Figure out which subject matching rules are valid.
1035 if (StrictSubjectMatchRuleSet.empty()) {
1036 // Check for contradicting match rules. Contradicting match rules are
1037 // either:
1038 // - a top-level rule and one of its sub-rules. E.g. variable and
1039 // variable(is_parameter).
1040 // - a sub-rule and a sibling that's negated. E.g.
1041 // variable(is_thread_local) and variable(unless(is_parameter))
1042 llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
1043 RulesToFirstSpecifiedNegatedSubRule;
1044 for (const auto &Rule : Rules) {
1045 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1046 std::optional<attr::SubjectMatchRule> ParentRule =
1047 getParentAttrMatcherRule(Rule: MatchRule);
1048 if (!ParentRule)
1049 continue;
1050 auto It = Rules.find(Val: *ParentRule);
1051 if (It != Rules.end()) {
1052 // A sub-rule contradicts a parent rule.
1053 Diag(Loc: Rule.second.getBegin(),
1054 DiagID: diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
1055 << attr::getSubjectMatchRuleSpelling(Rule: MatchRule)
1056 << attr::getSubjectMatchRuleSpelling(Rule: *ParentRule) << It->second
1057 << FixItHint::CreateRemoval(
1058 RemoveRange: replacementRangeForListElement(S: *this, Range: Rule.second));
1059 // Keep going without removing this rule as it won't change the set of
1060 // declarations that receive the attribute.
1061 continue;
1062 }
1063 if (isNegatedAttrMatcherSubRule(Rule: MatchRule))
1064 RulesToFirstSpecifiedNegatedSubRule.insert(
1065 KV: std::make_pair(x&: *ParentRule, y: Rule));
1066 }
1067 bool IgnoreNegatedSubRules = false;
1068 for (const auto &Rule : Rules) {
1069 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1070 std::optional<attr::SubjectMatchRule> ParentRule =
1071 getParentAttrMatcherRule(Rule: MatchRule);
1072 if (!ParentRule)
1073 continue;
1074 auto It = RulesToFirstSpecifiedNegatedSubRule.find(Val: *ParentRule);
1075 if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
1076 It->second != Rule) {
1077 // Negated sub-rule contradicts another sub-rule.
1078 Diag(
1079 Loc: It->second.second.getBegin(),
1080 DiagID: diag::
1081 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
1082 << attr::getSubjectMatchRuleSpelling(
1083 Rule: attr::SubjectMatchRule(It->second.first))
1084 << attr::getSubjectMatchRuleSpelling(Rule: MatchRule) << Rule.second
1085 << FixItHint::CreateRemoval(
1086 RemoveRange: replacementRangeForListElement(S: *this, Range: It->second.second));
1087 // Keep going but ignore all of the negated sub-rules.
1088 IgnoreNegatedSubRules = true;
1089 RulesToFirstSpecifiedNegatedSubRule.erase(I: It);
1090 }
1091 }
1092
1093 if (!IgnoreNegatedSubRules) {
1094 for (const auto &Rule : Rules)
1095 SubjectMatchRules.push_back(Elt: attr::SubjectMatchRule(Rule.first));
1096 } else {
1097 for (const auto &Rule : Rules) {
1098 if (!isNegatedAttrMatcherSubRule(Rule: attr::SubjectMatchRule(Rule.first)))
1099 SubjectMatchRules.push_back(Elt: attr::SubjectMatchRule(Rule.first));
1100 }
1101 }
1102 Rules.clear();
1103 } else {
1104 // Each rule in Rules must be a strict subset of the attribute's
1105 // SubjectMatch rules. I.e. we're allowed to use
1106 // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
1107 // but should not allow `apply_to=variables` on an attribute which has
1108 // `SubjectList<[GlobalVar]>`.
1109 for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
1110 // First, check for exact match.
1111 if (Rules.erase(Val: StrictRule.first)) {
1112 // Add the rule to the set of attribute receivers only if it's supported
1113 // in the current language mode.
1114 if (StrictRule.second)
1115 SubjectMatchRules.push_back(Elt: StrictRule.first);
1116 }
1117 }
1118 // Check remaining rules for subset matches.
1119 auto RulesToCheck = Rules;
1120 for (const auto &Rule : RulesToCheck) {
1121 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1122 if (auto ParentRule = getParentAttrMatcherRule(Rule: MatchRule)) {
1123 if (llvm::any_of(Range&: StrictSubjectMatchRuleSet,
1124 P: [ParentRule](const auto &StrictRule) {
1125 return StrictRule.first == *ParentRule &&
1126 StrictRule.second; // IsEnabled
1127 })) {
1128 SubjectMatchRules.push_back(Elt: MatchRule);
1129 Rules.erase(Val: MatchRule);
1130 }
1131 }
1132 }
1133 }
1134
1135 if (!Rules.empty()) {
1136 auto Diagnostic =
1137 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_attribute_invalid_matchers)
1138 << Attribute;
1139 SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
1140 for (const auto &Rule : Rules) {
1141 ExtraRules.push_back(Elt: attr::SubjectMatchRule(Rule.first));
1142 Diagnostic << FixItHint::CreateRemoval(
1143 RemoveRange: replacementRangeForListElement(S: *this, Range: Rule.second));
1144 }
1145 Diagnostic << attrMatcherRuleListToString(Rules: ExtraRules);
1146 }
1147
1148 if (PragmaAttributeStack.empty()) {
1149 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_attr_attr_no_push);
1150 return;
1151 }
1152
1153 PragmaAttributeStack.back().Entries.push_back(
1154 Elt: {.Loc: PragmaLoc, .Attribute: &Attribute, .MatchRules: std::move(SubjectMatchRules), /*IsUsed=*/false});
1155}
1156
1157void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
1158 const IdentifierInfo *Namespace) {
1159 PragmaAttributeStack.emplace_back();
1160 PragmaAttributeStack.back().Loc = PragmaLoc;
1161 PragmaAttributeStack.back().Namespace = Namespace;
1162}
1163
1164void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
1165 const IdentifierInfo *Namespace) {
1166 if (PragmaAttributeStack.empty()) {
1167 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_attribute_stack_mismatch) << 1;
1168 return;
1169 }
1170
1171 // Dig back through the stack trying to find the most recently pushed group
1172 // that in Namespace. Note that this works fine if no namespace is present,
1173 // think of push/pops without namespaces as having an implicit "nullptr"
1174 // namespace.
1175 for (size_t Index = PragmaAttributeStack.size(); Index;) {
1176 --Index;
1177 if (PragmaAttributeStack[Index].Namespace == Namespace) {
1178 for (const PragmaAttributeEntry &Entry :
1179 PragmaAttributeStack[Index].Entries) {
1180 if (!Entry.IsUsed) {
1181 assert(Entry.Attribute && "Expected an attribute");
1182 Diag(Loc: Entry.Attribute->getLoc(), DiagID: diag::warn_pragma_attribute_unused)
1183 << *Entry.Attribute;
1184 Diag(Loc: PragmaLoc, DiagID: diag::note_pragma_attribute_region_ends_here);
1185 }
1186 }
1187 PragmaAttributeStack.erase(CI: PragmaAttributeStack.begin() + Index);
1188 return;
1189 }
1190 }
1191
1192 if (Namespace)
1193 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_attribute_stack_mismatch)
1194 << 0 << Namespace->getName();
1195 else
1196 Diag(Loc: PragmaLoc, DiagID: diag::err_pragma_attribute_stack_mismatch) << 1;
1197}
1198
1199void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
1200 if (PragmaAttributeStack.empty())
1201 return;
1202
1203 if (const auto *P = dyn_cast<ParmVarDecl>(Val: D))
1204 if (P->getType()->isVoidType())
1205 return;
1206
1207 for (auto &Group : PragmaAttributeStack) {
1208 for (auto &Entry : Group.Entries) {
1209 ParsedAttr *Attribute = Entry.Attribute;
1210 assert(Attribute && "Expected an attribute");
1211 assert(Attribute->isPragmaClangAttribute() &&
1212 "expected #pragma clang attribute");
1213
1214 // Ensure that the attribute can be applied to the given declaration.
1215 bool Applies = false;
1216 for (const auto &Rule : Entry.MatchRules) {
1217 if (Attribute->appliesToDecl(D, MatchRule: Rule)) {
1218 Applies = true;
1219 break;
1220 }
1221 }
1222 if (!Applies)
1223 continue;
1224 Entry.IsUsed = true;
1225 PragmaAttributeCurrentTargetDecl = D;
1226 ParsedAttributesView Attrs;
1227 Attrs.addAtEnd(newAttr: Attribute);
1228 ProcessDeclAttributeList(S, D, AttrList: Attrs);
1229 PragmaAttributeCurrentTargetDecl = nullptr;
1230 }
1231 }
1232}
1233
1234void Sema::PrintPragmaAttributeInstantiationPoint(
1235 InstantiationContextDiagFuncRef DiagFunc) {
1236 assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
1237 DiagFunc(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
1238 PDiag(DiagID: diag::note_pragma_attribute_applied_decl_here));
1239}
1240
1241void Sema::DiagnosePrecisionLossInComplexDivision() {
1242 for (auto &[Type, Num] : ExcessPrecisionNotSatisfied) {
1243 assert(LocationOfExcessPrecisionNotSatisfied.isValid() &&
1244 "expected a valid source location");
1245 Diag(Loc: LocationOfExcessPrecisionNotSatisfied,
1246 DiagID: diag::warn_excess_precision_not_supported)
1247 << static_cast<bool>(Num);
1248 }
1249}
1250
1251void Sema::DiagnoseUnterminatedPragmaAttribute() {
1252 if (PragmaAttributeStack.empty())
1253 return;
1254 Diag(Loc: PragmaAttributeStack.back().Loc, DiagID: diag::err_pragma_attribute_no_pop_eof);
1255}
1256
1257void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
1258 if(On)
1259 OptimizeOffPragmaLocation = SourceLocation();
1260 else
1261 OptimizeOffPragmaLocation = PragmaLoc;
1262}
1263
1264void Sema::ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn) {
1265 if (!CurContext->getRedeclContext()->isFileContext()) {
1266 Diag(Loc, DiagID: diag::err_pragma_expected_file_scope) << "optimize";
1267 return;
1268 }
1269
1270 MSPragmaOptimizeIsOn = IsOn;
1271}
1272
1273void Sema::ActOnPragmaMSFunction(
1274 SourceLocation Loc, const llvm::SmallVectorImpl<StringRef> &NoBuiltins) {
1275 if (!CurContext->getRedeclContext()->isFileContext()) {
1276 Diag(Loc, DiagID: diag::err_pragma_expected_file_scope) << "function";
1277 return;
1278 }
1279
1280 MSFunctionNoBuiltins.insert_range(R: NoBuiltins);
1281}
1282
1283void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
1284 // In the future, check other pragmas if they're implemented (e.g. pragma
1285 // optimize 0 will probably map to this functionality too).
1286 if(OptimizeOffPragmaLocation.isValid())
1287 AddOptnoneAttributeIfNoConflicts(FD, Loc: OptimizeOffPragmaLocation);
1288}
1289
1290void Sema::AddSectionMSAllocText(FunctionDecl *FD) {
1291 if (!FD->getIdentifier())
1292 return;
1293
1294 StringRef Name = FD->getName();
1295 auto It = FunctionToSectionMap.find(Key: Name);
1296 if (It != FunctionToSectionMap.end()) {
1297 StringRef Section;
1298 SourceLocation Loc;
1299 std::tie(args&: Section, args&: Loc) = It->second;
1300
1301 if (!FD->hasAttr<SectionAttr>())
1302 FD->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: Section));
1303 }
1304}
1305
1306void Sema::ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD) {
1307 // Don't modify the function attributes if it's "on". "on" resets the
1308 // optimizations to the ones listed on the command line
1309 if (!MSPragmaOptimizeIsOn)
1310 AddOptnoneAttributeIfNoConflicts(FD, Loc: FD->getBeginLoc());
1311}
1312
1313void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
1314 SourceLocation Loc) {
1315 // Don't add a conflicting attribute. No diagnostic is needed.
1316 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
1317 return;
1318
1319 // Add attributes only if required. Optnone requires noinline as well, but if
1320 // either is already present then don't bother adding them.
1321 if (!FD->hasAttr<OptimizeNoneAttr>())
1322 FD->addAttr(A: OptimizeNoneAttr::CreateImplicit(Ctx&: Context, Range: Loc));
1323 if (!FD->hasAttr<NoInlineAttr>())
1324 FD->addAttr(A: NoInlineAttr::CreateImplicit(Ctx&: Context, Range: Loc));
1325}
1326
1327void Sema::AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD) {
1328 if (FD->isDeleted() || FD->isDefaulted())
1329 return;
1330 SmallVector<StringRef> V(MSFunctionNoBuiltins.begin(),
1331 MSFunctionNoBuiltins.end());
1332 if (!MSFunctionNoBuiltins.empty())
1333 FD->addAttr(A: NoBuiltinAttr::CreateImplicit(Ctx&: Context, BuiltinNames: V.data(), BuiltinNamesSize: V.size()));
1334}
1335
1336NamedDecl *Sema::lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
1337 SourceLocation NameLoc,
1338 Scope *curScope) {
1339 LookupResult Result(*this, IdentId, NameLoc, LookupOrdinaryName);
1340 LookupName(R&: Result, S: curScope);
1341 if (!getLangOpts().CPlusPlus)
1342 return Result.getAsSingle<NamedDecl>();
1343 for (NamedDecl *D : Result) {
1344 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1345 if (FD->isExternC())
1346 return D;
1347 if (isa<VarDecl>(Val: D))
1348 return D;
1349 }
1350 return nullptr;
1351}
1352
1353void Sema::ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation NameLoc,
1354 Scope *curScope) {
1355 if (!CurContext->getRedeclContext()->isFileContext()) {
1356 Diag(Loc: NameLoc, DiagID: diag::err_pragma_expected_file_scope) << "export";
1357 return;
1358 }
1359
1360 PendingPragmaInfo Info;
1361 Info.NameLoc = NameLoc;
1362 Info.Used = false;
1363
1364 NamedDecl *PrevDecl =
1365 lookupExternCFunctionOrVariable(IdentId, NameLoc, curScope);
1366 if (!PrevDecl) {
1367 PendingExportedNames[IdentId] = Info;
1368 return;
1369 }
1370
1371 if (auto *FD = dyn_cast<FunctionDecl>(Val: PrevDecl->getCanonicalDecl())) {
1372 if (!FD->hasExternalFormalLinkage()) {
1373 Diag(Loc: NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << PrevDecl;
1374 return;
1375 }
1376 if (FD->hasBody()) {
1377 Diag(Loc: NameLoc, DiagID: diag::warn_pragma_not_applied_to_defined_symbol)
1378 << "export";
1379 return;
1380 }
1381 } else if (auto *VD = dyn_cast<VarDecl>(Val: PrevDecl->getCanonicalDecl())) {
1382 if (!VD->hasExternalFormalLinkage()) {
1383 Diag(Loc: NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << PrevDecl;
1384 return;
1385 }
1386 if (VD->hasDefinition() == VarDecl::Definition) {
1387 Diag(Loc: NameLoc, DiagID: diag::warn_pragma_not_applied_to_defined_symbol)
1388 << "export";
1389 return;
1390 }
1391 }
1392 mergeVisibilityType(D: PrevDecl->getCanonicalDecl(), Loc: NameLoc,
1393 Type: VisibilityAttr::Default);
1394}
1395
1396typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
1397enum : unsigned { NoVisibility = ~0U };
1398
1399void Sema::AddPushedVisibilityAttribute(Decl *D) {
1400 if (!VisContext)
1401 return;
1402
1403 NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
1404 if (ND && ND->getExplicitVisibility(kind: NamedDecl::VisibilityForValue))
1405 return;
1406
1407 VisStack *Stack = static_cast<VisStack*>(VisContext);
1408 unsigned rawType = Stack->back().first;
1409 if (rawType == NoVisibility) return;
1410
1411 VisibilityAttr::VisibilityType type
1412 = (VisibilityAttr::VisibilityType) rawType;
1413 SourceLocation loc = Stack->back().second;
1414
1415 D->addAttr(A: VisibilityAttr::CreateImplicit(Ctx&: Context, Visibility: type, Range: loc));
1416}
1417
1418void Sema::FreeVisContext() {
1419 delete static_cast<VisStack*>(VisContext);
1420 VisContext = nullptr;
1421}
1422
1423static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
1424 // Put visibility on stack.
1425 if (!S.VisContext)
1426 S.VisContext = new VisStack;
1427
1428 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
1429 Stack->push_back(x: std::make_pair(x&: type, y&: loc));
1430}
1431
1432void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
1433 SourceLocation PragmaLoc) {
1434 if (VisType) {
1435 // Compute visibility to use.
1436 VisibilityAttr::VisibilityType T;
1437 if (!VisibilityAttr::ConvertStrToVisibilityType(Val: VisType->getName(), Out&: T)) {
1438 Diag(Loc: PragmaLoc, DiagID: diag::warn_attribute_unknown_visibility) << VisType;
1439 return;
1440 }
1441 PushPragmaVisibility(S&: *this, type: T, loc: PragmaLoc);
1442 } else {
1443 PopPragmaVisibility(IsNamespaceEnd: false, EndLoc: PragmaLoc);
1444 }
1445}
1446
1447void Sema::ActOnPragmaFPContract(SourceLocation Loc,
1448 LangOptions::FPModeKind FPC) {
1449 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1450 switch (FPC) {
1451 case LangOptions::FPM_On:
1452 NewFPFeatures.setAllowFPContractWithinStatement();
1453 break;
1454 case LangOptions::FPM_Fast:
1455 case LangOptions::FPM_FastHonorPragmas:
1456 NewFPFeatures.setAllowFPContractAcrossStatement();
1457 break;
1458 case LangOptions::FPM_Off:
1459 NewFPFeatures.setDisallowFPContract();
1460 break;
1461 }
1462 FpPragmaStack.Act(PragmaLocation: Loc, Action: Sema::PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1463 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1464}
1465
1466void Sema::ActOnPragmaFPValueChangingOption(SourceLocation Loc,
1467 PragmaFPKind Kind, bool IsEnabled) {
1468 if (IsEnabled) {
1469 // For value unsafe context, combining this pragma with eval method
1470 // setting is not recommended. See comment in function FixupInvocation#506.
1471 int Reason = -1;
1472 if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)
1473 // Eval method set using the option 'ffp-eval-method'.
1474 Reason = 1;
1475 if (PP.getLastFPEvalPragmaLocation().isValid())
1476 // Eval method set using the '#pragma clang fp eval_method'.
1477 // We could have both an option and a pragma used to the set the eval
1478 // method. The pragma overrides the option in the command line. The Reason
1479 // of the diagnostic is overriden too.
1480 Reason = 0;
1481 if (Reason != -1)
1482 Diag(Loc, DiagID: diag::err_setting_eval_method_used_in_unsafe_context)
1483 << Reason << (Kind == PFK_Reassociate ? 4 : 5);
1484 }
1485
1486 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1487 switch (Kind) {
1488 case PFK_Reassociate:
1489 NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
1490 break;
1491 case PFK_Reciprocal:
1492 NewFPFeatures.setAllowReciprocalOverride(IsEnabled);
1493 break;
1494 default:
1495 llvm_unreachable("unhandled value changing pragma fp");
1496 }
1497
1498 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1499 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1500}
1501
1502void Sema::ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode FPR) {
1503 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1504 NewFPFeatures.setConstRoundingModeOverride(FPR);
1505 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1506 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1507}
1508
1509void Sema::setExceptionMode(SourceLocation Loc,
1510 LangOptions::FPExceptionModeKind FPE) {
1511 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1512 NewFPFeatures.setSpecifiedExceptionModeOverride(FPE);
1513 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1514 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1515}
1516
1517void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
1518 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1519 if (IsEnabled) {
1520 // Verify Microsoft restriction:
1521 // You can't enable fenv_access unless precise semantics are enabled.
1522 // Precise semantics can be enabled either by the float_control
1523 // pragma, or by using the /fp:precise or /fp:strict compiler options
1524 if (!isPreciseFPEnabled())
1525 Diag(Loc, DiagID: diag::err_pragma_fenv_requires_precise);
1526 }
1527 NewFPFeatures.setAllowFEnvAccessOverride(IsEnabled);
1528 NewFPFeatures.setRoundingMathOverride(IsEnabled);
1529 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1530 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1531}
1532
1533void Sema::ActOnPragmaCXLimitedRange(SourceLocation Loc,
1534 LangOptions::ComplexRangeKind Range) {
1535 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1536 NewFPFeatures.setComplexRangeOverride(Range);
1537 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1538 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1539}
1540
1541void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
1542 LangOptions::FPExceptionModeKind FPE) {
1543 setExceptionMode(Loc, FPE);
1544}
1545
1546void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1547 SourceLocation Loc) {
1548 // Visibility calculations will consider the namespace's visibility.
1549 // Here we just want to note that we're in a visibility context
1550 // which overrides any enclosing #pragma context, but doesn't itself
1551 // contribute visibility.
1552 PushPragmaVisibility(S&: *this, type: NoVisibility, loc: Loc);
1553}
1554
1555void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1556 if (!VisContext) {
1557 Diag(Loc: EndLoc, DiagID: diag::err_pragma_pop_visibility_mismatch);
1558 return;
1559 }
1560
1561 // Pop visibility from stack
1562 VisStack *Stack = static_cast<VisStack*>(VisContext);
1563
1564 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1565 bool StartsWithPragma = Back->first != NoVisibility;
1566 if (StartsWithPragma && IsNamespaceEnd) {
1567 Diag(Loc: Back->second, DiagID: diag::err_pragma_push_visibility_mismatch);
1568 Diag(Loc: EndLoc, DiagID: diag::note_surrounding_namespace_ends_here);
1569
1570 // For better error recovery, eat all pushes inside the namespace.
1571 do {
1572 Stack->pop_back();
1573 Back = &Stack->back();
1574 StartsWithPragma = Back->first != NoVisibility;
1575 } while (StartsWithPragma);
1576 } else if (!StartsWithPragma && !IsNamespaceEnd) {
1577 Diag(Loc: EndLoc, DiagID: diag::err_pragma_pop_visibility_mismatch);
1578 Diag(Loc: Back->second, DiagID: diag::note_surrounding_namespace_starts_here);
1579 return;
1580 }
1581
1582 Stack->pop_back();
1583 // To simplify the implementation, never keep around an empty stack.
1584 if (Stack->empty())
1585 FreeVisContext();
1586}
1587
1588template <typename Ty>
1589static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,
1590 const ParsedAttr &A,
1591 bool SkipArgCountCheck) {
1592 // Several attributes carry different semantics than the parsing requires, so
1593 // those are opted out of the common argument checks.
1594 //
1595 // We also bail on unknown and ignored attributes because those are handled
1596 // as part of the target-specific handling logic.
1597 if (A.getKind() == ParsedAttr::UnknownAttribute)
1598 return false;
1599 // Check whether the attribute requires specific language extensions to be
1600 // enabled.
1601 if (!A.diagnoseLangOpts(S))
1602 return true;
1603 // Check whether the attribute appertains to the given subject.
1604 if (!A.diagnoseAppertainsTo(S, Node))
1605 return true;
1606 // Check whether the attribute is mutually exclusive with other attributes
1607 // that have already been applied to the declaration.
1608 if (!A.diagnoseMutualExclusion(S, Node))
1609 return true;
1610 // Check whether the attribute exists in the target architecture.
1611 if (S.CheckAttrTarget(CurrAttr: A))
1612 return true;
1613
1614 if (A.hasCustomParsing())
1615 return false;
1616
1617 if (!SkipArgCountCheck) {
1618 if (A.getMinArgs() == A.getMaxArgs()) {
1619 // If there are no optional arguments, then checking for the argument
1620 // count is trivial.
1621 if (!A.checkExactlyNumArgs(S, Num: A.getMinArgs()))
1622 return true;
1623 } else {
1624 // There are optional arguments, so checking is slightly more involved.
1625 if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, Num: A.getMinArgs()))
1626 return true;
1627 else if (!A.hasVariadicArg() && A.getMaxArgs() &&
1628 !A.checkAtMostNumArgs(S, Num: A.getMaxArgs()))
1629 return true;
1630 }
1631 }
1632
1633 return false;
1634}
1635
1636bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
1637 bool SkipArgCountCheck) {
1638 return ::checkCommonAttributeFeatures(S&: *this, Node: D, A, SkipArgCountCheck);
1639}
1640bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
1641 bool SkipArgCountCheck) {
1642 return ::checkCommonAttributeFeatures(S&: *this, Node: S, A, SkipArgCountCheck);
1643}
1644