SemaAttr.cpp revision 2a5c45b1ae4406459fbb39cb477951987c59cb0f
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/Sema/SemaInternal.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Lex/Preprocessor.h"
21using namespace clang;
22
23//===----------------------------------------------------------------------===//
24// Pragma 'pack' and 'options align'
25//===----------------------------------------------------------------------===//
26
27namespace {
28  struct PackStackEntry {
29    // We just use a sentinel to represent when the stack is set to mac68k
30    // alignment.
31    static const unsigned kMac68kAlignmentSentinel = ~0U;
32
33    unsigned Alignment;
34    IdentifierInfo *Name;
35  };
36
37  /// PragmaPackStack - Simple class to wrap the stack used by #pragma
38  /// pack.
39  class PragmaPackStack {
40    typedef std::vector<PackStackEntry> stack_ty;
41
42    /// Alignment - The current user specified alignment.
43    unsigned Alignment;
44
45    /// Stack - Entries in the #pragma pack stack, consisting of saved
46    /// alignments and optional names.
47    stack_ty Stack;
48
49  public:
50    PragmaPackStack() : Alignment(0) {}
51
52    void setAlignment(unsigned A) { Alignment = A; }
53    unsigned getAlignment() { return Alignment; }
54
55    /// push - Push the current alignment onto the stack, optionally
56    /// using the given \arg Name for the record, if non-zero.
57    void push(IdentifierInfo *Name) {
58      PackStackEntry PSE = { Alignment, Name };
59      Stack.push_back(PSE);
60    }
61
62    /// pop - Pop a record from the stack and restore the current
63    /// alignment to the previous value. If \arg Name is non-zero then
64    /// the first such named record is popped, otherwise the top record
65    /// is popped. Returns true if the pop succeeded.
66    bool pop(IdentifierInfo *Name, bool IsReset);
67  };
68}  // end anonymous namespace.
69
70bool PragmaPackStack::pop(IdentifierInfo *Name, bool IsReset) {
71  // If name is empty just pop top.
72  if (!Name) {
73    // An empty stack is a special case...
74    if (Stack.empty()) {
75      // If this isn't a reset, it is always an error.
76      if (!IsReset)
77        return false;
78
79      // Otherwise, it is an error only if some alignment has been set.
80      if (!Alignment)
81        return false;
82
83      // Otherwise, reset to the default alignment.
84      Alignment = 0;
85    } else {
86      Alignment = Stack.back().Alignment;
87      Stack.pop_back();
88    }
89
90    return true;
91  }
92
93  // Otherwise, find the named record.
94  for (unsigned i = Stack.size(); i != 0; ) {
95    --i;
96    if (Stack[i].Name == Name) {
97      // Found it, pop up to and including this record.
98      Alignment = Stack[i].Alignment;
99      Stack.erase(Stack.begin() + i, Stack.end());
100      return true;
101    }
102  }
103
104  return false;
105}
106
107
108/// FreePackedContext - Deallocate and null out PackContext.
109void Sema::FreePackedContext() {
110  delete static_cast<PragmaPackStack*>(PackContext);
111  PackContext = 0;
112}
113
114void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
115  // If there is no pack context, we don't need any attributes.
116  if (!PackContext)
117    return;
118
119  PragmaPackStack *Stack = static_cast<PragmaPackStack*>(PackContext);
120
121  // Otherwise, check to see if we need a max field alignment attribute.
122  if (unsigned Alignment = Stack->getAlignment()) {
123    if (Alignment == PackStackEntry::kMac68kAlignmentSentinel)
124      RD->addAttr(::new (Context) AlignMac68kAttr(SourceLocation(), Context));
125    else
126      RD->addAttr(::new (Context) MaxFieldAlignmentAttr(SourceLocation(),
127                                                        Context,
128                                                        Alignment * 8));
129  }
130}
131
132void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
133                                   SourceLocation PragmaLoc,
134                                   SourceLocation KindLoc) {
135  if (PackContext == 0)
136    PackContext = new PragmaPackStack();
137
138  PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
139
140  // Reset just pops the top of the stack, or resets the current alignment to
141  // default.
142  if (Kind == Sema::POAK_Reset) {
143    if (!Context->pop(0, /*IsReset=*/true)) {
144      Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
145        << "stack empty";
146    }
147    return;
148  }
149
150  switch (Kind) {
151    // For all targets we support native and natural are the same.
152    //
153    // FIXME: This is not true on Darwin/PPC.
154  case POAK_Native:
155  case POAK_Power:
156  case POAK_Natural:
157    Context->push(0);
158    Context->setAlignment(0);
159    break;
160
161    // Note that '#pragma options align=packed' is not equivalent to attribute
162    // packed, it has a different precedence relative to attribute aligned.
163  case POAK_Packed:
164    Context->push(0);
165    Context->setAlignment(1);
166    break;
167
168  case POAK_Mac68k:
169    // Check if the target supports this.
170    if (!PP.getTargetInfo().hasAlignMac68kSupport()) {
171      Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
172      return;
173    }
174    Context->push(0);
175    Context->setAlignment(PackStackEntry::kMac68kAlignmentSentinel);
176    break;
177
178  default:
179    Diag(PragmaLoc, diag::warn_pragma_options_align_unsupported_option)
180      << KindLoc;
181    break;
182  }
183}
184
185void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
186                           ExprTy *alignment, SourceLocation PragmaLoc,
187                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
188  Expr *Alignment = static_cast<Expr *>(alignment);
189
190  // If specified then alignment must be a "small" power of two.
191  unsigned AlignmentVal = 0;
192  if (Alignment) {
193    llvm::APSInt Val;
194
195    // pack(0) is like pack(), which just works out since that is what
196    // we use 0 for in PackAttr.
197    if (Alignment->isTypeDependent() ||
198        Alignment->isValueDependent() ||
199        !Alignment->isIntegerConstantExpr(Val, Context) ||
200        !(Val == 0 || Val.isPowerOf2()) ||
201        Val.getZExtValue() > 16) {
202      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
203      return; // Ignore
204    }
205
206    AlignmentVal = (unsigned) Val.getZExtValue();
207  }
208
209  if (PackContext == 0)
210    PackContext = new PragmaPackStack();
211
212  PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
213
214  switch (Kind) {
215  case Sema::PPK_Default: // pack([n])
216    Context->setAlignment(AlignmentVal);
217    break;
218
219  case Sema::PPK_Show: // pack(show)
220    // Show the current alignment, making sure to show the right value
221    // for the default.
222    AlignmentVal = Context->getAlignment();
223    // FIXME: This should come from the target.
224    if (AlignmentVal == 0)
225      AlignmentVal = 8;
226    if (AlignmentVal == PackStackEntry::kMac68kAlignmentSentinel)
227      Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
228    else
229      Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
230    break;
231
232  case Sema::PPK_Push: // pack(push [, id] [, [n])
233    Context->push(Name);
234    // Set the new alignment if specified.
235    if (Alignment)
236      Context->setAlignment(AlignmentVal);
237    break;
238
239  case Sema::PPK_Pop: // pack(pop [, id] [,  n])
240    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
241    // "#pragma pack(pop, identifier, n) is undefined"
242    if (Alignment && Name)
243      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
244
245    // Do the pop.
246    if (!Context->pop(Name, /*IsReset=*/false)) {
247      // If a name was specified then failure indicates the name
248      // wasn't found. Otherwise failure indicates the stack was
249      // empty.
250      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
251        << (Name ? "no record matching name" : "stack empty");
252
253      // FIXME: Warn about popping named records as MSVC does.
254    } else {
255      // Pop succeeded, set the new alignment if specified.
256      if (Alignment)
257        Context->setAlignment(AlignmentVal);
258    }
259    break;
260
261  default:
262    assert(0 && "Invalid #pragma pack kind.");
263  }
264}
265
266void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
267                             SourceLocation PragmaLoc) {
268
269  IdentifierInfo *Name = IdTok.getIdentifierInfo();
270  LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
271  LookupParsedName(Lookup, curScope, NULL, true);
272
273  if (Lookup.empty()) {
274    Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
275      << Name << SourceRange(IdTok.getLocation());
276    return;
277  }
278
279  VarDecl *VD = Lookup.getAsSingle<VarDecl>();
280  if (!VD) {
281    Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
282      << Name << SourceRange(IdTok.getLocation());
283    return;
284  }
285
286  // Warn if this was used before being marked unused.
287  if (VD->isUsed())
288    Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
289
290  VD->addAttr(::new (Context) UnusedAttr(IdTok.getLocation(), Context));
291}
292
293typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
294enum { NoVisibility = (unsigned) -1 };
295
296void Sema::AddPushedVisibilityAttribute(Decl *D) {
297  if (!VisContext)
298    return;
299
300  if (D->hasAttr<VisibilityAttr>())
301    return;
302
303  VisStack *Stack = static_cast<VisStack*>(VisContext);
304  unsigned rawType = Stack->back().first;
305  if (rawType == NoVisibility) return;
306
307  VisibilityAttr::VisibilityType type
308    = (VisibilityAttr::VisibilityType) rawType;
309  SourceLocation loc = Stack->back().second;
310
311  D->addAttr(::new (Context) VisibilityAttr(loc, Context, type));
312}
313
314/// FreeVisContext - Deallocate and null out VisContext.
315void Sema::FreeVisContext() {
316  delete static_cast<VisStack*>(VisContext);
317  VisContext = 0;
318}
319
320static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
321  // Put visibility on stack.
322  if (!S.VisContext)
323    S.VisContext = new VisStack;
324
325  VisStack *Stack = static_cast<VisStack*>(S.VisContext);
326  Stack->push_back(std::make_pair(type, loc));
327}
328
329void Sema::ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
330                                 SourceLocation PragmaLoc) {
331  if (IsPush) {
332    // Compute visibility to use.
333    VisibilityAttr::VisibilityType type;
334    if (VisType->isStr("default"))
335      type = VisibilityAttr::Default;
336    else if (VisType->isStr("hidden"))
337      type = VisibilityAttr::Hidden;
338    else if (VisType->isStr("internal"))
339      type = VisibilityAttr::Hidden; // FIXME
340    else if (VisType->isStr("protected"))
341      type = VisibilityAttr::Protected;
342    else {
343      Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) <<
344        VisType->getName();
345      return;
346    }
347    PushPragmaVisibility(*this, type, PragmaLoc);
348  } else {
349    PopPragmaVisibility();
350  }
351}
352
353void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr) {
354  // Visibility calculations will consider the namespace's visibility.
355  // Here we just want to note that we're in a visibility context
356  // which overrides any enclosing #pragma context, but doesn't itself
357  // contribute visibility.
358  PushPragmaVisibility(*this, NoVisibility, SourceLocation());
359}
360
361void Sema::PopPragmaVisibility() {
362  // Pop visibility from stack, if there is one on the stack.
363  if (VisContext) {
364    VisStack *Stack = static_cast<VisStack*>(VisContext);
365
366    Stack->pop_back();
367    // To simplify the implementation, never keep around an empty stack.
368    if (Stack->empty())
369      FreeVisContext();
370  }
371  // FIXME: Add diag for pop without push.
372}
373