1 //===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for non-trivial attributes and
13 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/SemaInternal.h"
22 using namespace clang;
24 //===----------------------------------------------------------------------===//
25 // Pragma 'pack' and 'options align'
26 //===----------------------------------------------------------------------===//
28 Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
31 : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
33 S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
34 S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
35 S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
36 S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
37 S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
41 Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
43 S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
44 S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
45 S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
46 S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
47 S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
51 void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
52 // If there is no pack value, we don't need any attributes.
53 if (!PackStack.CurrentValue)
56 // Otherwise, check to see if we need a max field alignment attribute.
57 if (unsigned Alignment = PackStack.CurrentValue) {
58 if (Alignment == Sema::kMac68kAlignmentSentinel)
59 RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
61 RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
66 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
68 RD->addAttr(MSStructAttr::CreateImplicit(Context));
70 // FIXME: We should merge AddAlignmentAttributesForRecord with
71 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
72 // all active pragmas and applies them as attributes to class definitions.
73 if (VtorDispStack.CurrentValue != getLangOpts().VtorDispMode)
75 MSVtorDispAttr::CreateImplicit(Context, VtorDispStack.CurrentValue));
78 void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
79 SourceLocation PragmaLoc) {
80 PragmaMsStackAction Action = Sema::PSK_Reset;
81 unsigned Alignment = 0;
83 // For all targets we support native and natural are the same.
85 // FIXME: This is not true on Darwin/PPC.
89 Action = Sema::PSK_Push_Set;
93 // Note that '#pragma options align=packed' is not equivalent to attribute
94 // packed, it has a different precedence relative to attribute aligned.
96 Action = Sema::PSK_Push_Set;
101 // Check if the target supports this.
102 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
103 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
106 Action = Sema::PSK_Push_Set;
107 Alignment = Sema::kMac68kAlignmentSentinel;
111 // Reset just pops the top of the stack, or resets the current alignment to
113 Action = Sema::PSK_Pop;
114 if (PackStack.Stack.empty()) {
115 if (PackStack.CurrentValue) {
116 Action = Sema::PSK_Reset;
118 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
126 PackStack.Act(PragmaLoc, Action, StringRef(), Alignment);
129 void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
130 StringRef SlotLabel, Expr *alignment) {
131 Expr *Alignment = static_cast<Expr *>(alignment);
133 // If specified then alignment must be a "small" power of two.
134 unsigned AlignmentVal = 0;
138 // pack(0) is like pack(), which just works out since that is what
139 // we use 0 for in PackAttr.
140 if (Alignment->isTypeDependent() ||
141 Alignment->isValueDependent() ||
142 !Alignment->isIntegerConstantExpr(Val, Context) ||
143 !(Val == 0 || Val.isPowerOf2()) ||
144 Val.getZExtValue() > 16) {
145 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
149 AlignmentVal = (unsigned) Val.getZExtValue();
151 if (Action == Sema::PSK_Show) {
152 // Show the current alignment, making sure to show the right value
154 // FIXME: This should come from the target.
155 AlignmentVal = PackStack.CurrentValue;
156 if (AlignmentVal == 0)
158 if (AlignmentVal == Sema::kMac68kAlignmentSentinel)
159 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
161 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
163 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
164 // "#pragma pack(pop, identifier, n) is undefined"
165 if (Action & Sema::PSK_Pop) {
166 if (Alignment && !SlotLabel.empty())
167 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
168 if (PackStack.Stack.empty())
169 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
172 PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal);
175 void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
176 MSStructPragmaOn = (Kind == PMSST_ON);
179 void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
180 PragmaMSCommentKind Kind, StringRef Arg) {
181 auto *PCD = PragmaCommentDecl::Create(
182 Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
183 Context.getTranslationUnitDecl()->addDecl(PCD);
184 Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
187 void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
189 auto *PDMD = PragmaDetectMismatchDecl::Create(
190 Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
191 Context.getTranslationUnitDecl()->addDecl(PDMD);
192 Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
195 void Sema::ActOnPragmaMSPointersToMembers(
196 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
197 SourceLocation PragmaLoc) {
198 MSPointerToMemberRepresentationMethod = RepresentationMethod;
199 ImplicitMSInheritanceAttrLoc = PragmaLoc;
202 void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
203 SourceLocation PragmaLoc,
204 MSVtorDispAttr::Mode Mode) {
205 if (Action & PSK_Pop && VtorDispStack.Stack.empty())
206 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
208 VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
211 template<typename ValueType>
212 void Sema::PragmaStack<ValueType>::Act(SourceLocation PragmaLocation,
213 PragmaMsStackAction Action,
214 llvm::StringRef StackSlotLabel,
216 if (Action == PSK_Reset) {
217 CurrentValue = DefaultValue;
220 if (Action & PSK_Push)
221 Stack.push_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation));
222 else if (Action & PSK_Pop) {
223 if (!StackSlotLabel.empty()) {
224 // If we've got a label, try to find it and jump there.
225 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
226 return x.StackSlotLabel == StackSlotLabel;
228 // If we found the label so pop from there.
229 if (I != Stack.rend()) {
230 CurrentValue = I->Value;
231 CurrentPragmaLocation = I->PragmaLocation;
232 Stack.erase(std::prev(I.base()), Stack.end());
234 } else if (!Stack.empty()) {
235 // We don't have a label, just pop the last entry.
236 CurrentValue = Stack.back().Value;
237 CurrentPragmaLocation = Stack.back().PragmaLocation;
241 if (Action & PSK_Set) {
242 CurrentValue = Value;
243 CurrentPragmaLocation = PragmaLocation;
247 bool Sema::UnifySection(StringRef SectionName,
249 DeclaratorDecl *Decl) {
250 auto Section = Context.SectionInfos.find(SectionName);
251 if (Section == Context.SectionInfos.end()) {
252 Context.SectionInfos[SectionName] =
253 ASTContext::SectionInfo(Decl, SourceLocation(), SectionFlags);
256 // A pre-declared section takes precedence w/o diagnostic.
257 if (Section->second.SectionFlags == SectionFlags ||
258 !(Section->second.SectionFlags & ASTContext::PSF_Implicit))
260 auto OtherDecl = Section->second.Decl;
261 Diag(Decl->getLocation(), diag::err_section_conflict)
262 << Decl << OtherDecl;
263 Diag(OtherDecl->getLocation(), diag::note_declared_at)
264 << OtherDecl->getName();
265 if (auto A = Decl->getAttr<SectionAttr>())
267 Diag(A->getLocation(), diag::note_pragma_entered_here);
268 if (auto A = OtherDecl->getAttr<SectionAttr>())
270 Diag(A->getLocation(), diag::note_pragma_entered_here);
274 bool Sema::UnifySection(StringRef SectionName,
276 SourceLocation PragmaSectionLocation) {
277 auto Section = Context.SectionInfos.find(SectionName);
278 if (Section != Context.SectionInfos.end()) {
279 if (Section->second.SectionFlags == SectionFlags)
281 if (!(Section->second.SectionFlags & ASTContext::PSF_Implicit)) {
282 Diag(PragmaSectionLocation, diag::err_section_conflict)
283 << "this" << "a prior #pragma section";
284 Diag(Section->second.PragmaSectionLocation,
285 diag::note_pragma_entered_here);
289 Context.SectionInfos[SectionName] =
290 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
294 /// \brief Called on well formed \#pragma bss_seg().
295 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
296 PragmaMsStackAction Action,
297 llvm::StringRef StackSlotLabel,
298 StringLiteral *SegmentName,
299 llvm::StringRef PragmaName) {
300 PragmaStack<StringLiteral *> *Stack =
301 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
302 .Case("data_seg", &DataSegStack)
303 .Case("bss_seg", &BSSSegStack)
304 .Case("const_seg", &ConstSegStack)
305 .Case("code_seg", &CodeSegStack);
306 if (Action & PSK_Pop && Stack->Stack.empty())
307 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
310 !checkSectionName(SegmentName->getLocStart(), SegmentName->getString()))
312 Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
315 /// \brief Called on well formed \#pragma bss_seg().
316 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
317 int SectionFlags, StringLiteral *SegmentName) {
318 UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
321 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
322 StringLiteral *SegmentName) {
323 // There's no stack to maintain, so we just have a current section. When we
324 // see the default section, reset our current section back to null so we stop
325 // tacking on unnecessary attributes.
326 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
327 CurInitSegLoc = PragmaLocation;
330 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
331 SourceLocation PragmaLoc) {
333 IdentifierInfo *Name = IdTok.getIdentifierInfo();
334 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
335 LookupParsedName(Lookup, curScope, nullptr, true);
337 if (Lookup.empty()) {
338 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
339 << Name << SourceRange(IdTok.getLocation());
343 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
345 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
346 << Name << SourceRange(IdTok.getLocation());
350 // Warn if this was used before being marked unused.
352 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
354 VD->addAttr(UnusedAttr::CreateImplicit(Context, UnusedAttr::GNU_unused,
355 IdTok.getLocation()));
358 void Sema::AddCFAuditedAttribute(Decl *D) {
359 SourceLocation Loc = PP.getPragmaARCCFCodeAuditedLoc();
360 if (!Loc.isValid()) return;
362 // Don't add a redundant or conflicting attribute.
363 if (D->hasAttr<CFAuditedTransferAttr>() ||
364 D->hasAttr<CFUnknownTransferAttr>())
367 D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Loc));
370 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
372 OptimizeOffPragmaLocation = SourceLocation();
374 OptimizeOffPragmaLocation = PragmaLoc;
377 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
378 // In the future, check other pragmas if they're implemented (e.g. pragma
379 // optimize 0 will probably map to this functionality too).
380 if(OptimizeOffPragmaLocation.isValid())
381 AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
384 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
385 SourceLocation Loc) {
386 // Don't add a conflicting attribute. No diagnostic is needed.
387 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
390 // Add attributes only if required. Optnone requires noinline as well, but if
391 // either is already present then don't bother adding them.
392 if (!FD->hasAttr<OptimizeNoneAttr>())
393 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
394 if (!FD->hasAttr<NoInlineAttr>())
395 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
398 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
399 enum : unsigned { NoVisibility = ~0U };
401 void Sema::AddPushedVisibilityAttribute(Decl *D) {
405 NamedDecl *ND = dyn_cast<NamedDecl>(D);
406 if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
409 VisStack *Stack = static_cast<VisStack*>(VisContext);
410 unsigned rawType = Stack->back().first;
411 if (rawType == NoVisibility) return;
413 VisibilityAttr::VisibilityType type
414 = (VisibilityAttr::VisibilityType) rawType;
415 SourceLocation loc = Stack->back().second;
417 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
420 /// FreeVisContext - Deallocate and null out VisContext.
421 void Sema::FreeVisContext() {
422 delete static_cast<VisStack*>(VisContext);
423 VisContext = nullptr;
426 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
427 // Put visibility on stack.
429 S.VisContext = new VisStack;
431 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
432 Stack->push_back(std::make_pair(type, loc));
435 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
436 SourceLocation PragmaLoc) {
438 // Compute visibility to use.
439 VisibilityAttr::VisibilityType T;
440 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
441 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
444 PushPragmaVisibility(*this, T, PragmaLoc);
446 PopPragmaVisibility(false, PragmaLoc);
450 void Sema::ActOnPragmaFPContract(tok::OnOffSwitch OOS) {
453 FPFeatures.fp_contract = 1;
456 FPFeatures.fp_contract = 0;
458 case tok::OOS_DEFAULT:
459 FPFeatures.fp_contract = getLangOpts().DefaultFPContract;
464 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
465 SourceLocation Loc) {
466 // Visibility calculations will consider the namespace's visibility.
467 // Here we just want to note that we're in a visibility context
468 // which overrides any enclosing #pragma context, but doesn't itself
469 // contribute visibility.
470 PushPragmaVisibility(*this, NoVisibility, Loc);
473 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
475 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
479 // Pop visibility from stack
480 VisStack *Stack = static_cast<VisStack*>(VisContext);
482 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
483 bool StartsWithPragma = Back->first != NoVisibility;
484 if (StartsWithPragma && IsNamespaceEnd) {
485 Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
486 Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
488 // For better error recovery, eat all pushes inside the namespace.
491 Back = &Stack->back();
492 StartsWithPragma = Back->first != NoVisibility;
493 } while (StartsWithPragma);
494 } else if (!StartsWithPragma && !IsNamespaceEnd) {
495 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
496 Diag(Back->second, diag::note_surrounding_namespace_starts_here);
501 // To simplify the implementation, never keep around an empty stack.