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