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