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