]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaAttr.cpp
Merge lldb trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaAttr.cpp
1 //===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for non-trivial attributes and
11 // pragmas.
12 //
13 //===----------------------------------------------------------------------===//
14
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;
23
24 //===----------------------------------------------------------------------===//
25 // Pragma 'pack' and 'options align'
26 //===----------------------------------------------------------------------===//
27
28 Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
29                                                        StringRef SlotLabel,
30                                                        bool ShouldAct)
31     : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
32   if (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);
38   }
39 }
40
41 Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
42   if (ShouldAct) {
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);
48   }
49 }
50
51 void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
52   // If there is no pack value, we don't need any attributes.
53   if (!PackStack.CurrentValue)
54     return;
55
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));
60     else
61       RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
62                                                         Alignment * 8));
63   }
64 }
65
66 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
67   if (MSStructPragmaOn)
68     RD->addAttr(MSStructAttr::CreateImplicit(Context));
69
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)
74     RD->addAttr(
75         MSVtorDispAttr::CreateImplicit(Context, VtorDispStack.CurrentValue));
76 }
77
78 void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
79                                    SourceLocation PragmaLoc) {
80   PragmaMsStackAction Action = Sema::PSK_Reset;
81   unsigned Alignment = 0;
82   switch (Kind) {
83     // For all targets we support native and natural are the same.
84     //
85     // FIXME: This is not true on Darwin/PPC.
86   case POAK_Native:
87   case POAK_Power:
88   case POAK_Natural:
89     Action = Sema::PSK_Push_Set;
90     Alignment = 0;
91     break;
92
93     // Note that '#pragma options align=packed' is not equivalent to attribute
94     // packed, it has a different precedence relative to attribute aligned.
95   case POAK_Packed:
96     Action = Sema::PSK_Push_Set;
97     Alignment = 1;
98     break;
99
100   case POAK_Mac68k:
101     // Check if the target supports this.
102     if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
103       Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
104       return;
105     }
106     Action = Sema::PSK_Push_Set;
107     Alignment = Sema::kMac68kAlignmentSentinel;
108     break;
109
110   case POAK_Reset:
111     // Reset just pops the top of the stack, or resets the current alignment to
112     // default.
113     Action = Sema::PSK_Pop;
114     if (PackStack.Stack.empty()) {
115       if (PackStack.CurrentValue) {
116         Action = Sema::PSK_Reset;
117       } else {
118         Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
119             << "stack empty";
120         return;
121       }
122     }
123     break;
124   }
125
126   PackStack.Act(PragmaLoc, Action, StringRef(), Alignment);
127 }
128
129 void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
130                            StringRef SlotLabel, Expr *alignment) {
131   Expr *Alignment = static_cast<Expr *>(alignment);
132
133   // If specified then alignment must be a "small" power of two.
134   unsigned AlignmentVal = 0;
135   if (Alignment) {
136     llvm::APSInt Val;
137
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);
146       return; // Ignore
147     }
148
149     AlignmentVal = (unsigned) Val.getZExtValue();
150   }
151   if (Action == Sema::PSK_Show) {
152     // Show the current alignment, making sure to show the right value
153     // for the default.
154     // FIXME: This should come from the target.
155     AlignmentVal = PackStack.CurrentValue;
156     if (AlignmentVal == 0)
157       AlignmentVal = 8;
158     if (AlignmentVal == Sema::kMac68kAlignmentSentinel)
159       Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
160     else
161       Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
162   }
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";
170   }
171
172   PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal);
173 }
174
175 void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) { 
176   MSStructPragmaOn = (Kind == PMSST_ON);
177 }
178
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));
185 }
186
187 void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
188                                      StringRef Value) {
189   auto *PDMD = PragmaDetectMismatchDecl::Create(
190       Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
191   Context.getTranslationUnitDecl()->addDecl(PDMD);
192   Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
193 }
194
195 void Sema::ActOnPragmaMSPointersToMembers(
196     LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
197     SourceLocation PragmaLoc) {
198   MSPointerToMemberRepresentationMethod = RepresentationMethod;
199   ImplicitMSInheritanceAttrLoc = PragmaLoc;
200 }
201
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"
207                                                   << "stack empty";
208   VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
209 }
210
211 template<typename ValueType>
212 void Sema::PragmaStack<ValueType>::Act(SourceLocation PragmaLocation,
213                                        PragmaMsStackAction Action,
214                                        llvm::StringRef StackSlotLabel,
215                                        ValueType Value) {
216   if (Action == PSK_Reset) {
217     CurrentValue = DefaultValue;
218     CurrentPragmaLocation = PragmaLocation;
219     return;
220   }
221   if (Action & PSK_Push)
222     Stack.push_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation));
223   else if (Action & PSK_Pop) {
224     if (!StackSlotLabel.empty()) {
225       // If we've got a label, try to find it and jump there.
226       auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
227         return x.StackSlotLabel == StackSlotLabel;
228       });
229       // If we found the label so pop from there.
230       if (I != Stack.rend()) {
231         CurrentValue = I->Value;
232         CurrentPragmaLocation = I->PragmaLocation;
233         Stack.erase(std::prev(I.base()), Stack.end());
234       }
235     } else if (!Stack.empty()) {
236       // We don't have a label, just pop the last entry.
237       CurrentValue = Stack.back().Value;
238       CurrentPragmaLocation = Stack.back().PragmaLocation;
239       Stack.pop_back();
240     }
241   }
242   if (Action & PSK_Set) {
243     CurrentValue = Value;
244     CurrentPragmaLocation = PragmaLocation;
245   }
246 }
247
248 bool Sema::UnifySection(StringRef SectionName,
249                         int SectionFlags,
250                         DeclaratorDecl *Decl) {
251   auto Section = Context.SectionInfos.find(SectionName);
252   if (Section == Context.SectionInfos.end()) {
253     Context.SectionInfos[SectionName] =
254         ASTContext::SectionInfo(Decl, SourceLocation(), SectionFlags);
255     return false;
256   }
257   // A pre-declared section takes precedence w/o diagnostic.
258   if (Section->second.SectionFlags == SectionFlags ||
259       !(Section->second.SectionFlags & ASTContext::PSF_Implicit))
260     return false;
261   auto OtherDecl = Section->second.Decl;
262   Diag(Decl->getLocation(), diag::err_section_conflict)
263       << Decl << OtherDecl;
264   Diag(OtherDecl->getLocation(), diag::note_declared_at)
265       << OtherDecl->getName();
266   if (auto A = Decl->getAttr<SectionAttr>())
267     if (A->isImplicit())
268       Diag(A->getLocation(), diag::note_pragma_entered_here);
269   if (auto A = OtherDecl->getAttr<SectionAttr>())
270     if (A->isImplicit())
271       Diag(A->getLocation(), diag::note_pragma_entered_here);
272   return true;
273 }
274
275 bool Sema::UnifySection(StringRef SectionName,
276                         int SectionFlags,
277                         SourceLocation PragmaSectionLocation) {
278   auto Section = Context.SectionInfos.find(SectionName);
279   if (Section != Context.SectionInfos.end()) {
280     if (Section->second.SectionFlags == SectionFlags)
281       return false;
282     if (!(Section->second.SectionFlags & ASTContext::PSF_Implicit)) {
283       Diag(PragmaSectionLocation, diag::err_section_conflict)
284           << "this" << "a prior #pragma section";
285       Diag(Section->second.PragmaSectionLocation,
286            diag::note_pragma_entered_here);
287       return true;
288     }
289   }
290   Context.SectionInfos[SectionName] =
291       ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
292   return false;
293 }
294
295 /// \brief Called on well formed \#pragma bss_seg().
296 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
297                             PragmaMsStackAction Action,
298                             llvm::StringRef StackSlotLabel,
299                             StringLiteral *SegmentName,
300                             llvm::StringRef PragmaName) {
301   PragmaStack<StringLiteral *> *Stack =
302     llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
303         .Case("data_seg", &DataSegStack)
304         .Case("bss_seg", &BSSSegStack)
305         .Case("const_seg", &ConstSegStack)
306         .Case("code_seg", &CodeSegStack);
307   if (Action & PSK_Pop && Stack->Stack.empty())
308     Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
309         << "stack empty";
310   if (SegmentName &&
311       !checkSectionName(SegmentName->getLocStart(), SegmentName->getString()))
312     return;
313   Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
314 }
315
316 /// \brief Called on well formed \#pragma bss_seg().
317 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
318                                 int SectionFlags, StringLiteral *SegmentName) {
319   UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
320 }
321
322 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
323                                 StringLiteral *SegmentName) {
324   // There's no stack to maintain, so we just have a current section.  When we
325   // see the default section, reset our current section back to null so we stop
326   // tacking on unnecessary attributes.
327   CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
328   CurInitSegLoc = PragmaLocation;
329 }
330
331 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
332                              SourceLocation PragmaLoc) {
333
334   IdentifierInfo *Name = IdTok.getIdentifierInfo();
335   LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
336   LookupParsedName(Lookup, curScope, nullptr, true);
337
338   if (Lookup.empty()) {
339     Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
340       << Name << SourceRange(IdTok.getLocation());
341     return;
342   }
343
344   VarDecl *VD = Lookup.getAsSingle<VarDecl>();
345   if (!VD) {
346     Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
347       << Name << SourceRange(IdTok.getLocation());
348     return;
349   }
350
351   // Warn if this was used before being marked unused.
352   if (VD->isUsed())
353     Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
354
355   VD->addAttr(UnusedAttr::CreateImplicit(Context, UnusedAttr::GNU_unused,
356                                          IdTok.getLocation()));
357 }
358
359 void Sema::AddCFAuditedAttribute(Decl *D) {
360   SourceLocation Loc = PP.getPragmaARCCFCodeAuditedLoc();
361   if (!Loc.isValid()) return;
362
363   // Don't add a redundant or conflicting attribute.
364   if (D->hasAttr<CFAuditedTransferAttr>() ||
365       D->hasAttr<CFUnknownTransferAttr>())
366     return;
367
368   D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Loc));
369 }
370
371 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
372   if(On)
373     OptimizeOffPragmaLocation = SourceLocation();
374   else
375     OptimizeOffPragmaLocation = PragmaLoc;
376 }
377
378 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
379   // In the future, check other pragmas if they're implemented (e.g. pragma
380   // optimize 0 will probably map to this functionality too).
381   if(OptimizeOffPragmaLocation.isValid())
382     AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
383 }
384
385 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, 
386                                             SourceLocation Loc) {
387   // Don't add a conflicting attribute. No diagnostic is needed.
388   if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
389     return;
390
391   // Add attributes only if required. Optnone requires noinline as well, but if
392   // either is already present then don't bother adding them.
393   if (!FD->hasAttr<OptimizeNoneAttr>())
394     FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
395   if (!FD->hasAttr<NoInlineAttr>())
396     FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
397 }
398
399 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
400 enum : unsigned { NoVisibility = ~0U };
401
402 void Sema::AddPushedVisibilityAttribute(Decl *D) {
403   if (!VisContext)
404     return;
405
406   NamedDecl *ND = dyn_cast<NamedDecl>(D);
407   if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
408     return;
409
410   VisStack *Stack = static_cast<VisStack*>(VisContext);
411   unsigned rawType = Stack->back().first;
412   if (rawType == NoVisibility) return;
413
414   VisibilityAttr::VisibilityType type
415     = (VisibilityAttr::VisibilityType) rawType;
416   SourceLocation loc = Stack->back().second;
417
418   D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
419 }
420
421 /// FreeVisContext - Deallocate and null out VisContext.
422 void Sema::FreeVisContext() {
423   delete static_cast<VisStack*>(VisContext);
424   VisContext = nullptr;
425 }
426
427 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
428   // Put visibility on stack.
429   if (!S.VisContext)
430     S.VisContext = new VisStack;
431
432   VisStack *Stack = static_cast<VisStack*>(S.VisContext);
433   Stack->push_back(std::make_pair(type, loc));
434 }
435
436 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
437                                  SourceLocation PragmaLoc) {
438   if (VisType) {
439     // Compute visibility to use.
440     VisibilityAttr::VisibilityType T;
441     if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
442       Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
443       return;
444     }
445     PushPragmaVisibility(*this, T, PragmaLoc);
446   } else {
447     PopPragmaVisibility(false, PragmaLoc);
448   }
449 }
450
451 void Sema::ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC) {
452   switch (FPC) {
453   case LangOptions::FPC_On:
454     FPFeatures.setAllowFPContractWithinStatement();
455     break;
456   case LangOptions::FPC_Fast:
457     FPFeatures.setAllowFPContractAcrossStatement();
458     break;
459   case LangOptions::FPC_Off:
460     FPFeatures.setDisallowFPContract();
461     break;
462   }
463 }
464
465 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
466                                        SourceLocation Loc) {
467   // Visibility calculations will consider the namespace's visibility.
468   // Here we just want to note that we're in a visibility context
469   // which overrides any enclosing #pragma context, but doesn't itself
470   // contribute visibility.
471   PushPragmaVisibility(*this, NoVisibility, Loc);
472 }
473
474 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
475   if (!VisContext) {
476     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
477     return;
478   }
479
480   // Pop visibility from stack
481   VisStack *Stack = static_cast<VisStack*>(VisContext);
482
483   const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
484   bool StartsWithPragma = Back->first != NoVisibility;
485   if (StartsWithPragma && IsNamespaceEnd) {
486     Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
487     Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
488
489     // For better error recovery, eat all pushes inside the namespace.
490     do {
491       Stack->pop_back();
492       Back = &Stack->back();
493       StartsWithPragma = Back->first != NoVisibility;
494     } while (StartsWithPragma);
495   } else if (!StartsWithPragma && !IsNamespaceEnd) {
496     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
497     Diag(Back->second, diag::note_surrounding_namespace_starts_here);
498     return;
499   }
500
501   Stack->pop_back();
502   // To simplify the implementation, never keep around an empty stack.
503   if (Stack->empty())
504     FreeVisContext();
505 }