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