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   // If there is no pack value, we don't need any attributes.
52   if (!PackStack.CurrentValue)
53     return;
54 
55   // Otherwise, check to see if we need a max field alignment attribute.
56   if (unsigned Alignment = PackStack.CurrentValue) {
57     if (Alignment == Sema::kMac68kAlignmentSentinel)
58       RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
59     else
60       RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
61                                                         Alignment * 8));
62   }
63   if (PackIncludeStack.empty())
64     return;
65   // The #pragma pack affected a record in an included file,  so Clang should
66   // warn when that pragma was written in a file that included the included
67   // file.
68   for (auto &PackedInclude : llvm::reverse(PackIncludeStack)) {
69     if (PackedInclude.CurrentPragmaLocation != PackStack.CurrentPragmaLocation)
70       break;
71     if (PackedInclude.HasNonDefaultValue)
72       PackedInclude.ShouldWarnOnInclude = true;
73   }
74 }
75 
76 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
77   if (MSStructPragmaOn)
78     RD->addAttr(MSStructAttr::CreateImplicit(Context));
79 
80   // FIXME: We should merge AddAlignmentAttributesForRecord with
81   // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
82   // all active pragmas and applies them as attributes to class definitions.
83   if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
84     RD->addAttr(MSVtorDispAttr::CreateImplicit(
85         Context, unsigned(VtorDispStack.CurrentValue)));
86 }
87 
88 template <typename Attribute>
89 static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
90                                                      CXXRecordDecl *Record) {
91   if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
92     return;
93 
94   for (Decl *Redecl : Record->redecls())
95     Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
96 }
97 
98 void Sema::inferGslPointerAttribute(NamedDecl *ND,
99                                     CXXRecordDecl *UnderlyingRecord) {
100   if (!UnderlyingRecord)
101     return;
102 
103   const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
104   if (!Parent)
105     return;
106 
107   static llvm::StringSet<> Containers{
108       "array",
109       "basic_string",
110       "deque",
111       "forward_list",
112       "vector",
113       "list",
114       "map",
115       "multiset",
116       "multimap",
117       "priority_queue",
118       "queue",
119       "set",
120       "stack",
121       "unordered_set",
122       "unordered_map",
123       "unordered_multiset",
124       "unordered_multimap",
125   };
126 
127   static llvm::StringSet<> Iterators{"iterator", "const_iterator",
128                                      "reverse_iterator",
129                                      "const_reverse_iterator"};
130 
131   if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
132       Containers.count(Parent->getName()))
133     addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
134                                                           UnderlyingRecord);
135 }
136 
137 void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
138 
139   QualType Canonical = TD->getUnderlyingType().getCanonicalType();
140 
141   CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
142   if (!RD) {
143     if (auto *TST =
144             dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
145 
146       RD = dyn_cast_or_null<CXXRecordDecl>(
147           TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
148     }
149   }
150 
151   inferGslPointerAttribute(TD, RD);
152 }
153 
154 void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
155   static llvm::StringSet<> StdOwners{
156       "any",
157       "array",
158       "basic_regex",
159       "basic_string",
160       "deque",
161       "forward_list",
162       "vector",
163       "list",
164       "map",
165       "multiset",
166       "multimap",
167       "optional",
168       "priority_queue",
169       "queue",
170       "set",
171       "stack",
172       "unique_ptr",
173       "unordered_set",
174       "unordered_map",
175       "unordered_multiset",
176       "unordered_multimap",
177       "variant",
178   };
179   static llvm::StringSet<> StdPointers{
180       "basic_string_view",
181       "reference_wrapper",
182       "regex_iterator",
183   };
184 
185   if (!Record->getIdentifier())
186     return;
187 
188   // Handle classes that directly appear in std namespace.
189   if (Record->isInStdNamespace()) {
190     if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
191       return;
192 
193     if (StdOwners.count(Record->getName()))
194       addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
195     else if (StdPointers.count(Record->getName()))
196       addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
197 
198     return;
199   }
200 
201   // Handle nested classes that could be a gsl::Pointer.
202   inferGslPointerAttribute(Record, Record);
203 }
204 
205 void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
206                                    SourceLocation PragmaLoc) {
207   PragmaMsStackAction Action = Sema::PSK_Reset;
208   unsigned Alignment = 0;
209   switch (Kind) {
210     // For all targets we support native and natural are the same.
211     //
212     // FIXME: This is not true on Darwin/PPC.
213   case POAK_Native:
214   case POAK_Power:
215   case POAK_Natural:
216     Action = Sema::PSK_Push_Set;
217     Alignment = 0;
218     break;
219 
220     // Note that '#pragma options align=packed' is not equivalent to attribute
221     // packed, it has a different precedence relative to attribute aligned.
222   case POAK_Packed:
223     Action = Sema::PSK_Push_Set;
224     Alignment = 1;
225     break;
226 
227   case POAK_Mac68k:
228     // Check if the target supports this.
229     if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
230       Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
231       return;
232     }
233     Action = Sema::PSK_Push_Set;
234     Alignment = Sema::kMac68kAlignmentSentinel;
235     break;
236 
237   case POAK_Reset:
238     // Reset just pops the top of the stack, or resets the current alignment to
239     // default.
240     Action = Sema::PSK_Pop;
241     if (PackStack.Stack.empty()) {
242       if (PackStack.CurrentValue) {
243         Action = Sema::PSK_Reset;
244       } else {
245         Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
246             << "stack empty";
247         return;
248       }
249     }
250     break;
251   }
252 
253   PackStack.Act(PragmaLoc, Action, StringRef(), Alignment);
254 }
255 
256 void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action,
257                                    PragmaClangSectionKind SecKind, StringRef SecName) {
258   PragmaClangSection *CSec;
259   int SectionFlags = ASTContext::PSF_Read;
260   switch (SecKind) {
261     case PragmaClangSectionKind::PCSK_BSS:
262       CSec = &PragmaClangBSSSection;
263       SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
264       break;
265     case PragmaClangSectionKind::PCSK_Data:
266       CSec = &PragmaClangDataSection;
267       SectionFlags |= ASTContext::PSF_Write;
268       break;
269     case PragmaClangSectionKind::PCSK_Rodata:
270       CSec = &PragmaClangRodataSection;
271       break;
272     case PragmaClangSectionKind::PCSK_Relro:
273       CSec = &PragmaClangRelroSection;
274       break;
275     case PragmaClangSectionKind::PCSK_Text:
276       CSec = &PragmaClangTextSection;
277       SectionFlags |= ASTContext::PSF_Execute;
278       break;
279     default:
280       llvm_unreachable("invalid clang section kind");
281   }
282 
283   if (Action == PragmaClangSectionAction::PCSA_Clear) {
284     CSec->Valid = false;
285     return;
286   }
287 
288   if (UnifySection(SecName, SectionFlags, PragmaLoc))
289     return;
290 
291   CSec->Valid = true;
292   CSec->SectionName = std::string(SecName);
293   CSec->PragmaLocation = PragmaLoc;
294 }
295 
296 void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
297                            StringRef SlotLabel, Expr *alignment) {
298   Expr *Alignment = static_cast<Expr *>(alignment);
299 
300   // If specified then alignment must be a "small" power of two.
301   unsigned AlignmentVal = 0;
302   if (Alignment) {
303     Optional<llvm::APSInt> Val;
304 
305     // pack(0) is like pack(), which just works out since that is what
306     // we use 0 for in PackAttr.
307     if (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
308         !(Val = Alignment->getIntegerConstantExpr(Context)) ||
309         !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
310       Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
311       return; // Ignore
312     }
313 
314     AlignmentVal = (unsigned)Val->getZExtValue();
315   }
316   if (Action == Sema::PSK_Show) {
317     // Show the current alignment, making sure to show the right value
318     // for the default.
319     // FIXME: This should come from the target.
320     AlignmentVal = PackStack.CurrentValue;
321     if (AlignmentVal == 0)
322       AlignmentVal = 8;
323     if (AlignmentVal == Sema::kMac68kAlignmentSentinel)
324       Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
325     else
326       Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
327   }
328   // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
329   // "#pragma pack(pop, identifier, n) is undefined"
330   if (Action & Sema::PSK_Pop) {
331     if (Alignment && !SlotLabel.empty())
332       Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
333     if (PackStack.Stack.empty())
334       Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
335   }
336 
337   PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal);
338 }
339 
340 void Sema::DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
341                                         SourceLocation IncludeLoc) {
342   if (Kind == PragmaPackDiagnoseKind::NonDefaultStateAtInclude) {
343     SourceLocation PrevLocation = PackStack.CurrentPragmaLocation;
344     // Warn about non-default alignment at #includes (without redundant
345     // warnings for the same directive in nested includes).
346     // The warning is delayed until the end of the file to avoid warnings
347     // for files that don't have any records that are affected by the modified
348     // alignment.
349     bool HasNonDefaultValue =
350         PackStack.hasValue() &&
351         (PackIncludeStack.empty() ||
352          PackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
353     PackIncludeStack.push_back(
354         {PackStack.CurrentValue,
355          PackStack.hasValue() ? PrevLocation : SourceLocation(),
356          HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
357     return;
358   }
359 
360   assert(Kind == PragmaPackDiagnoseKind::ChangedStateAtExit && "invalid kind");
361   PackIncludeState PrevPackState = PackIncludeStack.pop_back_val();
362   if (PrevPackState.ShouldWarnOnInclude) {
363     // Emit the delayed non-default alignment at #include warning.
364     Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
365     Diag(PrevPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
366   }
367   // Warn about modified alignment after #includes.
368   if (PrevPackState.CurrentValue != PackStack.CurrentValue) {
369     Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
370     Diag(PackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
371   }
372 }
373 
374 void Sema::DiagnoseUnterminatedPragmaPack() {
375   if (PackStack.Stack.empty())
376     return;
377   bool IsInnermost = true;
378   for (const auto &StackSlot : llvm::reverse(PackStack.Stack)) {
379     Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
380     // The user might have already reset the alignment, so suggest replacing
381     // the reset with a pop.
382     if (IsInnermost && PackStack.CurrentValue == PackStack.DefaultValue) {
383       DiagnosticBuilder DB = Diag(PackStack.CurrentPragmaLocation,
384                                   diag::note_pragma_pack_pop_instead_reset);
385       SourceLocation FixItLoc = Lexer::findLocationAfterToken(
386           PackStack.CurrentPragmaLocation, tok::l_paren, SourceMgr, LangOpts,
387           /*SkipTrailing=*/false);
388       if (FixItLoc.isValid())
389         DB << FixItHint::CreateInsertion(FixItLoc, "pop");
390     }
391     IsInnermost = false;
392   }
393 }
394 
395 void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
396   MSStructPragmaOn = (Kind == PMSST_ON);
397 }
398 
399 void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
400                                 PragmaMSCommentKind Kind, StringRef Arg) {
401   auto *PCD = PragmaCommentDecl::Create(
402       Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
403   Context.getTranslationUnitDecl()->addDecl(PCD);
404   Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
405 }
406 
407 void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
408                                      StringRef Value) {
409   auto *PDMD = PragmaDetectMismatchDecl::Create(
410       Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
411   Context.getTranslationUnitDecl()->addDecl(PDMD);
412   Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
413 }
414 
415 void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
416                                    PragmaMsStackAction Action,
417                                    PragmaFloatControlKind Value) {
418   unsigned NewValue = FpPragmaStack.hasValue()
419                           ? FpPragmaStack.CurrentValue
420                           : CurFPFeatureOverrides().getAsOpaqueInt();
421   FPOptionsOverride NewFPFeatures(NewValue);
422   if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
423       !(CurContext->isTranslationUnit()) && !CurContext->isNamespace()) {
424     // Push and pop can only occur at file or namespace scope.
425     Diag(Loc, diag::err_pragma_fc_pp_scope);
426     return;
427   }
428   switch (Value) {
429   default:
430     llvm_unreachable("invalid pragma float_control kind");
431   case PFC_Precise:
432     NewFPFeatures.setFPPreciseEnabled(true);
433     NewValue = NewFPFeatures.getAsOpaqueInt();
434     FpPragmaStack.Act(Loc, Action, StringRef(), NewValue);
435     break;
436   case PFC_NoPrecise:
437     if (CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Strict)
438       Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
439     else if (CurFPFeatures.getAllowFEnvAccess())
440       Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
441     else
442       NewFPFeatures.setFPPreciseEnabled(false);
443     NewValue = NewFPFeatures.getAsOpaqueInt();
444     FpPragmaStack.Act(Loc, Action, StringRef(), NewValue);
445     break;
446   case PFC_Except:
447     if (!isPreciseFPEnabled())
448       Diag(Loc, diag::err_pragma_fc_except_requires_precise);
449     else
450       NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
451     NewValue = NewFPFeatures.getAsOpaqueInt();
452     FpPragmaStack.Act(Loc, Action, StringRef(), NewValue);
453     break;
454   case PFC_NoExcept:
455     NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Ignore);
456     NewValue = NewFPFeatures.getAsOpaqueInt();
457     FpPragmaStack.Act(Loc, Action, StringRef(), NewValue);
458     break;
459   case PFC_Push:
460     FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(),
461                       NewFPFeatures.getAsOpaqueInt());
462     break;
463   case PFC_Pop:
464     if (FpPragmaStack.Stack.empty()) {
465       Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
466                                               << "stack empty";
467       return;
468     }
469     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures.getAsOpaqueInt());
470     NewValue = FpPragmaStack.CurrentValue;
471     break;
472   }
473   FPOptionsOverride NewOverrides;
474   if (NewValue != FpPragmaStack.DefaultValue)
475     NewOverrides.getFromOpaqueInt(NewValue);
476   CurFPFeatures = NewOverrides.applyOverrides(getLangOpts());
477 }
478 
479 void Sema::ActOnPragmaMSPointersToMembers(
480     LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
481     SourceLocation PragmaLoc) {
482   MSPointerToMemberRepresentationMethod = RepresentationMethod;
483   ImplicitMSInheritanceAttrLoc = PragmaLoc;
484 }
485 
486 void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
487                                  SourceLocation PragmaLoc,
488                                  MSVtorDispMode Mode) {
489   if (Action & PSK_Pop && VtorDispStack.Stack.empty())
490     Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
491                                                   << "stack empty";
492   VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
493 }
494 
495 bool Sema::UnifySection(StringRef SectionName,
496                         int SectionFlags,
497                         DeclaratorDecl *Decl) {
498   SourceLocation PragmaLocation;
499   if (auto A = Decl->getAttr<SectionAttr>())
500     if (A->isImplicit())
501       PragmaLocation = A->getLocation();
502   auto SectionIt = Context.SectionInfos.find(SectionName);
503   if (SectionIt == Context.SectionInfos.end()) {
504     Context.SectionInfos[SectionName] =
505         ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
506     return false;
507   }
508   // A pre-declared section takes precedence w/o diagnostic.
509   const auto &Section = SectionIt->second;
510   if (Section.SectionFlags == SectionFlags ||
511       ((SectionFlags & ASTContext::PSF_Implicit) &&
512        !(Section.SectionFlags & ASTContext::PSF_Implicit)))
513     return false;
514   Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
515   if (Section.Decl)
516     Diag(Section.Decl->getLocation(), diag::note_declared_at)
517         << Section.Decl->getName();
518   if (PragmaLocation.isValid())
519     Diag(PragmaLocation, diag::note_pragma_entered_here);
520   if (Section.PragmaSectionLocation.isValid())
521     Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
522   return true;
523 }
524 
525 bool Sema::UnifySection(StringRef SectionName,
526                         int SectionFlags,
527                         SourceLocation PragmaSectionLocation) {
528   auto SectionIt = Context.SectionInfos.find(SectionName);
529   if (SectionIt != Context.SectionInfos.end()) {
530     const auto &Section = SectionIt->second;
531     if (Section.SectionFlags == SectionFlags)
532       return false;
533     if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
534       Diag(PragmaSectionLocation, diag::err_section_conflict)
535           << "this" << Section;
536       if (Section.Decl)
537         Diag(Section.Decl->getLocation(), diag::note_declared_at)
538             << Section.Decl->getName();
539       if (Section.PragmaSectionLocation.isValid())
540         Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
541       return true;
542     }
543   }
544   Context.SectionInfos[SectionName] =
545       ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
546   return false;
547 }
548 
549 /// Called on well formed \#pragma bss_seg().
550 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
551                             PragmaMsStackAction Action,
552                             llvm::StringRef StackSlotLabel,
553                             StringLiteral *SegmentName,
554                             llvm::StringRef PragmaName) {
555   PragmaStack<StringLiteral *> *Stack =
556     llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
557         .Case("data_seg", &DataSegStack)
558         .Case("bss_seg", &BSSSegStack)
559         .Case("const_seg", &ConstSegStack)
560         .Case("code_seg", &CodeSegStack);
561   if (Action & PSK_Pop && Stack->Stack.empty())
562     Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
563         << "stack empty";
564   if (SegmentName) {
565     if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
566       return;
567 
568     if (SegmentName->getString() == ".drectve" &&
569         Context.getTargetInfo().getCXXABI().isMicrosoft())
570       Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
571   }
572 
573   Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
574 }
575 
576 /// Called on well formed \#pragma bss_seg().
577 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
578                                 int SectionFlags, StringLiteral *SegmentName) {
579   UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
580 }
581 
582 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
583                                 StringLiteral *SegmentName) {
584   // There's no stack to maintain, so we just have a current section.  When we
585   // see the default section, reset our current section back to null so we stop
586   // tacking on unnecessary attributes.
587   CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
588   CurInitSegLoc = PragmaLocation;
589 }
590 
591 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
592                              SourceLocation PragmaLoc) {
593 
594   IdentifierInfo *Name = IdTok.getIdentifierInfo();
595   LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
596   LookupParsedName(Lookup, curScope, nullptr, true);
597 
598   if (Lookup.empty()) {
599     Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
600       << Name << SourceRange(IdTok.getLocation());
601     return;
602   }
603 
604   VarDecl *VD = Lookup.getAsSingle<VarDecl>();
605   if (!VD) {
606     Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
607       << Name << SourceRange(IdTok.getLocation());
608     return;
609   }
610 
611   // Warn if this was used before being marked unused.
612   if (VD->isUsed())
613     Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
614 
615   VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
616                                          AttributeCommonInfo::AS_Pragma,
617                                          UnusedAttr::GNU_unused));
618 }
619 
620 void Sema::AddCFAuditedAttribute(Decl *D) {
621   IdentifierInfo *Ident;
622   SourceLocation Loc;
623   std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
624   if (!Loc.isValid()) return;
625 
626   // Don't add a redundant or conflicting attribute.
627   if (D->hasAttr<CFAuditedTransferAttr>() ||
628       D->hasAttr<CFUnknownTransferAttr>())
629     return;
630 
631   AttributeCommonInfo Info(Ident, SourceRange(Loc),
632                            AttributeCommonInfo::AS_Pragma);
633   D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
634 }
635 
636 namespace {
637 
638 Optional<attr::SubjectMatchRule>
639 getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
640   using namespace attr;
641   switch (Rule) {
642   default:
643     return None;
644 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
645 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
646   case Value:                                                                  \
647     return Parent;
648 #include "clang/Basic/AttrSubMatchRulesList.inc"
649   }
650 }
651 
652 bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
653   using namespace attr;
654   switch (Rule) {
655   default:
656     return false;
657 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
658 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
659   case Value:                                                                  \
660     return IsNegated;
661 #include "clang/Basic/AttrSubMatchRulesList.inc"
662   }
663 }
664 
665 CharSourceRange replacementRangeForListElement(const Sema &S,
666                                                SourceRange Range) {
667   // Make sure that the ',' is removed as well.
668   SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
669       Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
670       /*SkipTrailingWhitespaceAndNewLine=*/false);
671   if (AfterCommaLoc.isValid())
672     return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
673   else
674     return CharSourceRange::getTokenRange(Range);
675 }
676 
677 std::string
678 attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
679   std::string Result;
680   llvm::raw_string_ostream OS(Result);
681   for (const auto &I : llvm::enumerate(Rules)) {
682     if (I.index())
683       OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
684     OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
685   }
686   return OS.str();
687 }
688 
689 } // end anonymous namespace
690 
691 void Sema::ActOnPragmaAttributeAttribute(
692     ParsedAttr &Attribute, SourceLocation PragmaLoc,
693     attr::ParsedSubjectMatchRuleSet Rules) {
694   Attribute.setIsPragmaClangAttribute();
695   SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
696   // Gather the subject match rules that are supported by the attribute.
697   SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
698       StrictSubjectMatchRuleSet;
699   Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
700 
701   // Figure out which subject matching rules are valid.
702   if (StrictSubjectMatchRuleSet.empty()) {
703     // Check for contradicting match rules. Contradicting match rules are
704     // either:
705     //  - a top-level rule and one of its sub-rules. E.g. variable and
706     //    variable(is_parameter).
707     //  - a sub-rule and a sibling that's negated. E.g.
708     //    variable(is_thread_local) and variable(unless(is_parameter))
709     llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
710         RulesToFirstSpecifiedNegatedSubRule;
711     for (const auto &Rule : Rules) {
712       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
713       Optional<attr::SubjectMatchRule> ParentRule =
714           getParentAttrMatcherRule(MatchRule);
715       if (!ParentRule)
716         continue;
717       auto It = Rules.find(*ParentRule);
718       if (It != Rules.end()) {
719         // A sub-rule contradicts a parent rule.
720         Diag(Rule.second.getBegin(),
721              diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
722             << attr::getSubjectMatchRuleSpelling(MatchRule)
723             << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
724             << FixItHint::CreateRemoval(
725                    replacementRangeForListElement(*this, Rule.second));
726         // Keep going without removing this rule as it won't change the set of
727         // declarations that receive the attribute.
728         continue;
729       }
730       if (isNegatedAttrMatcherSubRule(MatchRule))
731         RulesToFirstSpecifiedNegatedSubRule.insert(
732             std::make_pair(*ParentRule, Rule));
733     }
734     bool IgnoreNegatedSubRules = false;
735     for (const auto &Rule : Rules) {
736       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
737       Optional<attr::SubjectMatchRule> ParentRule =
738           getParentAttrMatcherRule(MatchRule);
739       if (!ParentRule)
740         continue;
741       auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
742       if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
743           It->second != Rule) {
744         // Negated sub-rule contradicts another sub-rule.
745         Diag(
746             It->second.second.getBegin(),
747             diag::
748                 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
749             << attr::getSubjectMatchRuleSpelling(
750                    attr::SubjectMatchRule(It->second.first))
751             << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
752             << FixItHint::CreateRemoval(
753                    replacementRangeForListElement(*this, It->second.second));
754         // Keep going but ignore all of the negated sub-rules.
755         IgnoreNegatedSubRules = true;
756         RulesToFirstSpecifiedNegatedSubRule.erase(It);
757       }
758     }
759 
760     if (!IgnoreNegatedSubRules) {
761       for (const auto &Rule : Rules)
762         SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
763     } else {
764       for (const auto &Rule : Rules) {
765         if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
766           SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
767       }
768     }
769     Rules.clear();
770   } else {
771     for (const auto &Rule : StrictSubjectMatchRuleSet) {
772       if (Rules.erase(Rule.first)) {
773         // Add the rule to the set of attribute receivers only if it's supported
774         // in the current language mode.
775         if (Rule.second)
776           SubjectMatchRules.push_back(Rule.first);
777       }
778     }
779   }
780 
781   if (!Rules.empty()) {
782     auto Diagnostic =
783         Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
784         << Attribute;
785     SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
786     for (const auto &Rule : Rules) {
787       ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
788       Diagnostic << FixItHint::CreateRemoval(
789           replacementRangeForListElement(*this, Rule.second));
790     }
791     Diagnostic << attrMatcherRuleListToString(ExtraRules);
792   }
793 
794   if (PragmaAttributeStack.empty()) {
795     Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
796     return;
797   }
798 
799   PragmaAttributeStack.back().Entries.push_back(
800       {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
801 }
802 
803 void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
804                                          const IdentifierInfo *Namespace) {
805   PragmaAttributeStack.emplace_back();
806   PragmaAttributeStack.back().Loc = PragmaLoc;
807   PragmaAttributeStack.back().Namespace = Namespace;
808 }
809 
810 void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
811                                    const IdentifierInfo *Namespace) {
812   if (PragmaAttributeStack.empty()) {
813     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
814     return;
815   }
816 
817   // Dig back through the stack trying to find the most recently pushed group
818   // that in Namespace. Note that this works fine if no namespace is present,
819   // think of push/pops without namespaces as having an implicit "nullptr"
820   // namespace.
821   for (size_t Index = PragmaAttributeStack.size(); Index;) {
822     --Index;
823     if (PragmaAttributeStack[Index].Namespace == Namespace) {
824       for (const PragmaAttributeEntry &Entry :
825            PragmaAttributeStack[Index].Entries) {
826         if (!Entry.IsUsed) {
827           assert(Entry.Attribute && "Expected an attribute");
828           Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
829               << *Entry.Attribute;
830           Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
831         }
832       }
833       PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
834       return;
835     }
836   }
837 
838   if (Namespace)
839     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
840         << 0 << Namespace->getName();
841   else
842     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
843 }
844 
845 void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
846   if (PragmaAttributeStack.empty())
847     return;
848   for (auto &Group : PragmaAttributeStack) {
849     for (auto &Entry : Group.Entries) {
850       ParsedAttr *Attribute = Entry.Attribute;
851       assert(Attribute && "Expected an attribute");
852       assert(Attribute->isPragmaClangAttribute() &&
853              "expected #pragma clang attribute");
854 
855       // Ensure that the attribute can be applied to the given declaration.
856       bool Applies = false;
857       for (const auto &Rule : Entry.MatchRules) {
858         if (Attribute->appliesToDecl(D, Rule)) {
859           Applies = true;
860           break;
861         }
862       }
863       if (!Applies)
864         continue;
865       Entry.IsUsed = true;
866       PragmaAttributeCurrentTargetDecl = D;
867       ParsedAttributesView Attrs;
868       Attrs.addAtEnd(Attribute);
869       ProcessDeclAttributeList(S, D, Attrs);
870       PragmaAttributeCurrentTargetDecl = nullptr;
871     }
872   }
873 }
874 
875 void Sema::PrintPragmaAttributeInstantiationPoint() {
876   assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
877   Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
878                diag::note_pragma_attribute_applied_decl_here);
879 }
880 
881 void Sema::DiagnoseUnterminatedPragmaAttribute() {
882   if (PragmaAttributeStack.empty())
883     return;
884   Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
885 }
886 
887 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
888   if(On)
889     OptimizeOffPragmaLocation = SourceLocation();
890   else
891     OptimizeOffPragmaLocation = PragmaLoc;
892 }
893 
894 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
895   // In the future, check other pragmas if they're implemented (e.g. pragma
896   // optimize 0 will probably map to this functionality too).
897   if(OptimizeOffPragmaLocation.isValid())
898     AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
899 }
900 
901 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
902                                             SourceLocation Loc) {
903   // Don't add a conflicting attribute. No diagnostic is needed.
904   if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
905     return;
906 
907   // Add attributes only if required. Optnone requires noinline as well, but if
908   // either is already present then don't bother adding them.
909   if (!FD->hasAttr<OptimizeNoneAttr>())
910     FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
911   if (!FD->hasAttr<NoInlineAttr>())
912     FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
913 }
914 
915 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
916 enum : unsigned { NoVisibility = ~0U };
917 
918 void Sema::AddPushedVisibilityAttribute(Decl *D) {
919   if (!VisContext)
920     return;
921 
922   NamedDecl *ND = dyn_cast<NamedDecl>(D);
923   if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
924     return;
925 
926   VisStack *Stack = static_cast<VisStack*>(VisContext);
927   unsigned rawType = Stack->back().first;
928   if (rawType == NoVisibility) return;
929 
930   VisibilityAttr::VisibilityType type
931     = (VisibilityAttr::VisibilityType) rawType;
932   SourceLocation loc = Stack->back().second;
933 
934   D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
935 }
936 
937 /// FreeVisContext - Deallocate and null out VisContext.
938 void Sema::FreeVisContext() {
939   delete static_cast<VisStack*>(VisContext);
940   VisContext = nullptr;
941 }
942 
943 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
944   // Put visibility on stack.
945   if (!S.VisContext)
946     S.VisContext = new VisStack;
947 
948   VisStack *Stack = static_cast<VisStack*>(S.VisContext);
949   Stack->push_back(std::make_pair(type, loc));
950 }
951 
952 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
953                                  SourceLocation PragmaLoc) {
954   if (VisType) {
955     // Compute visibility to use.
956     VisibilityAttr::VisibilityType T;
957     if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
958       Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
959       return;
960     }
961     PushPragmaVisibility(*this, T, PragmaLoc);
962   } else {
963     PopPragmaVisibility(false, PragmaLoc);
964   }
965 }
966 
967 void Sema::ActOnPragmaFPContract(SourceLocation Loc,
968                                  LangOptions::FPModeKind FPC) {
969   unsigned NewValue = FpPragmaStack.hasValue()
970                           ? FpPragmaStack.CurrentValue
971                           : CurFPFeatureOverrides().getAsOpaqueInt();
972   FPOptionsOverride NewFPFeatures(NewValue);
973   switch (FPC) {
974   case LangOptions::FPM_On:
975     NewFPFeatures.setAllowFPContractWithinStatement();
976     break;
977   case LangOptions::FPM_Fast:
978     NewFPFeatures.setAllowFPContractAcrossStatement();
979     break;
980   case LangOptions::FPM_Off:
981     NewFPFeatures.setDisallowFPContract();
982     break;
983   }
984   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
985   FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(),
986                     NewFPFeatures.getAsOpaqueInt());
987 }
988 
989 void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
990   unsigned NewValue = FpPragmaStack.hasValue()
991                           ? FpPragmaStack.CurrentValue
992                           : CurFPFeatureOverrides().getAsOpaqueInt();
993   FPOptionsOverride NewFPFeatures(NewValue);
994   NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
995   NewValue = NewFPFeatures.getAsOpaqueInt();
996   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewValue);
997   FPOptionsOverride NewOverrides(NewValue);
998   CurFPFeatures = NewOverrides.applyOverrides(getLangOpts());
999 }
1000 
1001 void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
1002   unsigned NewValue = FpPragmaStack.hasValue()
1003                           ? FpPragmaStack.CurrentValue
1004                           : CurFPFeatureOverrides().getAsOpaqueInt();
1005   FPOptionsOverride NewFPFeatures(NewValue);
1006   NewFPFeatures.setRoundingModeOverride(FPR);
1007   NewValue = NewFPFeatures.getAsOpaqueInt();
1008   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewValue);
1009   FPOptionsOverride NewOverrides(NewValue);
1010   CurFPFeatures = NewOverrides.applyOverrides(getLangOpts());
1011 }
1012 
1013 void Sema::setExceptionMode(SourceLocation Loc,
1014                             LangOptions::FPExceptionModeKind FPE) {
1015   unsigned NewValue = FpPragmaStack.hasValue()
1016                           ? FpPragmaStack.CurrentValue
1017                           : CurFPFeatureOverrides().getAsOpaqueInt();
1018   FPOptionsOverride NewFPFeatures(NewValue);
1019   NewFPFeatures.setFPExceptionModeOverride(FPE);
1020   NewValue = NewFPFeatures.getAsOpaqueInt();
1021   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewValue);
1022   FPOptionsOverride NewOverrides(NewValue);
1023   CurFPFeatures = NewOverrides.applyOverrides(getLangOpts());
1024 }
1025 
1026 void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
1027   unsigned NewValue = FpPragmaStack.hasValue()
1028                           ? FpPragmaStack.CurrentValue
1029                           : CurFPFeatureOverrides().getAsOpaqueInt();
1030   FPOptionsOverride NewFPFeatures(NewValue);
1031   if (IsEnabled) {
1032     // Verify Microsoft restriction:
1033     // You can't enable fenv_access unless precise semantics are enabled.
1034     // Precise semantics can be enabled either by the float_control
1035     // pragma, or by using the /fp:precise or /fp:strict compiler options
1036     if (!isPreciseFPEnabled())
1037       Diag(Loc, diag::err_pragma_fenv_requires_precise);
1038     NewFPFeatures.setAllowFEnvAccessOverride(true);
1039   } else
1040     NewFPFeatures.setAllowFEnvAccessOverride(false);
1041   NewValue = NewFPFeatures.getAsOpaqueInt();
1042   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewValue);
1043   FPOptionsOverride NewOverrides(NewValue);
1044   CurFPFeatures = NewOverrides.applyOverrides(getLangOpts());
1045 }
1046 
1047 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1048                                        SourceLocation Loc) {
1049   // Visibility calculations will consider the namespace's visibility.
1050   // Here we just want to note that we're in a visibility context
1051   // which overrides any enclosing #pragma context, but doesn't itself
1052   // contribute visibility.
1053   PushPragmaVisibility(*this, NoVisibility, Loc);
1054 }
1055 
1056 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1057   if (!VisContext) {
1058     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1059     return;
1060   }
1061 
1062   // Pop visibility from stack
1063   VisStack *Stack = static_cast<VisStack*>(VisContext);
1064 
1065   const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1066   bool StartsWithPragma = Back->first != NoVisibility;
1067   if (StartsWithPragma && IsNamespaceEnd) {
1068     Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1069     Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1070 
1071     // For better error recovery, eat all pushes inside the namespace.
1072     do {
1073       Stack->pop_back();
1074       Back = &Stack->back();
1075       StartsWithPragma = Back->first != NoVisibility;
1076     } while (StartsWithPragma);
1077   } else if (!StartsWithPragma && !IsNamespaceEnd) {
1078     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1079     Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1080     return;
1081   }
1082 
1083   Stack->pop_back();
1084   // To simplify the implementation, never keep around an empty stack.
1085   if (Stack->empty())
1086     FreeVisContext();
1087 }
1088