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    Dereferenceable,       ///< Pointer is known to be dereferenceable
92    DereferenceableOrNull, ///< Pointer is either null or dereferenceable
93    NoRedZone,             ///< Disable redzone
94    NoReturn,              ///< Mark the function as not returning
95    NoUnwind,              ///< Function doesn't unwind stack
96    OptimizeForSize,       ///< opt_size
97    OptimizeNone,          ///< Function must not be optimized.
98    ReadNone,              ///< Function does not access memory
99    ReadOnly,              ///< Function only reads from memory
100    Returned,              ///< Return value is always equal to this argument
101    ReturnsTwice,          ///< Function can return twice
102    SExt,                  ///< Sign extended before/after call
103    StackAlignment,        ///< Alignment of stack for function (3 bits)
104                           ///< stored as log2 of alignment with +1 bias 0
105                           ///< means unaligned (different from
106                           ///< alignstack=(1))
107    StackProtect,          ///< Stack protection.
108    StackProtectReq,       ///< Stack protection required.
109    StackProtectStrong,    ///< Strong Stack protection.
110    StructRet,             ///< Hidden pointer to structure to return
111    SanitizeAddress,       ///< AddressSanitizer is on.
112    SanitizeThread,        ///< ThreadSanitizer is on.
113    SanitizeMemory,        ///< MemorySanitizer is on.
114    UWTable,               ///< Function must be in a unwind table
115    ZExt,                  ///< Zero extended before/after call
116
117    EndAttrKinds           ///< Sentinal value useful for loops
118  };
119private:
120  AttributeImpl *pImpl;
121  Attribute(AttributeImpl *A) : pImpl(A) {}
122public:
123  Attribute() : pImpl(nullptr) {}
124
125  //===--------------------------------------------------------------------===//
126  // Attribute Construction
127  //===--------------------------------------------------------------------===//
128
129  /// \brief Return a uniquified Attribute object.
130  static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val = 0);
131  static Attribute get(LLVMContext &Context, StringRef Kind,
132                       StringRef Val = StringRef());
133
134  /// \brief Return a uniquified Attribute object that has the specific
135  /// alignment set.
136  static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align);
137  static Attribute getWithStackAlignment(LLVMContext &Context, uint64_t Align);
138  static Attribute getWithDereferenceableBytes(LLVMContext &Context,
139                                              uint64_t Bytes);
140  static Attribute getWithDereferenceableOrNullBytes(LLVMContext &Context,
141                                                     uint64_t Bytes);
142
143  //===--------------------------------------------------------------------===//
144  // Attribute Accessors
145  //===--------------------------------------------------------------------===//
146
147  /// \brief Return true if the attribute is an Attribute::AttrKind type.
148  bool isEnumAttribute() const;
149
150  /// \brief Return true if the attribute is an integer attribute.
151  bool isIntAttribute() const;
152
153  /// \brief Return true if the attribute is a string (target-dependent)
154  /// attribute.
155  bool isStringAttribute() const;
156
157  /// \brief Return true if the attribute is present.
158  bool hasAttribute(AttrKind Val) const;
159
160  /// \brief Return true if the target-dependent attribute is present.
161  bool hasAttribute(StringRef Val) const;
162
163  /// \brief Return the attribute's kind as an enum (Attribute::AttrKind). This
164  /// requires the attribute to be an enum or alignment attribute.
165  Attribute::AttrKind getKindAsEnum() const;
166
167  /// \brief Return the attribute's value as an integer. This requires that the
168  /// attribute be an alignment attribute.
169  uint64_t getValueAsInt() const;
170
171  /// \brief Return the attribute's kind as a string. This requires the
172  /// attribute to be a string attribute.
173  StringRef getKindAsString() const;
174
175  /// \brief Return the attribute's value as a string. This requires the
176  /// attribute to be a string attribute.
177  StringRef getValueAsString() const;
178
179  /// \brief Returns the alignment field of an attribute as a byte alignment
180  /// value.
181  unsigned getAlignment() const;
182
183  /// \brief Returns the stack alignment field of an attribute as a byte
184  /// alignment value.
185  unsigned getStackAlignment() const;
186
187  /// \brief Returns the number of dereferenceable bytes from the
188  /// dereferenceable attribute (or zero if unknown).
189  uint64_t getDereferenceableBytes() const;
190
191  /// \brief Returns the number of dereferenceable_or_null bytes from the
192  /// dereferenceable_or_null attribute (or zero if unknown).
193  uint64_t getDereferenceableOrNullBytes() const;
194
195  /// \brief The Attribute is converted to a string of equivalent mnemonic. This
196  /// is, presumably, for writing out the mnemonics for the assembly writer.
197  std::string getAsString(bool InAttrGrp = false) const;
198
199  /// \brief Equality and non-equality operators.
200  bool operator==(Attribute A) const { return pImpl == A.pImpl; }
201  bool operator!=(Attribute A) const { return pImpl != A.pImpl; }
202
203  /// \brief Less-than operator. Useful for sorting the attributes list.
204  bool operator<(Attribute A) const;
205
206  void Profile(FoldingSetNodeID &ID) const {
207    ID.AddPointer(pImpl);
208  }
209};
210
211//===----------------------------------------------------------------------===//
212/// \class
213/// \brief This class holds the attributes for a function, its return value, and
214/// its parameters. You access the attributes for each of them via an index into
215/// the AttributeSet object. The function attributes are at index
216/// `AttributeSet::FunctionIndex', the return value is at index
217/// `AttributeSet::ReturnIndex', and the attributes for the parameters start at
218/// index `1'.
219class AttributeSet {
220public:
221  enum AttrIndex : unsigned {
222    ReturnIndex = 0U,
223    FunctionIndex = ~0U
224  };
225private:
226  friend class AttrBuilder;
227  friend class AttributeSetImpl;
228  template <typename Ty> friend struct DenseMapInfo;
229
230  /// \brief The attributes that we are managing. This can be null to represent
231  /// the empty attributes list.
232  AttributeSetImpl *pImpl;
233
234  /// \brief The attributes for the specified index are returned.
235  AttributeSetNode *getAttributes(unsigned Index) const;
236
237  /// \brief Create an AttributeSet with the specified parameters in it.
238  static AttributeSet get(LLVMContext &C,
239                          ArrayRef<std::pair<unsigned, Attribute> > Attrs);
240  static AttributeSet get(LLVMContext &C,
241                          ArrayRef<std::pair<unsigned,
242                                             AttributeSetNode*> > Attrs);
243
244  static AttributeSet getImpl(LLVMContext &C,
245                              ArrayRef<std::pair<unsigned,
246                                                 AttributeSetNode*> > Attrs);
247
248
249  explicit AttributeSet(AttributeSetImpl *LI) : pImpl(LI) {}
250public:
251  AttributeSet() : pImpl(nullptr) {}
252
253  //===--------------------------------------------------------------------===//
254  // AttributeSet Construction and Mutation
255  //===--------------------------------------------------------------------===//
256
257  /// \brief Return an AttributeSet with the specified parameters in it.
258  static AttributeSet get(LLVMContext &C, ArrayRef<AttributeSet> Attrs);
259  static AttributeSet get(LLVMContext &C, unsigned Index,
260                          ArrayRef<Attribute::AttrKind> Kind);
261  static AttributeSet get(LLVMContext &C, unsigned Index, const AttrBuilder &B);
262
263  /// \brief Add an attribute to the attribute set at the given index. Since
264  /// attribute sets are immutable, this returns a new set.
265  AttributeSet addAttribute(LLVMContext &C, unsigned Index,
266                            Attribute::AttrKind Attr) const;
267
268  /// \brief Add an attribute to the attribute set at the given index. Since
269  /// attribute sets are immutable, this returns a new set.
270  AttributeSet addAttribute(LLVMContext &C, unsigned Index,
271                            StringRef Kind) const;
272  AttributeSet addAttribute(LLVMContext &C, unsigned Index,
273                            StringRef Kind, StringRef Value) const;
274
275  /// \brief Add attributes to the attribute set at the given index. Since
276  /// attribute sets are immutable, this returns a new set.
277  AttributeSet addAttributes(LLVMContext &C, unsigned Index,
278                             AttributeSet Attrs) const;
279
280  /// \brief Remove the specified attribute at the specified index from this
281  /// attribute list. Since attribute lists are immutable, this returns the new
282  /// list.
283  AttributeSet removeAttribute(LLVMContext &C, unsigned Index,
284                               Attribute::AttrKind Attr) const;
285
286  /// \brief Remove the specified attributes at the specified index from this
287  /// attribute list. Since attribute lists are immutable, this returns the new
288  /// list.
289  AttributeSet removeAttributes(LLVMContext &C, unsigned Index,
290                                AttributeSet Attrs) const;
291
292  /// \brief Add the dereferenceable attribute to the attribute set at the given
293  /// index. Since attribute sets are immutable, this returns a new set.
294  AttributeSet addDereferenceableAttr(LLVMContext &C, unsigned Index,
295                                      uint64_t Bytes) const;
296
297  /// \brief Add the dereferenceable_or_null attribute to the attribute set at
298  /// the given index. Since attribute sets are immutable, this returns a new
299  /// set.
300  AttributeSet addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index,
301                                            uint64_t Bytes) const;
302
303  //===--------------------------------------------------------------------===//
304  // AttributeSet Accessors
305  //===--------------------------------------------------------------------===//
306
307  /// \brief Retrieve the LLVM context.
308  LLVMContext &getContext() const;
309
310  /// \brief The attributes for the specified index are returned.
311  AttributeSet getParamAttributes(unsigned Index) const;
312
313  /// \brief The attributes for the ret value are returned.
314  AttributeSet getRetAttributes() const;
315
316  /// \brief The function attributes are returned.
317  AttributeSet getFnAttributes() const;
318
319  /// \brief Return true if the attribute exists at the given index.
320  bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
321
322  /// \brief Return true if the attribute exists at the given index.
323  bool hasAttribute(unsigned Index, StringRef Kind) const;
324
325  /// \brief Return true if attribute exists at the given index.
326  bool hasAttributes(unsigned Index) const;
327
328  /// \brief Return true if the specified attribute is set for at least one
329  /// parameter or for the return value.
330  bool hasAttrSomewhere(Attribute::AttrKind Attr) const;
331
332  /// \brief Return the attribute object that exists at the given index.
333  Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const;
334
335  /// \brief Return the attribute object that exists at the given index.
336  Attribute getAttribute(unsigned Index, StringRef Kind) const;
337
338  /// \brief Return the alignment for the specified function parameter.
339  unsigned getParamAlignment(unsigned Index) const;
340
341  /// \brief Get the stack alignment.
342  unsigned getStackAlignment(unsigned Index) const;
343
344  /// \brief Get the number of dereferenceable bytes (or zero if unknown).
345  uint64_t getDereferenceableBytes(unsigned Index) const;
346
347  /// \brief Get the number of dereferenceable_or_null bytes (or zero if
348  /// unknown).
349  uint64_t getDereferenceableOrNullBytes(unsigned Index) const;
350
351  /// \brief Return the attributes at the index as a string.
352  std::string getAsString(unsigned Index, bool InAttrGrp = false) const;
353
354  typedef ArrayRef<Attribute>::iterator iterator;
355
356  iterator begin(unsigned Slot) const;
357  iterator end(unsigned Slot) const;
358
359  /// operator==/!= - Provide equality predicates.
360  bool operator==(const AttributeSet &RHS) const {
361    return pImpl == RHS.pImpl;
362  }
363  bool operator!=(const AttributeSet &RHS) const {
364    return pImpl != RHS.pImpl;
365  }
366
367  //===--------------------------------------------------------------------===//
368  // AttributeSet Introspection
369  //===--------------------------------------------------------------------===//
370
371  // FIXME: Remove this.
372  uint64_t Raw(unsigned Index) const;
373
374  /// \brief Return a raw pointer that uniquely identifies this attribute list.
375  void *getRawPointer() const {
376    return pImpl;
377  }
378
379  /// \brief Return true if there are no attributes.
380  bool isEmpty() const {
381    return getNumSlots() == 0;
382  }
383
384  /// \brief Return the number of slots used in this attribute list.  This is
385  /// the number of arguments that have an attribute set on them (including the
386  /// function itself).
387  unsigned getNumSlots() const;
388
389  /// \brief Return the index for the given slot.
390  unsigned getSlotIndex(unsigned Slot) const;
391
392  /// \brief Return the attributes at the given slot.
393  AttributeSet getSlotAttributes(unsigned Slot) const;
394
395  void dump() const;
396};
397
398//===----------------------------------------------------------------------===//
399/// \class
400/// \brief Provide DenseMapInfo for AttributeSet.
401template<> struct DenseMapInfo<AttributeSet> {
402  static inline AttributeSet getEmptyKey() {
403    uintptr_t Val = static_cast<uintptr_t>(-1);
404    Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
405    return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
406  }
407  static inline AttributeSet getTombstoneKey() {
408    uintptr_t Val = static_cast<uintptr_t>(-2);
409    Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
410    return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
411  }
412  static unsigned getHashValue(AttributeSet AS) {
413    return (unsigned((uintptr_t)AS.pImpl) >> 4) ^
414           (unsigned((uintptr_t)AS.pImpl) >> 9);
415  }
416  static bool isEqual(AttributeSet LHS, AttributeSet RHS) { return LHS == RHS; }
417};
418
419//===----------------------------------------------------------------------===//
420/// \class
421/// \brief This class is used in conjunction with the Attribute::get method to
422/// create an Attribute object. The object itself is uniquified. The Builder's
423/// value, however, is not. So this can be used as a quick way to test for
424/// equality, presence of attributes, etc.
425class AttrBuilder {
426  std::bitset<Attribute::EndAttrKinds> Attrs;
427  std::map<std::string, std::string> TargetDepAttrs;
428  uint64_t Alignment;
429  uint64_t StackAlignment;
430  uint64_t DerefBytes;
431  uint64_t DerefOrNullBytes;
432public:
433  AttrBuilder() : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {}
434  explicit AttrBuilder(uint64_t Val)
435    : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
436    addRawValue(Val);
437  }
438  AttrBuilder(const Attribute &A)
439    : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
440    addAttribute(A);
441  }
442  AttrBuilder(AttributeSet AS, unsigned Idx);
443
444  void clear();
445
446  /// \brief Add an attribute to the builder.
447  AttrBuilder &addAttribute(Attribute::AttrKind Val);
448
449  /// \brief Add the Attribute object to the builder.
450  AttrBuilder &addAttribute(Attribute A);
451
452  /// \brief Add the target-dependent attribute to the builder.
453  AttrBuilder &addAttribute(StringRef A, StringRef V = StringRef());
454
455  /// \brief Remove an attribute from the builder.
456  AttrBuilder &removeAttribute(Attribute::AttrKind Val);
457
458  /// \brief Remove the attributes from the builder.
459  AttrBuilder &removeAttributes(AttributeSet A, uint64_t Index);
460
461  /// \brief Remove the target-dependent attribute to the builder.
462  AttrBuilder &removeAttribute(StringRef A);
463
464  /// \brief Add the attributes from the builder.
465  AttrBuilder &merge(const AttrBuilder &B);
466
467  /// \brief Return true if the builder has the specified attribute.
468  bool contains(Attribute::AttrKind A) const {
469    assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!");
470    return Attrs[A];
471  }
472
473  /// \brief Return true if the builder has the specified target-dependent
474  /// attribute.
475  bool contains(StringRef A) const;
476
477  /// \brief Return true if the builder has IR-level attributes.
478  bool hasAttributes() const;
479
480  /// \brief Return true if the builder has any attribute that's in the
481  /// specified attribute.
482  bool hasAttributes(AttributeSet A, uint64_t Index) const;
483
484  /// \brief Return true if the builder has an alignment attribute.
485  bool hasAlignmentAttr() const;
486
487  /// \brief Retrieve the alignment attribute, if it exists.
488  uint64_t getAlignment() const { return Alignment; }
489
490  /// \brief Retrieve the stack alignment attribute, if it exists.
491  uint64_t getStackAlignment() const { return StackAlignment; }
492
493  /// \brief Retrieve the number of dereferenceable bytes, if the dereferenceable
494  /// attribute exists (zero is returned otherwise).
495  uint64_t getDereferenceableBytes() const { return DerefBytes; }
496
497  /// \brief Retrieve the number of dereferenceable_or_null bytes, if the
498  /// dereferenceable_or_null attribute exists (zero is returned otherwise).
499  uint64_t getDereferenceableOrNullBytes() const { return DerefOrNullBytes; }
500
501  /// \brief This turns an int alignment (which must be a power of 2) into the
502  /// form used internally in Attribute.
503  AttrBuilder &addAlignmentAttr(unsigned Align);
504
505  /// \brief This turns an int stack alignment (which must be a power of 2) into
506  /// the form used internally in Attribute.
507  AttrBuilder &addStackAlignmentAttr(unsigned Align);
508
509  /// \brief This turns the number of dereferenceable bytes into the form used
510  /// internally in Attribute.
511  AttrBuilder &addDereferenceableAttr(uint64_t Bytes);
512
513  /// \brief This turns the number of dereferenceable_or_null bytes into the
514  /// form used internally in Attribute.
515  AttrBuilder &addDereferenceableOrNullAttr(uint64_t Bytes);
516
517  /// \brief Return true if the builder contains no target-independent
518  /// attributes.
519  bool empty() const { return Attrs.none(); }
520
521  // Iterators for target-dependent attributes.
522  typedef std::pair<std::string, std::string>                td_type;
523  typedef std::map<std::string, std::string>::iterator       td_iterator;
524  typedef std::map<std::string, std::string>::const_iterator td_const_iterator;
525  typedef llvm::iterator_range<td_iterator>                  td_range;
526  typedef llvm::iterator_range<td_const_iterator>            td_const_range;
527
528  td_iterator td_begin()             { return TargetDepAttrs.begin(); }
529  td_iterator td_end()               { return TargetDepAttrs.end(); }
530
531  td_const_iterator td_begin() const { return TargetDepAttrs.begin(); }
532  td_const_iterator td_end() const   { return TargetDepAttrs.end(); }
533
534  td_range td_attrs() { return td_range(td_begin(), td_end()); }
535  td_const_range td_attrs() const {
536    return td_const_range(td_begin(), td_end());
537  }
538
539  bool td_empty() const              { return TargetDepAttrs.empty(); }
540
541  bool operator==(const AttrBuilder &B);
542  bool operator!=(const AttrBuilder &B) {
543    return !(*this == B);
544  }
545
546  // FIXME: Remove this in 4.0.
547
548  /// \brief Add the raw value to the internal representation.
549  AttrBuilder &addRawValue(uint64_t Val);
550};
551
552namespace AttributeFuncs {
553
554/// \brief Which attributes cannot be applied to a type.
555AttributeSet typeIncompatible(Type *Ty, uint64_t Index);
556
557} // end AttributeFuncs namespace
558
559} // end llvm namespace
560
561#endif
562