AttributeList.h revision dc7c5ad7a15914b7ae24f31f18a20ad2f8ecd0bc
1//===--- AttributeList.h - Parsed attribute sets ----------------*- C++ -*-===//
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 defines the AttributeList class, which is used to collect
11// parsed attributes.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_ATTRLIST_H
16#define LLVM_CLANG_SEMA_ATTRLIST_H
17
18#include "llvm/Support/Allocator.h"
19#include "llvm/ADT/SmallVector.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/VersionTuple.h"
22#include <cassert>
23
24namespace clang {
25  class ASTContext;
26  class IdentifierInfo;
27  class Expr;
28
29/// \brief Represents information about a change in availability for
30/// an entity, which is part of the encoding of the 'availability'
31/// attribute.
32struct AvailabilityChange {
33  /// \brief The location of the keyword indicating the kind of change.
34  SourceLocation KeywordLoc;
35
36  /// \brief The version number at which the change occurred.
37  VersionTuple Version;
38
39  /// \brief The source range covering the version number.
40  SourceRange VersionRange;
41
42  /// \brief Determine whether this availability change is valid.
43  bool isValid() const { return !Version.empty(); }
44};
45
46/// AttributeList - Represents GCC's __attribute__ declaration. There are
47/// 4 forms of this construct...they are:
48///
49/// 1: __attribute__(( const )). ParmName/Args/NumArgs will all be unused.
50/// 2: __attribute__(( mode(byte) )). ParmName used, Args/NumArgs unused.
51/// 3: __attribute__(( format(printf, 1, 2) )). ParmName/Args/NumArgs all used.
52/// 4: __attribute__(( aligned(16) )). ParmName is unused, Args/Num used.
53///
54class AttributeList { // TODO: This should really be called ParsedAttribute
55private:
56  IdentifierInfo *AttrName;
57  IdentifierInfo *ScopeName;
58  IdentifierInfo *ParmName;
59  SourceLocation AttrLoc;
60  SourceLocation ScopeLoc;
61  SourceLocation ParmLoc;
62
63  /// The number of expression arguments this attribute has.
64  /// The expressions themselves are stored after the object.
65  unsigned NumArgs : 16;
66
67  /// True if Microsoft style: declspec(foo).
68  unsigned DeclspecAttribute : 1;
69
70  /// True if C++0x-style: [[foo]].
71  unsigned CXX0XAttribute : 1;
72
73  /// True if already diagnosed as invalid.
74  mutable unsigned Invalid : 1;
75
76  /// True if this has the extra information associated with an
77  /// availability attribute.
78  unsigned IsAvailability : 1;
79
80  unsigned AttrKind : 8;
81
82  /// \brief The location of the 'unavailable' keyword in an
83  /// availability attribute.
84  SourceLocation UnavailableLoc;
85
86  /// The next attribute in the current position.
87  AttributeList *NextInPosition;
88
89  /// The next attribute allocated in the current Pool.
90  AttributeList *NextInPool;
91
92  Expr **getArgsBuffer() {
93    return reinterpret_cast<Expr**>(this+1);
94  }
95  Expr * const *getArgsBuffer() const {
96    return reinterpret_cast<Expr* const *>(this+1);
97  }
98
99  enum AvailabilitySlot {
100    IntroducedSlot, DeprecatedSlot, ObsoletedSlot
101  };
102
103  AvailabilityChange &getAvailabilitySlot(AvailabilitySlot index) {
104    return reinterpret_cast<AvailabilityChange*>(this+1)[index];
105  }
106  const AvailabilityChange &getAvailabilitySlot(AvailabilitySlot index) const {
107    return reinterpret_cast<const AvailabilityChange*>(this+1)[index];
108  }
109
110  AttributeList(const AttributeList &); // DO NOT IMPLEMENT
111  void operator=(const AttributeList &); // DO NOT IMPLEMENT
112  void operator delete(void *); // DO NOT IMPLEMENT
113  ~AttributeList(); // DO NOT IMPLEMENT
114
115  size_t allocated_size() const;
116
117  AttributeList(IdentifierInfo *attrName, SourceLocation attrLoc,
118                IdentifierInfo *scopeName, SourceLocation scopeLoc,
119                IdentifierInfo *parmName, SourceLocation parmLoc,
120                Expr **args, unsigned numArgs,
121                bool declspec, bool cxx0x)
122    : AttrName(attrName), ScopeName(scopeName), ParmName(parmName),
123      AttrLoc(attrLoc), ScopeLoc(scopeLoc), ParmLoc(parmLoc),
124      NumArgs(numArgs),
125      DeclspecAttribute(declspec), CXX0XAttribute(cxx0x), Invalid(false),
126      IsAvailability(false), NextInPosition(0), NextInPool(0) {
127    if (numArgs) memcpy(getArgsBuffer(), args, numArgs * sizeof(Expr*));
128    AttrKind = getKind(getName());
129  }
130
131  AttributeList(IdentifierInfo *attrName, SourceLocation attrLoc,
132                IdentifierInfo *scopeName, SourceLocation scopeLoc,
133                IdentifierInfo *parmName, SourceLocation parmLoc,
134                const AvailabilityChange &introduced,
135                const AvailabilityChange &deprecated,
136                const AvailabilityChange &obsoleted,
137                SourceLocation unavailable,
138                bool declspec, bool cxx0x)
139    : AttrName(attrName), ScopeName(scopeName), ParmName(parmName),
140      AttrLoc(attrLoc), ScopeLoc(scopeLoc), ParmLoc(parmLoc),
141      NumArgs(0), DeclspecAttribute(declspec), CXX0XAttribute(cxx0x),
142      Invalid(false), IsAvailability(true), UnavailableLoc(unavailable),
143      NextInPosition(0), NextInPool(0) {
144    new (&getAvailabilitySlot(IntroducedSlot)) AvailabilityChange(introduced);
145    new (&getAvailabilitySlot(DeprecatedSlot)) AvailabilityChange(deprecated);
146    new (&getAvailabilitySlot(ObsoletedSlot)) AvailabilityChange(obsoleted);
147    AttrKind = getKind(getName());
148  }
149
150  friend class AttributePool;
151  friend class AttributeFactory;
152
153public:
154  enum Kind {             // Please keep this list alphabetized.
155    AT_address_space,
156    AT_alias,
157    AT_aligned,
158    AT_always_inline,
159    AT_analyzer_noreturn,
160    AT_annotate,
161    AT_arc_weakref_unavailable,
162    AT_availability,      // Clang-specific
163    AT_base_check,
164    AT_blocks,
165    AT_carries_dependency,
166    AT_cdecl,
167    AT_cf_consumed,             // Clang-specific.
168    AT_cf_returns_autoreleased, // Clang-specific.
169    AT_cf_returns_not_retained, // Clang-specific.
170    AT_cf_returns_retained,     // Clang-specific.
171    AT_cleanup,
172    AT_common,
173    AT_const,
174    AT_constant,
175    AT_constructor,
176    AT_deprecated,
177    AT_destructor,
178    AT_device,
179    AT_dllexport,
180    AT_dllimport,
181    AT_ext_vector_type,
182    AT_fastcall,
183    AT_format,
184    AT_format_arg,
185    AT_global,
186    AT_gnu_inline,
187    AT_host,
188    AT_IBAction,          // Clang-specific.
189    AT_IBOutlet,          // Clang-specific.
190    AT_IBOutletCollection, // Clang-specific.
191    AT_init_priority,
192    AT_launch_bounds,
193    AT_malloc,
194    AT_may_alias,
195    AT_mode,
196    AT_MsStruct,
197    AT_naked,
198    AT_neon_polyvector_type,    // Clang-specific.
199    AT_neon_vector_type,        // Clang-specific.
200    AT_no_instrument_function,
201    AT_nocommon,
202    AT_nodebug,
203    AT_noinline,
204    AT_nonnull,
205    AT_noreturn,
206    AT_nothrow,
207    AT_ns_consumed,             // Clang-specific.
208    AT_ns_consumes_self,        // Clang-specific.
209    AT_ns_returns_autoreleased, // Clang-specific.
210    AT_ns_returns_not_retained, // Clang-specific.
211    AT_ns_returns_retained,     // Clang-specific.
212    AT_nsobject,
213    AT_objc_exception,
214    AT_objc_gc,
215    AT_objc_method_family,
216    AT_objc_ownership,          // Clang-specific.
217    AT_objc_precise_lifetime,   // Clang-specific.
218    AT_objc_returns_inner_pointer, // Clang-specific.
219    AT_opencl_image_access,     // OpenCL-specific.
220    AT_opencl_kernel_function,  // OpenCL-specific.
221    AT_overloadable,       // Clang-specific.
222    AT_ownership_holds,    // Clang-specific.
223    AT_ownership_returns,  // Clang-specific.
224    AT_ownership_takes,    // Clang-specific.
225    AT_packed,
226    AT_pascal,
227    AT_pcs,  // ARM specific
228    AT_pure,
229    AT_regparm,
230    AT_reqd_wg_size,
231    AT_section,
232    AT_sentinel,
233    AT_shared,
234    AT_stdcall,
235    AT_thiscall,
236    AT_transparent_union,
237    AT_unavailable,
238    AT_unused,
239    AT_used,
240    AT_uuid,
241    AT_vecreturn,     // PS3 PPU-specific.
242    AT_vector_size,
243    AT_visibility,
244    AT_warn_unused_result,
245    AT_weak,
246    AT_weak_import,
247    AT_weakref,
248    IgnoredAttribute,
249    UnknownAttribute
250  };
251
252  IdentifierInfo *getName() const { return AttrName; }
253  SourceLocation getLoc() const { return AttrLoc; }
254
255  bool hasScope() const { return ScopeName; }
256  IdentifierInfo *getScopeName() const { return ScopeName; }
257  SourceLocation getScopeLoc() const { return ScopeLoc; }
258
259  IdentifierInfo *getParameterName() const { return ParmName; }
260  SourceLocation getParameterLoc() const { return ParmLoc; }
261
262  bool isDeclspecAttribute() const { return DeclspecAttribute; }
263  bool isCXX0XAttribute() const { return CXX0XAttribute; }
264
265  bool isInvalid() const { return Invalid; }
266  void setInvalid(bool b = true) const { Invalid = b; }
267
268  Kind getKind() const { return Kind(AttrKind); }
269  static Kind getKind(const IdentifierInfo *Name);
270
271  AttributeList *getNext() const { return NextInPosition; }
272  void setNext(AttributeList *N) { NextInPosition = N; }
273
274  /// getNumArgs - Return the number of actual arguments to this attribute.
275  unsigned getNumArgs() const { return NumArgs; }
276
277  /// hasParameterOrArguments - Return true if this attribute has a parameter,
278  /// or has a non empty argument expression list.
279  bool hasParameterOrArguments() const { return ParmName || NumArgs; }
280
281  /// getArg - Return the specified argument.
282  Expr *getArg(unsigned Arg) const {
283    assert(Arg < NumArgs && "Arg access out of range!");
284    return getArgsBuffer()[Arg];
285  }
286
287  class arg_iterator {
288    Expr * const *X;
289    unsigned Idx;
290  public:
291    arg_iterator(Expr * const *x, unsigned idx) : X(x), Idx(idx) {}
292
293    arg_iterator& operator++() {
294      ++Idx;
295      return *this;
296    }
297
298    bool operator==(const arg_iterator& I) const {
299      assert (X == I.X &&
300              "compared arg_iterators are for different argument lists");
301      return Idx == I.Idx;
302    }
303
304    bool operator!=(const arg_iterator& I) const {
305      return !operator==(I);
306    }
307
308    Expr* operator*() const {
309      return X[Idx];
310    }
311
312    unsigned getArgNum() const {
313      return Idx+1;
314    }
315  };
316
317  arg_iterator arg_begin() const {
318    return arg_iterator(getArgsBuffer(), 0);
319  }
320
321  arg_iterator arg_end() const {
322    return arg_iterator(getArgsBuffer(), NumArgs);
323  }
324
325  const AvailabilityChange &getAvailabilityIntroduced() const {
326    assert(getKind() == AT_availability && "Not an availability attribute");
327    return getAvailabilitySlot(IntroducedSlot);
328  }
329
330  const AvailabilityChange &getAvailabilityDeprecated() const {
331    assert(getKind() == AT_availability && "Not an availability attribute");
332    return getAvailabilitySlot(DeprecatedSlot);
333  }
334
335  const AvailabilityChange &getAvailabilityObsoleted() const {
336    assert(getKind() == AT_availability && "Not an availability attribute");
337    return getAvailabilitySlot(ObsoletedSlot);
338  }
339
340  SourceLocation getUnavailableLoc() const {
341    assert(getKind() == AT_availability && "Not an availability attribute");
342    return UnavailableLoc;
343  }
344};
345
346/// A factory, from which one makes pools, from which one creates
347/// individual attributes which are deallocated with the pool.
348///
349/// Note that it's tolerably cheap to create and destroy one of
350/// these as long as you don't actually allocate anything in it.
351class AttributeFactory {
352public:
353  enum {
354    /// The required allocation size of an availability attribute,
355    /// which we want to ensure is a multiple of sizeof(void*).
356    AvailabilityAllocSize =
357      sizeof(AttributeList)
358      + ((3 * sizeof(AvailabilityChange) + sizeof(void*) - 1)
359         / sizeof(void*) * sizeof(void*))
360  };
361
362private:
363  enum {
364    /// The number of free lists we want to be sure to support
365    /// inline.  This is just enough that availability attributes
366    /// don't surpass it.  It's actually very unlikely we'll see an
367    /// attribute that needs more than that; on x86-64 you'd need 10
368    /// expression arguments, and on i386 you'd need 19.
369    InlineFreeListsCapacity =
370      1 + (AvailabilityAllocSize - sizeof(AttributeList)) / sizeof(void*)
371  };
372
373  llvm::BumpPtrAllocator Alloc;
374
375  /// Free lists.  The index is determined by the following formula:
376  ///   (size - sizeof(AttributeList)) / sizeof(void*)
377  SmallVector<AttributeList*, InlineFreeListsCapacity> FreeLists;
378
379  // The following are the private interface used by AttributePool.
380  friend class AttributePool;
381
382  /// Allocate an attribute of the given size.
383  void *allocate(size_t size);
384
385  /// Reclaim all the attributes in the given pool chain, which is
386  /// non-empty.  Note that the current implementation is safe
387  /// against reclaiming things which were not actually allocated
388  /// with the allocator, although of course it's important to make
389  /// sure that their allocator lives at least as long as this one.
390  void reclaimPool(AttributeList *head);
391
392public:
393  AttributeFactory();
394  ~AttributeFactory();
395};
396
397class AttributePool {
398  AttributeFactory &Factory;
399  AttributeList *Head;
400
401  void *allocate(size_t size) {
402    return Factory.allocate(size);
403  }
404
405  AttributeList *add(AttributeList *attr) {
406    // We don't care about the order of the pool.
407    attr->NextInPool = Head;
408    Head = attr;
409    return attr;
410  }
411
412  void takePool(AttributeList *pool);
413
414public:
415  /// Create a new pool for a factory.
416  AttributePool(AttributeFactory &factory) : Factory(factory), Head(0) {}
417
418  /// Move the given pool's allocations to this pool.
419  AttributePool(AttributePool &pool) : Factory(pool.Factory), Head(pool.Head) {
420    pool.Head = 0;
421  }
422
423  AttributeFactory &getFactory() const { return Factory; }
424
425  void clear() {
426    if (Head) {
427      Factory.reclaimPool(Head);
428      Head = 0;
429    }
430  }
431
432  /// Take the given pool's allocations and add them to this pool.
433  void takeAllFrom(AttributePool &pool) {
434    if (pool.Head) {
435      takePool(pool.Head);
436      pool.Head = 0;
437    }
438  }
439
440  ~AttributePool() {
441    if (Head) Factory.reclaimPool(Head);
442  }
443
444  AttributeList *create(IdentifierInfo *attrName, SourceLocation attrLoc,
445                        IdentifierInfo *scopeName, SourceLocation scopeLoc,
446                        IdentifierInfo *parmName, SourceLocation parmLoc,
447                        Expr **args, unsigned numArgs,
448                        bool declspec = false, bool cxx0x = false) {
449    void *memory = allocate(sizeof(AttributeList)
450                            + numArgs * sizeof(Expr*));
451    return add(new (memory) AttributeList(attrName, attrLoc,
452                                          scopeName, scopeLoc,
453                                          parmName, parmLoc,
454                                          args, numArgs,
455                                          declspec, cxx0x));
456  }
457
458  AttributeList *create(IdentifierInfo *attrName, SourceLocation attrLoc,
459                        IdentifierInfo *scopeName, SourceLocation scopeLoc,
460                        IdentifierInfo *parmName, SourceLocation parmLoc,
461                        const AvailabilityChange &introduced,
462                        const AvailabilityChange &deprecated,
463                        const AvailabilityChange &obsoleted,
464                        SourceLocation unavailable,
465                        bool declspec = false, bool cxx0x = false) {
466    void *memory = allocate(AttributeFactory::AvailabilityAllocSize);
467    return add(new (memory) AttributeList(attrName, attrLoc,
468                                          scopeName, scopeLoc,
469                                          parmName, parmLoc,
470                                          introduced, deprecated, obsoleted,
471                                          unavailable,
472                                          declspec, cxx0x));
473  }
474
475  AttributeList *createIntegerAttribute(ASTContext &C, IdentifierInfo *Name,
476                                        SourceLocation TokLoc, int Arg);
477};
478
479/// addAttributeLists - Add two AttributeLists together
480/// The right-hand list is appended to the left-hand list, if any
481/// A pointer to the joined list is returned.
482/// Note: the lists are not left unmodified.
483inline AttributeList *addAttributeLists(AttributeList *Left,
484                                        AttributeList *Right) {
485  if (!Left)
486    return Right;
487
488  AttributeList *next = Left, *prev;
489  do {
490    prev = next;
491    next = next->getNext();
492  } while (next);
493  prev->setNext(Right);
494  return Left;
495}
496
497/// CXX0XAttributeList - A wrapper around a C++0x attribute list.
498/// Stores, in addition to the list proper, whether or not an actual list was
499/// (as opposed to an empty list, which may be ill-formed in some places) and
500/// the source range of the list.
501struct CXX0XAttributeList {
502  AttributeList *AttrList;
503  SourceRange Range;
504  bool HasAttr;
505  CXX0XAttributeList (AttributeList *attrList, SourceRange range, bool hasAttr)
506    : AttrList(attrList), Range(range), HasAttr (hasAttr) {
507  }
508  CXX0XAttributeList ()
509    : AttrList(0), Range(), HasAttr(false) {
510  }
511};
512
513/// ParsedAttributes - A collection of parsed attributes.  Currently
514/// we don't differentiate between the various attribute syntaxes,
515/// which is basically silly.
516///
517/// Right now this is a very lightweight container, but the expectation
518/// is that this will become significantly more serious.
519class ParsedAttributes {
520public:
521  ParsedAttributes(AttributeFactory &factory)
522    : pool(factory), list(0) {
523  }
524
525  ParsedAttributes(ParsedAttributes &attrs)
526    : pool(attrs.pool), list(attrs.list) {
527    attrs.list = 0;
528  }
529
530  AttributePool &getPool() const { return pool; }
531
532  bool empty() const { return list == 0; }
533
534  void add(AttributeList *newAttr) {
535    assert(newAttr);
536    assert(newAttr->getNext() == 0);
537    newAttr->setNext(list);
538    list = newAttr;
539  }
540
541  void addAll(AttributeList *newList) {
542    if (!newList) return;
543
544    AttributeList *lastInNewList = newList;
545    while (AttributeList *next = lastInNewList->getNext())
546      lastInNewList = next;
547
548    lastInNewList->setNext(list);
549    list = newList;
550  }
551
552  void set(AttributeList *newList) {
553    list = newList;
554  }
555
556  void takeAllFrom(ParsedAttributes &attrs) {
557    addAll(attrs.list);
558    attrs.list = 0;
559    pool.takeAllFrom(attrs.pool);
560  }
561
562  void clear() { list = 0; pool.clear(); }
563  AttributeList *getList() const { return list; }
564
565  /// Returns a reference to the attribute list.  Try not to introduce
566  /// dependencies on this method, it may not be long-lived.
567  AttributeList *&getListRef() { return list; }
568
569
570  AttributeList *addNew(IdentifierInfo *attrName, SourceLocation attrLoc,
571                        IdentifierInfo *scopeName, SourceLocation scopeLoc,
572                        IdentifierInfo *parmName, SourceLocation parmLoc,
573                        Expr **args, unsigned numArgs,
574                        bool declspec = false, bool cxx0x = false) {
575    AttributeList *attr =
576      pool.create(attrName, attrLoc, scopeName, scopeLoc, parmName, parmLoc,
577                  args, numArgs, declspec, cxx0x);
578    add(attr);
579    return attr;
580  }
581
582  AttributeList *addNew(IdentifierInfo *attrName, SourceLocation attrLoc,
583                        IdentifierInfo *scopeName, SourceLocation scopeLoc,
584                        IdentifierInfo *parmName, SourceLocation parmLoc,
585                        const AvailabilityChange &introduced,
586                        const AvailabilityChange &deprecated,
587                        const AvailabilityChange &obsoleted,
588                        SourceLocation unavailable,
589                        bool declspec = false, bool cxx0x = false) {
590    AttributeList *attr =
591      pool.create(attrName, attrLoc, scopeName, scopeLoc, parmName, parmLoc,
592                  introduced, deprecated, obsoleted, unavailable,
593                  declspec, cxx0x);
594    add(attr);
595    return attr;
596  }
597
598  AttributeList *addNewInteger(ASTContext &C, IdentifierInfo *name,
599                               SourceLocation loc, int arg) {
600    AttributeList *attr =
601      pool.createIntegerAttribute(C, name, loc, arg);
602    add(attr);
603    return attr;
604  }
605
606
607private:
608  mutable AttributePool pool;
609  AttributeList *list;
610};
611
612}  // end namespace clang
613
614#endif
615