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/Expr.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/SemaInternal.h"
21 using namespace clang;
22 
23 //===----------------------------------------------------------------------===//
24 // Pragma 'pack' and 'options align'
25 //===----------------------------------------------------------------------===//
26 
27 Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
28                                                        StringRef SlotLabel,
29                                                        bool ShouldAct)
30     : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
31   if (ShouldAct) {
32     S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
33     S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
34     S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
35     S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
36     S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
37   }
38 }
39 
40 Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
41   if (ShouldAct) {
42     S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
43     S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
44     S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
45     S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
46     S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
47   }
48 }
49 
50 void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
51   AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
52   AlignPackInfo::Mode M = InfoVal.getAlignMode();
53   bool IsPackSet = InfoVal.IsPackSet();
54   bool IsXLPragma = getLangOpts().XLPragmaPack;
55 
56   // If we are not under mac68k/natural alignment mode and also there is no pack
57   // value, we don't need any attributes.
58   if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)
59     return;
60 
61   if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {
62     RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
63   } else if (IsPackSet) {
64     // Check to see if we need a max field alignment attribute.
65     RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
66         Context, InfoVal.getPackNumber() * 8));
67   }
68 
69   if (IsXLPragma && M == AlignPackInfo::Natural)
70     RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
71 
72   if (AlignPackIncludeStack.empty())
73     return;
74   // The #pragma align/pack affected a record in an included file, so Clang
75   // should warn when that pragma was written in a file that included the
76   // included file.
77   for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack)) {
78     if (AlignPackedInclude.CurrentPragmaLocation !=
79         AlignPackStack.CurrentPragmaLocation)
80       break;
81     if (AlignPackedInclude.HasNonDefaultValue)
82       AlignPackedInclude.ShouldWarnOnInclude = true;
83   }
84 }
85 
86 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
87   if (MSStructPragmaOn)
88     RD->addAttr(MSStructAttr::CreateImplicit(Context));
89 
90   // FIXME: We should merge AddAlignmentAttributesForRecord with
91   // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
92   // all active pragmas and applies them as attributes to class definitions.
93   if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
94     RD->addAttr(MSVtorDispAttr::CreateImplicit(
95         Context, unsigned(VtorDispStack.CurrentValue)));
96 }
97 
98 template <typename Attribute>
99 static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
100                                                      CXXRecordDecl *Record) {
101   if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
102     return;
103 
104   for (Decl *Redecl : Record->redecls())
105     Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
106 }
107 
108 void Sema::inferGslPointerAttribute(NamedDecl *ND,
109                                     CXXRecordDecl *UnderlyingRecord) {
110   if (!UnderlyingRecord)
111     return;
112 
113   const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
114   if (!Parent)
115     return;
116 
117   static llvm::StringSet<> Containers{
118       "array",
119       "basic_string",
120       "deque",
121       "forward_list",
122       "vector",
123       "list",
124       "map",
125       "multiset",
126       "multimap",
127       "priority_queue",
128       "queue",
129       "set",
130       "stack",
131       "unordered_set",
132       "unordered_map",
133       "unordered_multiset",
134       "unordered_multimap",
135   };
136 
137   static llvm::StringSet<> Iterators{"iterator", "const_iterator",
138                                      "reverse_iterator",
139                                      "const_reverse_iterator"};
140 
141   if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
142       Containers.count(Parent->getName()))
143     addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
144                                                           UnderlyingRecord);
145 }
146 
147 void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
148 
149   QualType Canonical = TD->getUnderlyingType().getCanonicalType();
150 
151   CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
152   if (!RD) {
153     if (auto *TST =
154             dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
155 
156       RD = dyn_cast_or_null<CXXRecordDecl>(
157           TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
158     }
159   }
160 
161   inferGslPointerAttribute(TD, RD);
162 }
163 
164 void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
165   static llvm::StringSet<> StdOwners{
166       "any",
167       "array",
168       "basic_regex",
169       "basic_string",
170       "deque",
171       "forward_list",
172       "vector",
173       "list",
174       "map",
175       "multiset",
176       "multimap",
177       "optional",
178       "priority_queue",
179       "queue",
180       "set",
181       "stack",
182       "unique_ptr",
183       "unordered_set",
184       "unordered_map",
185       "unordered_multiset",
186       "unordered_multimap",
187       "variant",
188   };
189   static llvm::StringSet<> StdPointers{
190       "basic_string_view",
191       "reference_wrapper",
192       "regex_iterator",
193   };
194 
195   if (!Record->getIdentifier())
196     return;
197 
198   // Handle classes that directly appear in std namespace.
199   if (Record->isInStdNamespace()) {
200     if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
201       return;
202 
203     if (StdOwners.count(Record->getName()))
204       addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
205     else if (StdPointers.count(Record->getName()))
206       addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
207 
208     return;
209   }
210 
211   // Handle nested classes that could be a gsl::Pointer.
212   inferGslPointerAttribute(Record, Record);
213 }
214 
215 void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
216                                    SourceLocation PragmaLoc) {
217   PragmaMsStackAction Action = Sema::PSK_Reset;
218   AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
219 
220   switch (Kind) {
221     // For most of the platforms we support, native and natural are the same.
222     // With XL, native is the same as power, natural means something else.
223     //
224     // FIXME: This is not true on Darwin/PPC.
225   case POAK_Native:
226   case POAK_Power:
227     Action = Sema::PSK_Push_Set;
228     break;
229   case POAK_Natural:
230     Action = Sema::PSK_Push_Set;
231     ModeVal = AlignPackInfo::Natural;
232     break;
233 
234     // Note that '#pragma options align=packed' is not equivalent to attribute
235     // packed, it has a different precedence relative to attribute aligned.
236   case POAK_Packed:
237     Action = Sema::PSK_Push_Set;
238     ModeVal = AlignPackInfo::Packed;
239     break;
240 
241   case POAK_Mac68k:
242     // Check if the target supports this.
243     if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
244       Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
245       return;
246     }
247     Action = Sema::PSK_Push_Set;
248     ModeVal = AlignPackInfo::Mac68k;
249     break;
250   case POAK_Reset:
251     // Reset just pops the top of the stack, or resets the current alignment to
252     // default.
253     Action = Sema::PSK_Pop;
254     if (AlignPackStack.Stack.empty()) {
255       if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
256           AlignPackStack.CurrentValue.IsPackAttr()) {
257         Action = Sema::PSK_Reset;
258       } else {
259         Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
260             << "stack empty";
261         return;
262       }
263     }
264     break;
265   }
266 
267   AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
268 
269   AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
270 }
271 
272 void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
273                                    PragmaClangSectionAction Action,
274                                    PragmaClangSectionKind SecKind,
275                                    StringRef SecName) {
276   PragmaClangSection *CSec;
277   int SectionFlags = ASTContext::PSF_Read;
278   switch (SecKind) {
279     case PragmaClangSectionKind::PCSK_BSS:
280       CSec = &PragmaClangBSSSection;
281       SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
282       break;
283     case PragmaClangSectionKind::PCSK_Data:
284       CSec = &PragmaClangDataSection;
285       SectionFlags |= ASTContext::PSF_Write;
286       break;
287     case PragmaClangSectionKind::PCSK_Rodata:
288       CSec = &PragmaClangRodataSection;
289       break;
290     case PragmaClangSectionKind::PCSK_Relro:
291       CSec = &PragmaClangRelroSection;
292       break;
293     case PragmaClangSectionKind::PCSK_Text:
294       CSec = &PragmaClangTextSection;
295       SectionFlags |= ASTContext::PSF_Execute;
296       break;
297     default:
298       llvm_unreachable("invalid clang section kind");
299   }
300 
301   if (Action == PragmaClangSectionAction::PCSA_Clear) {
302     CSec->Valid = false;
303     return;
304   }
305 
306   if (llvm::Error E = isValidSectionSpecifier(SecName)) {
307     Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
308         << toString(std::move(E));
309     CSec->Valid = false;
310     return;
311   }
312 
313   if (UnifySection(SecName, SectionFlags, PragmaLoc))
314     return;
315 
316   CSec->Valid = true;
317   CSec->SectionName = std::string(SecName);
318   CSec->PragmaLocation = PragmaLoc;
319 }
320 
321 void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
322                            StringRef SlotLabel, Expr *alignment) {
323   bool IsXLPragma = getLangOpts().XLPragmaPack;
324   // XL pragma pack does not support identifier syntax.
325   if (IsXLPragma && !SlotLabel.empty()) {
326     Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
327     return;
328   }
329 
330   const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
331   Expr *Alignment = static_cast<Expr *>(alignment);
332 
333   // If specified then alignment must be a "small" power of two.
334   unsigned AlignmentVal = 0;
335   AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
336 
337   if (Alignment) {
338     Optional<llvm::APSInt> Val;
339     Val = Alignment->getIntegerConstantExpr(Context);
340 
341     // pack(0) is like pack(), which just works out since that is what
342     // we use 0 for in PackAttr.
343     if (Alignment->isTypeDependent() || !Val ||
344         !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
345       Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
346       return; // Ignore
347     }
348 
349     if (IsXLPragma && *Val == 0) {
350       // pack(0) does not work out with XL.
351       Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
352       return; // Ignore
353     }
354 
355     AlignmentVal = (unsigned)Val->getZExtValue();
356   }
357 
358   if (Action == Sema::PSK_Show) {
359     // Show the current alignment, making sure to show the right value
360     // for the default.
361     // FIXME: This should come from the target.
362     AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
363     if (ModeVal == AlignPackInfo::Mac68k &&
364         (IsXLPragma || CurVal.IsAlignAttr()))
365       Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
366     else
367       Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
368   }
369 
370   // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
371   // "#pragma pack(pop, identifier, n) is undefined"
372   if (Action & Sema::PSK_Pop) {
373     if (Alignment && !SlotLabel.empty())
374       Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
375     if (AlignPackStack.Stack.empty()) {
376       assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
377              "Empty pack stack can only be at Native alignment mode.");
378       Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
379     }
380   }
381 
382   AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
383 
384   AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
385 }
386 
387 void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
388                                              SourceLocation IncludeLoc) {
389   if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
390     SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
391     // Warn about non-default alignment at #includes (without redundant
392     // warnings for the same directive in nested includes).
393     // The warning is delayed until the end of the file to avoid warnings
394     // for files that don't have any records that are affected by the modified
395     // alignment.
396     bool HasNonDefaultValue =
397         AlignPackStack.hasValue() &&
398         (AlignPackIncludeStack.empty() ||
399          AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
400     AlignPackIncludeStack.push_back(
401         {AlignPackStack.CurrentValue,
402          AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
403          HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
404     return;
405   }
406 
407   assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
408          "invalid kind");
409   AlignPackIncludeState PrevAlignPackState =
410       AlignPackIncludeStack.pop_back_val();
411   // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
412   // information, diagnostics below might not be accurate if we have mixed
413   // pragmas.
414   if (PrevAlignPackState.ShouldWarnOnInclude) {
415     // Emit the delayed non-default alignment at #include warning.
416     Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
417     Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
418   }
419   // Warn about modified alignment after #includes.
420   if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
421     Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
422     Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
423   }
424 }
425 
426 void Sema::DiagnoseUnterminatedPragmaAlignPack() {
427   if (AlignPackStack.Stack.empty())
428     return;
429   bool IsInnermost = true;
430 
431   // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
432   // information, diagnostics below might not be accurate if we have mixed
433   // pragmas.
434   for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {
435     Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
436     // The user might have already reset the alignment, so suggest replacing
437     // the reset with a pop.
438     if (IsInnermost &&
439         AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
440       auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
441                      diag::note_pragma_pack_pop_instead_reset);
442       SourceLocation FixItLoc =
443           Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,
444                                         tok::l_paren, SourceMgr, LangOpts,
445                                         /*SkipTrailing=*/false);
446       if (FixItLoc.isValid())
447         DB << FixItHint::CreateInsertion(FixItLoc, "pop");
448     }
449     IsInnermost = false;
450   }
451 }
452 
453 void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
454   MSStructPragmaOn = (Kind == PMSST_ON);
455 }
456 
457 void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
458                                 PragmaMSCommentKind Kind, StringRef Arg) {
459   auto *PCD = PragmaCommentDecl::Create(
460       Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
461   Context.getTranslationUnitDecl()->addDecl(PCD);
462   Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
463 }
464 
465 void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
466                                      StringRef Value) {
467   auto *PDMD = PragmaDetectMismatchDecl::Create(
468       Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
469   Context.getTranslationUnitDecl()->addDecl(PDMD);
470   Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
471 }
472 
473 void Sema::ActOnPragmaFPEvalMethod(SourceLocation Loc,
474                                    LangOptions::FPEvalMethodKind Value) {
475   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
476   switch (Value) {
477   default:
478     llvm_unreachable("invalid pragma eval_method kind");
479   case LangOptions::FEM_Source:
480     NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
481     break;
482   case LangOptions::FEM_Double:
483     NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
484     break;
485   case LangOptions::FEM_Extended:
486     NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
487     break;
488   }
489   if (getLangOpts().ApproxFunc)
490     Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
491   if (getLangOpts().AllowFPReassoc)
492     Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
493   if (getLangOpts().AllowRecip)
494     Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
495   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
496   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
497   PP.setCurrentFPEvalMethod(Loc, Value);
498 }
499 
500 void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
501                                    PragmaMsStackAction Action,
502                                    PragmaFloatControlKind Value) {
503   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
504   if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
505       !CurContext->getRedeclContext()->isFileContext()) {
506     // Push and pop can only occur at file or namespace scope, or within a
507     // language linkage declaration.
508     Diag(Loc, diag::err_pragma_fc_pp_scope);
509     return;
510   }
511   switch (Value) {
512   default:
513     llvm_unreachable("invalid pragma float_control kind");
514   case PFC_Precise:
515     NewFPFeatures.setFPPreciseEnabled(true);
516     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
517     if (PP.getCurrentFPEvalMethod() ==
518             LangOptions::FPEvalMethodKind::FEM_Indeterminable &&
519         PP.getLastFPEvalPragmaLocation().isValid())
520       // A preceding `pragma float_control(precise,off)` has changed
521       // the value of the evaluation method.
522       // Set it back to its old value.
523       PP.setCurrentFPEvalMethod(SourceLocation(), PP.getLastFPEvalMethod());
524     break;
525   case PFC_NoPrecise:
526     if (CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Strict)
527       Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
528     else if (CurFPFeatures.getAllowFEnvAccess())
529       Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
530     else
531       NewFPFeatures.setFPPreciseEnabled(false);
532     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
533     PP.setLastFPEvalMethod(PP.getCurrentFPEvalMethod());
534     // `AllowFPReassoc` or `AllowReciprocal` option is enabled.
535     PP.setCurrentFPEvalMethod(
536         Loc, LangOptions::FPEvalMethodKind::FEM_Indeterminable);
537     break;
538   case PFC_Except:
539     if (!isPreciseFPEnabled())
540       Diag(Loc, diag::err_pragma_fc_except_requires_precise);
541     else
542       NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
543     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
544     break;
545   case PFC_NoExcept:
546     NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Ignore);
547     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
548     break;
549   case PFC_Push:
550     FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
551     break;
552   case PFC_Pop:
553     if (FpPragmaStack.Stack.empty()) {
554       Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
555                                               << "stack empty";
556       return;
557     }
558     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
559     NewFPFeatures = FpPragmaStack.CurrentValue;
560     if (CurFPFeatures.getAllowFPReassociate() ||
561         CurFPFeatures.getAllowReciprocal())
562       // Since we are popping the pragma, we don't want to be passing
563       // a location here.
564       PP.setCurrentFPEvalMethod(SourceLocation(),
565                                 CurFPFeatures.getFPEvalMethod());
566     break;
567   }
568   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
569 }
570 
571 void Sema::ActOnPragmaMSPointersToMembers(
572     LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
573     SourceLocation PragmaLoc) {
574   MSPointerToMemberRepresentationMethod = RepresentationMethod;
575   ImplicitMSInheritanceAttrLoc = PragmaLoc;
576 }
577 
578 void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
579                                  SourceLocation PragmaLoc,
580                                  MSVtorDispMode Mode) {
581   if (Action & PSK_Pop && VtorDispStack.Stack.empty())
582     Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
583                                                   << "stack empty";
584   VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
585 }
586 
587 template <>
588 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
589                                                  PragmaMsStackAction Action,
590                                                  llvm::StringRef StackSlotLabel,
591                                                  AlignPackInfo Value) {
592   if (Action == PSK_Reset) {
593     CurrentValue = DefaultValue;
594     CurrentPragmaLocation = PragmaLocation;
595     return;
596   }
597   if (Action & PSK_Push)
598     Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
599                             PragmaLocation));
600   else if (Action & PSK_Pop) {
601     if (!StackSlotLabel.empty()) {
602       // If we've got a label, try to find it and jump there.
603       auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
604         return x.StackSlotLabel == StackSlotLabel;
605       });
606       // We found the label, so pop from there.
607       if (I != Stack.rend()) {
608         CurrentValue = I->Value;
609         CurrentPragmaLocation = I->PragmaLocation;
610         Stack.erase(std::prev(I.base()), Stack.end());
611       }
612     } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
613                CurrentValue.IsPackAttr()) {
614       // XL '#pragma align(reset)' would pop the stack until
615       // a current in effect pragma align is popped.
616       auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
617         return x.Value.IsAlignAttr();
618       });
619       // If we found pragma align so pop from there.
620       if (I != Stack.rend()) {
621         Stack.erase(std::prev(I.base()), Stack.end());
622         if (Stack.empty()) {
623           CurrentValue = DefaultValue;
624           CurrentPragmaLocation = PragmaLocation;
625         } else {
626           CurrentValue = Stack.back().Value;
627           CurrentPragmaLocation = Stack.back().PragmaLocation;
628           Stack.pop_back();
629         }
630       }
631     } else if (!Stack.empty()) {
632       // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
633       // over the baseline.
634       if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
635         return;
636 
637       // We don't have a label, just pop the last entry.
638       CurrentValue = Stack.back().Value;
639       CurrentPragmaLocation = Stack.back().PragmaLocation;
640       Stack.pop_back();
641     }
642   }
643   if (Action & PSK_Set) {
644     CurrentValue = Value;
645     CurrentPragmaLocation = PragmaLocation;
646   }
647 }
648 
649 bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
650                         NamedDecl *Decl) {
651   SourceLocation PragmaLocation;
652   if (auto A = Decl->getAttr<SectionAttr>())
653     if (A->isImplicit())
654       PragmaLocation = A->getLocation();
655   auto SectionIt = Context.SectionInfos.find(SectionName);
656   if (SectionIt == Context.SectionInfos.end()) {
657     Context.SectionInfos[SectionName] =
658         ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
659     return false;
660   }
661   // A pre-declared section takes precedence w/o diagnostic.
662   const auto &Section = SectionIt->second;
663   if (Section.SectionFlags == SectionFlags ||
664       ((SectionFlags & ASTContext::PSF_Implicit) &&
665        !(Section.SectionFlags & ASTContext::PSF_Implicit)))
666     return false;
667   Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
668   if (Section.Decl)
669     Diag(Section.Decl->getLocation(), diag::note_declared_at)
670         << Section.Decl->getName();
671   if (PragmaLocation.isValid())
672     Diag(PragmaLocation, diag::note_pragma_entered_here);
673   if (Section.PragmaSectionLocation.isValid())
674     Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
675   return true;
676 }
677 
678 bool Sema::UnifySection(StringRef SectionName,
679                         int SectionFlags,
680                         SourceLocation PragmaSectionLocation) {
681   auto SectionIt = Context.SectionInfos.find(SectionName);
682   if (SectionIt != Context.SectionInfos.end()) {
683     const auto &Section = SectionIt->second;
684     if (Section.SectionFlags == SectionFlags)
685       return false;
686     if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
687       Diag(PragmaSectionLocation, diag::err_section_conflict)
688           << "this" << Section;
689       if (Section.Decl)
690         Diag(Section.Decl->getLocation(), diag::note_declared_at)
691             << Section.Decl->getName();
692       if (Section.PragmaSectionLocation.isValid())
693         Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
694       return true;
695     }
696   }
697   Context.SectionInfos[SectionName] =
698       ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
699   return false;
700 }
701 
702 /// Called on well formed \#pragma bss_seg().
703 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
704                             PragmaMsStackAction Action,
705                             llvm::StringRef StackSlotLabel,
706                             StringLiteral *SegmentName,
707                             llvm::StringRef PragmaName) {
708   PragmaStack<StringLiteral *> *Stack =
709     llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
710         .Case("data_seg", &DataSegStack)
711         .Case("bss_seg", &BSSSegStack)
712         .Case("const_seg", &ConstSegStack)
713         .Case("code_seg", &CodeSegStack);
714   if (Action & PSK_Pop && Stack->Stack.empty())
715     Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
716         << "stack empty";
717   if (SegmentName) {
718     if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
719       return;
720 
721     if (SegmentName->getString() == ".drectve" &&
722         Context.getTargetInfo().getCXXABI().isMicrosoft())
723       Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
724   }
725 
726   Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
727 }
728 
729 /// Called on well formed \#pragma bss_seg().
730 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
731                                 int SectionFlags, StringLiteral *SegmentName) {
732   UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
733 }
734 
735 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
736                                 StringLiteral *SegmentName) {
737   // There's no stack to maintain, so we just have a current section.  When we
738   // see the default section, reset our current section back to null so we stop
739   // tacking on unnecessary attributes.
740   CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
741   CurInitSegLoc = PragmaLocation;
742 }
743 
744 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
745                              SourceLocation PragmaLoc) {
746 
747   IdentifierInfo *Name = IdTok.getIdentifierInfo();
748   LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
749   LookupParsedName(Lookup, curScope, nullptr, true);
750 
751   if (Lookup.empty()) {
752     Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
753       << Name << SourceRange(IdTok.getLocation());
754     return;
755   }
756 
757   VarDecl *VD = Lookup.getAsSingle<VarDecl>();
758   if (!VD) {
759     Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
760       << Name << SourceRange(IdTok.getLocation());
761     return;
762   }
763 
764   // Warn if this was used before being marked unused.
765   if (VD->isUsed())
766     Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
767 
768   VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
769                                          AttributeCommonInfo::AS_Pragma,
770                                          UnusedAttr::GNU_unused));
771 }
772 
773 void Sema::AddCFAuditedAttribute(Decl *D) {
774   IdentifierInfo *Ident;
775   SourceLocation Loc;
776   std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
777   if (!Loc.isValid()) return;
778 
779   // Don't add a redundant or conflicting attribute.
780   if (D->hasAttr<CFAuditedTransferAttr>() ||
781       D->hasAttr<CFUnknownTransferAttr>())
782     return;
783 
784   AttributeCommonInfo Info(Ident, SourceRange(Loc),
785                            AttributeCommonInfo::AS_Pragma);
786   D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
787 }
788 
789 namespace {
790 
791 Optional<attr::SubjectMatchRule>
792 getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
793   using namespace attr;
794   switch (Rule) {
795   default:
796     return None;
797 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
798 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
799   case Value:                                                                  \
800     return Parent;
801 #include "clang/Basic/AttrSubMatchRulesList.inc"
802   }
803 }
804 
805 bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
806   using namespace attr;
807   switch (Rule) {
808   default:
809     return false;
810 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
811 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
812   case Value:                                                                  \
813     return IsNegated;
814 #include "clang/Basic/AttrSubMatchRulesList.inc"
815   }
816 }
817 
818 CharSourceRange replacementRangeForListElement(const Sema &S,
819                                                SourceRange Range) {
820   // Make sure that the ',' is removed as well.
821   SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
822       Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
823       /*SkipTrailingWhitespaceAndNewLine=*/false);
824   if (AfterCommaLoc.isValid())
825     return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
826   else
827     return CharSourceRange::getTokenRange(Range);
828 }
829 
830 std::string
831 attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
832   std::string Result;
833   llvm::raw_string_ostream OS(Result);
834   for (const auto &I : llvm::enumerate(Rules)) {
835     if (I.index())
836       OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
837     OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
838   }
839   return Result;
840 }
841 
842 } // end anonymous namespace
843 
844 void Sema::ActOnPragmaAttributeAttribute(
845     ParsedAttr &Attribute, SourceLocation PragmaLoc,
846     attr::ParsedSubjectMatchRuleSet Rules) {
847   Attribute.setIsPragmaClangAttribute();
848   SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
849   // Gather the subject match rules that are supported by the attribute.
850   SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
851       StrictSubjectMatchRuleSet;
852   Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
853 
854   // Figure out which subject matching rules are valid.
855   if (StrictSubjectMatchRuleSet.empty()) {
856     // Check for contradicting match rules. Contradicting match rules are
857     // either:
858     //  - a top-level rule and one of its sub-rules. E.g. variable and
859     //    variable(is_parameter).
860     //  - a sub-rule and a sibling that's negated. E.g.
861     //    variable(is_thread_local) and variable(unless(is_parameter))
862     llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
863         RulesToFirstSpecifiedNegatedSubRule;
864     for (const auto &Rule : Rules) {
865       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
866       Optional<attr::SubjectMatchRule> ParentRule =
867           getParentAttrMatcherRule(MatchRule);
868       if (!ParentRule)
869         continue;
870       auto It = Rules.find(*ParentRule);
871       if (It != Rules.end()) {
872         // A sub-rule contradicts a parent rule.
873         Diag(Rule.second.getBegin(),
874              diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
875             << attr::getSubjectMatchRuleSpelling(MatchRule)
876             << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
877             << FixItHint::CreateRemoval(
878                    replacementRangeForListElement(*this, Rule.second));
879         // Keep going without removing this rule as it won't change the set of
880         // declarations that receive the attribute.
881         continue;
882       }
883       if (isNegatedAttrMatcherSubRule(MatchRule))
884         RulesToFirstSpecifiedNegatedSubRule.insert(
885             std::make_pair(*ParentRule, Rule));
886     }
887     bool IgnoreNegatedSubRules = false;
888     for (const auto &Rule : Rules) {
889       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
890       Optional<attr::SubjectMatchRule> ParentRule =
891           getParentAttrMatcherRule(MatchRule);
892       if (!ParentRule)
893         continue;
894       auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
895       if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
896           It->second != Rule) {
897         // Negated sub-rule contradicts another sub-rule.
898         Diag(
899             It->second.second.getBegin(),
900             diag::
901                 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
902             << attr::getSubjectMatchRuleSpelling(
903                    attr::SubjectMatchRule(It->second.first))
904             << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
905             << FixItHint::CreateRemoval(
906                    replacementRangeForListElement(*this, It->second.second));
907         // Keep going but ignore all of the negated sub-rules.
908         IgnoreNegatedSubRules = true;
909         RulesToFirstSpecifiedNegatedSubRule.erase(It);
910       }
911     }
912 
913     if (!IgnoreNegatedSubRules) {
914       for (const auto &Rule : Rules)
915         SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
916     } else {
917       for (const auto &Rule : Rules) {
918         if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
919           SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
920       }
921     }
922     Rules.clear();
923   } else {
924     // Each rule in Rules must be a strict subset of the attribute's
925     // SubjectMatch rules.  I.e. we're allowed to use
926     // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
927     // but should not allow `apply_to=variables` on an attribute which has
928     // `SubjectList<[GlobalVar]>`.
929     for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
930       // First, check for exact match.
931       if (Rules.erase(StrictRule.first)) {
932         // Add the rule to the set of attribute receivers only if it's supported
933         // in the current language mode.
934         if (StrictRule.second)
935           SubjectMatchRules.push_back(StrictRule.first);
936       }
937     }
938     // Check remaining rules for subset matches.
939     auto RulesToCheck = Rules;
940     for (const auto &Rule : RulesToCheck) {
941       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
942       if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
943         if (llvm::any_of(StrictSubjectMatchRuleSet,
944                          [ParentRule](const auto &StrictRule) {
945                            return StrictRule.first == *ParentRule &&
946                                   StrictRule.second; // IsEnabled
947                          })) {
948           SubjectMatchRules.push_back(MatchRule);
949           Rules.erase(MatchRule);
950         }
951       }
952     }
953   }
954 
955   if (!Rules.empty()) {
956     auto Diagnostic =
957         Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
958         << Attribute;
959     SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
960     for (const auto &Rule : Rules) {
961       ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
962       Diagnostic << FixItHint::CreateRemoval(
963           replacementRangeForListElement(*this, Rule.second));
964     }
965     Diagnostic << attrMatcherRuleListToString(ExtraRules);
966   }
967 
968   if (PragmaAttributeStack.empty()) {
969     Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
970     return;
971   }
972 
973   PragmaAttributeStack.back().Entries.push_back(
974       {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
975 }
976 
977 void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
978                                          const IdentifierInfo *Namespace) {
979   PragmaAttributeStack.emplace_back();
980   PragmaAttributeStack.back().Loc = PragmaLoc;
981   PragmaAttributeStack.back().Namespace = Namespace;
982 }
983 
984 void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
985                                    const IdentifierInfo *Namespace) {
986   if (PragmaAttributeStack.empty()) {
987     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
988     return;
989   }
990 
991   // Dig back through the stack trying to find the most recently pushed group
992   // that in Namespace. Note that this works fine if no namespace is present,
993   // think of push/pops without namespaces as having an implicit "nullptr"
994   // namespace.
995   for (size_t Index = PragmaAttributeStack.size(); Index;) {
996     --Index;
997     if (PragmaAttributeStack[Index].Namespace == Namespace) {
998       for (const PragmaAttributeEntry &Entry :
999            PragmaAttributeStack[Index].Entries) {
1000         if (!Entry.IsUsed) {
1001           assert(Entry.Attribute && "Expected an attribute");
1002           Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
1003               << *Entry.Attribute;
1004           Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
1005         }
1006       }
1007       PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
1008       return;
1009     }
1010   }
1011 
1012   if (Namespace)
1013     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
1014         << 0 << Namespace->getName();
1015   else
1016     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1017 }
1018 
1019 void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
1020   if (PragmaAttributeStack.empty())
1021     return;
1022   for (auto &Group : PragmaAttributeStack) {
1023     for (auto &Entry : Group.Entries) {
1024       ParsedAttr *Attribute = Entry.Attribute;
1025       assert(Attribute && "Expected an attribute");
1026       assert(Attribute->isPragmaClangAttribute() &&
1027              "expected #pragma clang attribute");
1028 
1029       // Ensure that the attribute can be applied to the given declaration.
1030       bool Applies = false;
1031       for (const auto &Rule : Entry.MatchRules) {
1032         if (Attribute->appliesToDecl(D, Rule)) {
1033           Applies = true;
1034           break;
1035         }
1036       }
1037       if (!Applies)
1038         continue;
1039       Entry.IsUsed = true;
1040       PragmaAttributeCurrentTargetDecl = D;
1041       ParsedAttributesView Attrs;
1042       Attrs.addAtEnd(Attribute);
1043       ProcessDeclAttributeList(S, D, Attrs);
1044       PragmaAttributeCurrentTargetDecl = nullptr;
1045     }
1046   }
1047 }
1048 
1049 void Sema::PrintPragmaAttributeInstantiationPoint() {
1050   assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
1051   Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
1052                diag::note_pragma_attribute_applied_decl_here);
1053 }
1054 
1055 void Sema::DiagnoseUnterminatedPragmaAttribute() {
1056   if (PragmaAttributeStack.empty())
1057     return;
1058   Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
1059 }
1060 
1061 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
1062   if(On)
1063     OptimizeOffPragmaLocation = SourceLocation();
1064   else
1065     OptimizeOffPragmaLocation = PragmaLoc;
1066 }
1067 
1068 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
1069   // In the future, check other pragmas if they're implemented (e.g. pragma
1070   // optimize 0 will probably map to this functionality too).
1071   if(OptimizeOffPragmaLocation.isValid())
1072     AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
1073 }
1074 
1075 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
1076                                             SourceLocation Loc) {
1077   // Don't add a conflicting attribute. No diagnostic is needed.
1078   if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
1079     return;
1080 
1081   // Add attributes only if required. Optnone requires noinline as well, but if
1082   // either is already present then don't bother adding them.
1083   if (!FD->hasAttr<OptimizeNoneAttr>())
1084     FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
1085   if (!FD->hasAttr<NoInlineAttr>())
1086     FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
1087 }
1088 
1089 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
1090 enum : unsigned { NoVisibility = ~0U };
1091 
1092 void Sema::AddPushedVisibilityAttribute(Decl *D) {
1093   if (!VisContext)
1094     return;
1095 
1096   NamedDecl *ND = dyn_cast<NamedDecl>(D);
1097   if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
1098     return;
1099 
1100   VisStack *Stack = static_cast<VisStack*>(VisContext);
1101   unsigned rawType = Stack->back().first;
1102   if (rawType == NoVisibility) return;
1103 
1104   VisibilityAttr::VisibilityType type
1105     = (VisibilityAttr::VisibilityType) rawType;
1106   SourceLocation loc = Stack->back().second;
1107 
1108   D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
1109 }
1110 
1111 /// FreeVisContext - Deallocate and null out VisContext.
1112 void Sema::FreeVisContext() {
1113   delete static_cast<VisStack*>(VisContext);
1114   VisContext = nullptr;
1115 }
1116 
1117 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
1118   // Put visibility on stack.
1119   if (!S.VisContext)
1120     S.VisContext = new VisStack;
1121 
1122   VisStack *Stack = static_cast<VisStack*>(S.VisContext);
1123   Stack->push_back(std::make_pair(type, loc));
1124 }
1125 
1126 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
1127                                  SourceLocation PragmaLoc) {
1128   if (VisType) {
1129     // Compute visibility to use.
1130     VisibilityAttr::VisibilityType T;
1131     if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
1132       Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
1133       return;
1134     }
1135     PushPragmaVisibility(*this, T, PragmaLoc);
1136   } else {
1137     PopPragmaVisibility(false, PragmaLoc);
1138   }
1139 }
1140 
1141 void Sema::ActOnPragmaFPContract(SourceLocation Loc,
1142                                  LangOptions::FPModeKind FPC) {
1143   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1144   switch (FPC) {
1145   case LangOptions::FPM_On:
1146     NewFPFeatures.setAllowFPContractWithinStatement();
1147     break;
1148   case LangOptions::FPM_Fast:
1149     NewFPFeatures.setAllowFPContractAcrossStatement();
1150     break;
1151   case LangOptions::FPM_Off:
1152     NewFPFeatures.setDisallowFPContract();
1153     break;
1154   case LangOptions::FPM_FastHonorPragmas:
1155     llvm_unreachable("Should not happen");
1156   }
1157   FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
1158   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1159 }
1160 
1161 void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
1162   if (IsEnabled) {
1163     // For value unsafe context, combining this pragma with eval method
1164     // setting is not recommended. See comment in function FixupInvocation#506.
1165     int Reason = -1;
1166     if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)
1167       // Eval method set using the option 'ffp-eval-method'.
1168       Reason = 1;
1169     if (PP.getLastFPEvalPragmaLocation().isValid())
1170       // Eval method set using the '#pragma clang fp eval_method'.
1171       // We could have both an option and a pragma used to the set the eval
1172       // method. The pragma overrides the option in the command line. The Reason
1173       // of the diagnostic is overriden too.
1174       Reason = 0;
1175     if (Reason != -1)
1176       Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context)
1177           << Reason << 4;
1178   }
1179   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1180   NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
1181   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1182   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1183 }
1184 
1185 void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
1186   // C2x: 7.6.2p3  If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off",
1187   // the translator may assume that the default rounding mode is in effect.
1188   if (FPR == llvm::RoundingMode::Dynamic &&
1189       !CurFPFeatures.getAllowFEnvAccess() &&
1190       CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Ignore)
1191     FPR = llvm::RoundingMode::NearestTiesToEven;
1192 
1193   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1194   NewFPFeatures.setRoundingModeOverride(FPR);
1195   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1196   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1197 }
1198 
1199 void Sema::setExceptionMode(SourceLocation Loc,
1200                             LangOptions::FPExceptionModeKind FPE) {
1201   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1202   NewFPFeatures.setFPExceptionModeOverride(FPE);
1203   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1204   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1205 }
1206 
1207 void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
1208   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1209   auto LO = getLangOpts();
1210   if (IsEnabled) {
1211     // Verify Microsoft restriction:
1212     // You can't enable fenv_access unless precise semantics are enabled.
1213     // Precise semantics can be enabled either by the float_control
1214     // pragma, or by using the /fp:precise or /fp:strict compiler options
1215     if (!isPreciseFPEnabled())
1216       Diag(Loc, diag::err_pragma_fenv_requires_precise);
1217     NewFPFeatures.setAllowFEnvAccessOverride(true);
1218     // Enabling FENV access sets the RoundingMode to Dynamic.
1219     // and ExceptionBehavior to Strict
1220     NewFPFeatures.setRoundingModeOverride(llvm::RoundingMode::Dynamic);
1221     NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
1222   } else {
1223     NewFPFeatures.setAllowFEnvAccessOverride(false);
1224   }
1225   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1226   CurFPFeatures = NewFPFeatures.applyOverrides(LO);
1227 }
1228 
1229 void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
1230                                    LangOptions::FPExceptionModeKind FPE) {
1231   setExceptionMode(Loc, FPE);
1232 }
1233 
1234 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1235                                        SourceLocation Loc) {
1236   // Visibility calculations will consider the namespace's visibility.
1237   // Here we just want to note that we're in a visibility context
1238   // which overrides any enclosing #pragma context, but doesn't itself
1239   // contribute visibility.
1240   PushPragmaVisibility(*this, NoVisibility, Loc);
1241 }
1242 
1243 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1244   if (!VisContext) {
1245     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1246     return;
1247   }
1248 
1249   // Pop visibility from stack
1250   VisStack *Stack = static_cast<VisStack*>(VisContext);
1251 
1252   const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1253   bool StartsWithPragma = Back->first != NoVisibility;
1254   if (StartsWithPragma && IsNamespaceEnd) {
1255     Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1256     Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1257 
1258     // For better error recovery, eat all pushes inside the namespace.
1259     do {
1260       Stack->pop_back();
1261       Back = &Stack->back();
1262       StartsWithPragma = Back->first != NoVisibility;
1263     } while (StartsWithPragma);
1264   } else if (!StartsWithPragma && !IsNamespaceEnd) {
1265     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1266     Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1267     return;
1268   }
1269 
1270   Stack->pop_back();
1271   // To simplify the implementation, never keep around an empty stack.
1272   if (Stack->empty())
1273     FreeVisContext();
1274 }
1275 
1276 template <typename Ty>
1277 static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,
1278                                          const ParsedAttr &A,
1279                                          bool SkipArgCountCheck) {
1280   // Several attributes carry different semantics than the parsing requires, so
1281   // those are opted out of the common argument checks.
1282   //
1283   // We also bail on unknown and ignored attributes because those are handled
1284   // as part of the target-specific handling logic.
1285   if (A.getKind() == ParsedAttr::UnknownAttribute)
1286     return false;
1287   // Check whether the attribute requires specific language extensions to be
1288   // enabled.
1289   if (!A.diagnoseLangOpts(S))
1290     return true;
1291   // Check whether the attribute appertains to the given subject.
1292   if (!A.diagnoseAppertainsTo(S, Node))
1293     return true;
1294   // Check whether the attribute is mutually exclusive with other attributes
1295   // that have already been applied to the declaration.
1296   if (!A.diagnoseMutualExclusion(S, Node))
1297     return true;
1298   // Check whether the attribute exists in the target architecture.
1299   if (S.CheckAttrTarget(A))
1300     return true;
1301 
1302   if (A.hasCustomParsing())
1303     return false;
1304 
1305   if (!SkipArgCountCheck) {
1306     if (A.getMinArgs() == A.getMaxArgs()) {
1307       // If there are no optional arguments, then checking for the argument
1308       // count is trivial.
1309       if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1310         return true;
1311     } else {
1312       // There are optional arguments, so checking is slightly more involved.
1313       if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, A.getMinArgs()))
1314         return true;
1315       else if (!A.hasVariadicArg() && A.getMaxArgs() &&
1316                !A.checkAtMostNumArgs(S, A.getMaxArgs()))
1317         return true;
1318     }
1319   }
1320 
1321   return false;
1322 }
1323 
1324 bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
1325                                         bool SkipArgCountCheck) {
1326   return ::checkCommonAttributeFeatures(*this, D, A, SkipArgCountCheck);
1327 }
1328 bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
1329                                         bool SkipArgCountCheck) {
1330   return ::checkCommonAttributeFeatures(*this, S, A, SkipArgCountCheck);
1331 }
1332