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