Attributes.h revision e1f95db4803a48a30fc2a1d5868281a87a36fb85
1//===-- llvm/Attributes.h - Container for Attributes ------------*- 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/// \file
11/// \brief This file contains the simple types necessary to represent the
12/// attributes associated with functions and their calls.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_IR_ATTRIBUTES_H
17#define LLVM_IR_ATTRIBUTES_H
18
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/Support/MathExtras.h"
23#include <cassert>
24#include <string>
25
26namespace llvm {
27
28class AttrBuilder;
29class AttributeImpl;
30class Constant;
31class LLVMContext;
32class Type;
33
34//===----------------------------------------------------------------------===//
35/// \class
36/// \brief Functions, function parameters, and return types can have attributes
37/// to indicate how they should be treated by optimizations and code
38/// generation. This class represents one of those attributes. It's light-weight
39/// and should be passed around by-value.
40class Attribute {
41public:
42  /// This enumeration lists the attributes that can be associated with
43  /// parameters, function results or the function itself.
44  ///
45  /// Note: uwtable is about the ABI or the user mandating an entry in the
46  /// unwind table. The nounwind attribute is about an exception passing by the
47  /// function.
48  ///
49  /// In a theoretical system that uses tables for profiling and sjlj for
50  /// exceptions, they would be fully independent. In a normal system that uses
51  /// tables for both, the semantics are:
52  ///
53  /// nil                = Needs an entry because an exception might pass by.
54  /// nounwind           = No need for an entry
55  /// uwtable            = Needs an entry because the ABI says so and because
56  ///                      an exception might pass by.
57  /// uwtable + nounwind = Needs an entry because the ABI says so.
58
59  enum AttrKind {
60    // IR-Level Attributes
61    None,                  ///< No attributes have been set
62    AddressSafety,         ///< Address safety checking is on.
63    Alignment,             ///< Alignment of parameter (5 bits)
64                           ///< stored as log2 of alignment with +1 bias
65                           ///< 0 means unaligned (different from align(1))
66    AlwaysInline,          ///< inline=always
67    ByVal,                 ///< Pass structure by value
68    InlineHint,            ///< Source said inlining was desirable
69    InReg,                 ///< Force argument to be passed in register
70    MinSize,               ///< Function must be optimized for size first
71    Naked,                 ///< Naked function
72    Nest,                  ///< Nested function static chain
73    NoAlias,               ///< Considered to not alias after call
74    NoCapture,             ///< Function creates no aliases of pointer
75    NoDuplicate,           ///< Call cannot be duplicated
76    NoImplicitFloat,       ///< Disable implicit floating point insts
77    NoInline,              ///< inline=never
78    NonLazyBind,           ///< Function is called early and/or
79                           ///< often, so lazy binding isn't worthwhile
80    NoRedZone,             ///< Disable redzone
81    NoReturn,              ///< Mark the function as not returning
82    NoUnwind,              ///< Function doesn't unwind stack
83    OptimizeForSize,       ///< opt_size
84    ReadNone,              ///< Function does not access memory
85    ReadOnly,              ///< Function only reads from memory
86    ReturnsTwice,          ///< Function can return twice
87    SExt,                  ///< Sign extended before/after call
88    StackAlignment,        ///< Alignment of stack for function (3 bits)
89                           ///< stored as log2 of alignment with +1 bias 0
90                           ///< means unaligned (different from
91                           ///< alignstack=(1))
92    StackProtect,          ///< Stack protection.
93    StackProtectReq,       ///< Stack protection required.
94    StackProtectStrong,    ///< Strong Stack protection.
95    StructRet,             ///< Hidden pointer to structure to return
96    UWTable,               ///< Function must be in a unwind table
97    ZExt,                  ///< Zero extended before/after call
98
99    EndAttrKinds,          ///< Sentinal value useful for loops
100
101    AttrKindEmptyKey,      ///< Empty key value for DenseMapInfo
102    AttrKindTombstoneKey   ///< Tombstone key value for DenseMapInfo
103  };
104private:
105  AttributeImpl *pImpl;
106  Attribute(AttributeImpl *A) : pImpl(A) {}
107public:
108  Attribute() : pImpl(0) {}
109
110  /// \brief Return a uniquified Attribute object. This takes the uniquified
111  /// value from the Builder and wraps it in the Attribute class.
112  static Attribute get(LLVMContext &Context, ArrayRef<AttrKind> Vals);
113  static Attribute get(LLVMContext &Context, AttrBuilder &B);
114
115  /// \brief Return true if the attribute is present.
116  bool hasAttribute(AttrKind Val) const;
117
118  /// \brief Return true if attributes exist
119  bool hasAttributes() const;
120
121  /// \brief Returns the alignment field of an attribute as a byte alignment
122  /// value.
123  unsigned getAlignment() const;
124
125  /// \brief Returns the stack alignment field of an attribute as a byte
126  /// alignment value.
127  unsigned getStackAlignment() const;
128
129  /// \brief Equality and non-equality query methods.
130  bool operator==(AttrKind K) const;
131  bool operator!=(AttrKind K) const;
132
133  bool operator<(Attribute A) const;
134
135  void Profile(FoldingSetNodeID &ID) const {
136    ID.AddPointer(pImpl);
137  }
138
139  // FIXME: Remove these 'operator' methods.
140  bool operator==(const Attribute &A) const {
141    return pImpl == A.pImpl;
142  }
143  bool operator!=(const Attribute &A) const {
144    return pImpl != A.pImpl;
145  }
146
147  uint64_t Raw() const;
148
149  /// \brief Which attributes cannot be applied to a type.
150  static Attribute typeIncompatible(Type *Ty);
151
152  /// \brief This returns an integer containing an encoding of all the LLVM
153  /// attributes found in the given attribute bitset.  Any change to this
154  /// encoding is a breaking change to bitcode compatibility.
155  static uint64_t encodeLLVMAttributesForBitcode(Attribute Attrs);
156
157  /// \brief This returns an attribute bitset containing the LLVM attributes
158  /// that have been decoded from the given integer.  This function must stay in
159  /// sync with 'encodeLLVMAttributesForBitcode'.
160  static Attribute decodeLLVMAttributesForBitcode(LLVMContext &C,
161                                                  uint64_t EncodedAttrs);
162
163  /// \brief The Attribute is converted to a string of equivalent mnemonic. This
164  /// is, presumably, for writing out the mnemonics for the assembly writer.
165  std::string getAsString() const;
166};
167
168//===----------------------------------------------------------------------===//
169/// \class
170/// \brief Provide DenseMapInfo for Attribute::AttrKinds. This is used by
171/// AttrBuilder.
172template<> struct DenseMapInfo<Attribute::AttrKind> {
173  static inline Attribute::AttrKind getEmptyKey() {
174    return Attribute::AttrKindEmptyKey;
175  }
176  static inline Attribute::AttrKind getTombstoneKey() {
177    return Attribute::AttrKindTombstoneKey;
178  }
179  static unsigned getHashValue(const Attribute::AttrKind &Val) {
180    return Val * 37U;
181  }
182  static bool isEqual(const Attribute::AttrKind &LHS,
183                      const Attribute::AttrKind &RHS) {
184    return LHS == RHS;
185  }
186};
187
188//===----------------------------------------------------------------------===//
189// AttributeSet Smart Pointer
190//===----------------------------------------------------------------------===//
191
192class AttrBuilder;
193class AttributeSetImpl;
194struct AttributeWithIndex;
195
196//===----------------------------------------------------------------------===//
197/// \class
198/// \brief This class manages the ref count for the opaque AttributeSetImpl
199/// object and provides accessors for it.
200class AttributeSet {
201public:
202  enum AttrIndex {
203    ReturnIndex = 0U,
204    FunctionIndex = ~0U
205  };
206private:
207  friend class AttrBuilder;
208
209  /// \brief The attributes that we are managing.  This can be null to represent
210  /// the empty attributes list.
211  AttributeSetImpl *AttrList;
212
213  /// \brief The attributes for the specified index are returned.  Attributes
214  /// for the result are denoted with Idx = 0.
215  Attribute getAttributes(unsigned Idx) const;
216
217  /// \brief Add the specified attribute at the specified index to this
218  /// attribute list.  Since attribute lists are immutable, this returns the new
219  /// list.
220  AttributeSet addAttr(LLVMContext &C, unsigned Idx, Attribute Attrs) const;
221
222  /// \brief Remove the specified attribute at the specified index from this
223  /// attribute list.  Since attribute lists are immutable, this returns the new
224  /// list.
225  AttributeSet removeAttr(LLVMContext &C, unsigned Idx, Attribute Attrs) const;
226
227  explicit AttributeSet(AttributeSetImpl *LI) : AttrList(LI) {}
228public:
229  AttributeSet() : AttrList(0) {}
230  AttributeSet(const AttributeSet &P) : AttrList(P.AttrList) {}
231  const AttributeSet &operator=(const AttributeSet &RHS);
232
233  //===--------------------------------------------------------------------===//
234  // Attribute List Construction and Mutation
235  //===--------------------------------------------------------------------===//
236
237  /// \brief Return an AttributeSet with the specified parameters in it.
238  static AttributeSet get(LLVMContext &C, ArrayRef<AttributeWithIndex> Attrs);
239  static AttributeSet get(LLVMContext &C, unsigned Idx,
240                          Attribute::AttrKind Kind);
241  static AttributeSet get(LLVMContext &C, unsigned Idx, AttrBuilder &B);
242
243  /// \brief Add an attribute to the attribute set at the given index. Since
244  /// attribute sets are immutable, this returns a new set.
245  AttributeSet addAttribute(LLVMContext &C, unsigned Idx,
246                            Attribute::AttrKind Attr) const;
247
248  /// \brief Add attributes to the attribute set at the given index. Since
249  /// attribute sets are immutable, this returns a new set.
250  AttributeSet addAttributes(LLVMContext &C, unsigned Idx,
251                             AttributeSet Attrs) const;
252
253  /// \brief Add return attributes to this attribute set. Since attribute sets
254  /// are immutable, this returns a new set.
255  AttributeSet addRetAttributes(LLVMContext &C, AttributeSet Attrs) const {
256    return addAttributes(C, ReturnIndex, Attrs);
257  }
258
259  /// \brief Add function attributes to this attribute set. Since attribute sets
260  /// are immutable, this returns a new set.
261  AttributeSet addFnAttributes(LLVMContext &C, AttributeSet Attrs) const {
262    return addAttributes(C, FunctionIndex, Attrs);
263  }
264
265  /// \brief Remove the specified attribute at the specified index from this
266  /// attribute list. Since attribute lists are immutable, this returns the new
267  /// list.
268  AttributeSet removeAttribute(LLVMContext &C, unsigned Idx,
269                               Attribute::AttrKind Attr) const;
270
271  /// \brief Remove the specified attributes at the specified index from this
272  /// attribute list. Since attribute lists are immutable, this returns the new
273  /// list.
274  AttributeSet removeAttributes(LLVMContext &C, unsigned Idx,
275                                AttributeSet Attrs) const;
276
277  //===--------------------------------------------------------------------===//
278  // Attribute List Accessors
279  //===--------------------------------------------------------------------===//
280
281  /// \brief The attributes for the specified index are returned.
282  AttributeSet getParamAttributes(unsigned Idx) const;
283
284  /// \brief The attributes for the ret value are returned.
285  AttributeSet getRetAttributes() const;
286
287  /// \brief The function attributes are returned.
288  AttributeSet getFnAttributes() const;
289
290  /// \brief Return the alignment for the specified function parameter.
291  unsigned getParamAlignment(unsigned Idx) const;
292
293  /// \brief Return true if the attribute exists at the given index.
294  bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
295
296  /// \brief Return true if attribute exists at the given index.
297  bool hasAttributes(unsigned Index) const;
298
299  /// \brief Get the stack alignment.
300  unsigned getStackAlignment(unsigned Index) const;
301
302  /// \brief Return the attributes at the index as a string.
303  std::string getAsString(unsigned Index) const;
304
305  uint64_t Raw(unsigned Index) const;
306
307  /// \brief Return true if the specified attribute is set for at least one
308  /// parameter or for the return value.
309  bool hasAttrSomewhere(Attribute::AttrKind Attr) const;
310
311  /// operator==/!= - Provide equality predicates.
312  bool operator==(const AttributeSet &RHS) const {
313    return AttrList == RHS.AttrList;
314  }
315  bool operator!=(const AttributeSet &RHS) const {
316    return AttrList != RHS.AttrList;
317  }
318
319  //===--------------------------------------------------------------------===//
320  // Attribute List Introspection
321  //===--------------------------------------------------------------------===//
322
323  /// \brief Return a raw pointer that uniquely identifies this attribute list.
324  void *getRawPointer() const {
325    return AttrList;
326  }
327
328  // Attributes are stored as a dense set of slots, where there is one slot for
329  // each argument that has an attribute.  This allows walking over the dense
330  // set instead of walking the sparse list of attributes.
331
332  /// \brief Return true if there are no attributes.
333  bool isEmpty() const {
334    return AttrList == 0;
335  }
336
337  /// \brief Return the number of slots used in this attribute list.  This is
338  /// the number of arguments that have an attribute set on them (including the
339  /// function itself).
340  unsigned getNumSlots() const;
341
342  /// \brief Return the index for the given slot.
343  unsigned getSlotIndex(unsigned Slot) const;
344
345  /// \brief Return the AttributeWithIndex at the specified slot.  This holds a
346  /// index number plus a set of attributes.
347  const AttributeWithIndex &getSlot(unsigned Slot) const;
348
349  void dump() const;
350};
351
352//===----------------------------------------------------------------------===//
353/// \class
354/// \brief This is just a pair of values to associate a set of attributes with
355/// an index.
356struct AttributeWithIndex {
357  Attribute Attrs;  ///< The attributes that are set, or'd together.
358  unsigned Index;   ///< Index of the parameter for which the attributes apply.
359
360  // FIXME: These methods all need to be revised. The first one is temporary.
361  static AttributeWithIndex get(LLVMContext &C, unsigned Idx, AttributeSet AS);
362  static AttributeWithIndex get(LLVMContext &C, unsigned Idx,
363                                ArrayRef<Attribute::AttrKind> Attrs) {
364    return get(Idx, Attribute::get(C, Attrs));
365  }
366  static AttributeWithIndex get(unsigned Idx, Attribute Attrs) {
367    AttributeWithIndex P;
368    P.Index = Idx;
369    P.Attrs = Attrs;
370    return P;
371  }
372};
373
374//===----------------------------------------------------------------------===//
375/// \class
376/// \brief This class is used in conjunction with the Attribute::get method to
377/// create an Attribute object. The object itself is uniquified. The Builder's
378/// value, however, is not. So this can be used as a quick way to test for
379/// equality, presence of attributes, etc.
380class AttrBuilder {
381  DenseSet<Attribute::AttrKind> Attrs;
382  uint64_t Alignment;
383  uint64_t StackAlignment;
384public:
385  AttrBuilder() : Alignment(0), StackAlignment(0) {}
386  explicit AttrBuilder(uint64_t B) : Alignment(0), StackAlignment(0) {
387    addRawValue(B);
388  }
389  AttrBuilder(const Attribute &A) : Alignment(0), StackAlignment(0) {
390    addAttributes(A);
391  }
392  AttrBuilder(AttributeSet AS, unsigned Idx);
393
394  void clear();
395
396  /// \brief Add an attribute to the builder.
397  AttrBuilder &addAttribute(Attribute::AttrKind Val);
398
399  /// \brief Remove an attribute from the builder.
400  AttrBuilder &removeAttribute(Attribute::AttrKind Val);
401
402  /// \brief Add the attributes from A to the builder.
403  AttrBuilder &addAttributes(const Attribute &A);
404
405  /// \brief Remove the attributes from A from the builder.
406  AttrBuilder &removeAttributes(const Attribute &A);
407
408  /// \brief Return true if the builder has the specified attribute.
409  bool contains(Attribute::AttrKind A) const;
410
411  /// \brief Return true if the builder has IR-level attributes.
412  bool hasAttributes() const;
413
414  /// \brief Return true if the builder has any attribute that's in the
415  /// specified attribute.
416  bool hasAttributes(const Attribute &A) const;
417
418  /// \brief Return true if the builder has an alignment attribute.
419  bool hasAlignmentAttr() const;
420
421  /// \brief Retrieve the alignment attribute, if it exists.
422  uint64_t getAlignment() const { return Alignment; }
423
424  /// \brief Retrieve the stack alignment attribute, if it exists.
425  uint64_t getStackAlignment() const { return StackAlignment; }
426
427  /// \brief This turns an int alignment (which must be a power of 2) into the
428  /// form used internally in Attribute.
429  AttrBuilder &addAlignmentAttr(unsigned Align);
430
431  /// \brief This turns an int stack alignment (which must be a power of 2) into
432  /// the form used internally in Attribute.
433  AttrBuilder &addStackAlignmentAttr(unsigned Align);
434
435  typedef DenseSet<Attribute::AttrKind>::iterator       iterator;
436  typedef DenseSet<Attribute::AttrKind>::const_iterator const_iterator;
437
438  iterator begin() { return Attrs.begin(); }
439  iterator end()   { return Attrs.end(); }
440
441  const_iterator begin() const { return Attrs.begin(); }
442  const_iterator end() const   { return Attrs.end(); }
443
444  /// \brief Add the raw value to the internal representation.
445  ///
446  /// N.B. This should be used ONLY for decoding LLVM bitcode!
447  AttrBuilder &addRawValue(uint64_t Val);
448
449  /// \brief Remove attributes that are used on functions only.
450  void removeFunctionOnlyAttrs() {
451    removeAttribute(Attribute::NoReturn)
452      .removeAttribute(Attribute::NoUnwind)
453      .removeAttribute(Attribute::ReadNone)
454      .removeAttribute(Attribute::ReadOnly)
455      .removeAttribute(Attribute::NoInline)
456      .removeAttribute(Attribute::AlwaysInline)
457      .removeAttribute(Attribute::OptimizeForSize)
458      .removeAttribute(Attribute::StackProtect)
459      .removeAttribute(Attribute::StackProtectReq)
460      .removeAttribute(Attribute::StackProtectStrong)
461      .removeAttribute(Attribute::NoRedZone)
462      .removeAttribute(Attribute::NoImplicitFloat)
463      .removeAttribute(Attribute::Naked)
464      .removeAttribute(Attribute::InlineHint)
465      .removeAttribute(Attribute::StackAlignment)
466      .removeAttribute(Attribute::UWTable)
467      .removeAttribute(Attribute::NonLazyBind)
468      .removeAttribute(Attribute::ReturnsTwice)
469      .removeAttribute(Attribute::AddressSafety)
470      .removeAttribute(Attribute::MinSize)
471      .removeAttribute(Attribute::NoDuplicate);
472  }
473
474  uint64_t Raw() const;
475
476  bool operator==(const AttrBuilder &B);
477  bool operator!=(const AttrBuilder &B) {
478    return !(*this == B);
479  }
480};
481
482} // end llvm namespace
483
484#endif
485