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