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