24fae1847d83ab225016cd7c4833a1828a2b4b0c
[oota-llvm.git] / include / llvm / IR / Attributes.h
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
28 namespace llvm {
29
30 class AttrBuilder;
31 class AttributeImpl;
32 class AttributeSetImpl;
33 class AttributeSetNode;
34 class Constant;
35 template<typename T> struct DenseMapInfo;
36 class LLVMContext;
37 class 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.
45 class Attribute {
46 public:
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   };
119 private:
120   AttributeImpl *pImpl;
121   Attribute(AttributeImpl *A) : pImpl(A) {}
122 public:
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'.
219 class AttributeSet {
220 public:
221   enum AttrIndex : unsigned {
222     ReturnIndex = 0U,
223     FunctionIndex = ~0U
224   };
225 private:
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) {}
250 public:
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. Because
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. Because
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. Because
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. Because attribute lists are immutable, this returns the
282   /// new 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. Because attribute lists are immutable, this returns the
288   /// new list.
289   AttributeSet removeAttributes(LLVMContext &C, unsigned Index, 
290                                 AttributeSet Attrs) const;
291
292   /// \brief Remove the specified attributes at the specified index from this
293   /// attribute list. Because attribute lists are immutable, this returns the
294   /// new list.
295   AttributeSet removeAttributes(LLVMContext &C, unsigned Index,
296                                 const AttrBuilder &Attrs) const;
297
298   /// \brief Add the dereferenceable attribute to the attribute set at the given
299   /// index. Because attribute sets are immutable, this returns a new set.
300   AttributeSet addDereferenceableAttr(LLVMContext &C, unsigned Index,
301                                       uint64_t Bytes) const;
302
303   /// \brief Add the dereferenceable_or_null attribute to the attribute set at
304   /// the given index. Because attribute sets are immutable, this returns a new
305   /// set.
306   AttributeSet addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index,
307                                             uint64_t Bytes) const;
308
309   //===--------------------------------------------------------------------===//
310   // AttributeSet Accessors
311   //===--------------------------------------------------------------------===//
312
313   /// \brief Retrieve the LLVM context.
314   LLVMContext &getContext() const;
315
316   /// \brief The attributes for the specified index are returned.
317   AttributeSet getParamAttributes(unsigned Index) const;
318
319   /// \brief The attributes for the ret value are returned.
320   AttributeSet getRetAttributes() const;
321
322   /// \brief The function attributes are returned.
323   AttributeSet getFnAttributes() const;
324
325   /// \brief Return true if the attribute exists at the given index.
326   bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
327
328   /// \brief Return true if the attribute exists at the given index.
329   bool hasAttribute(unsigned Index, StringRef Kind) const;
330
331   /// \brief Return true if attribute exists at the given index.
332   bool hasAttributes(unsigned Index) const;
333
334   /// \brief Return true if the specified attribute is set for at least one
335   /// parameter or for the return value.
336   bool hasAttrSomewhere(Attribute::AttrKind Attr) const;
337
338   /// \brief Return the attribute object that exists at the given index.
339   Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const;
340
341   /// \brief Return the attribute object that exists at the given index.
342   Attribute getAttribute(unsigned Index, StringRef Kind) const;
343
344   /// \brief Return the alignment for the specified function parameter.
345   unsigned getParamAlignment(unsigned Index) const;
346
347   /// \brief Get the stack alignment.
348   unsigned getStackAlignment(unsigned Index) const;
349
350   /// \brief Get the number of dereferenceable bytes (or zero if unknown).
351   uint64_t getDereferenceableBytes(unsigned Index) const;
352
353   /// \brief Get the number of dereferenceable_or_null bytes (or zero if
354   /// unknown).
355   uint64_t getDereferenceableOrNullBytes(unsigned Index) const;
356
357   /// \brief Return the attributes at the index as a string.
358   std::string getAsString(unsigned Index, bool InAttrGrp = false) const;
359
360   typedef ArrayRef<Attribute>::iterator iterator;
361
362   iterator begin(unsigned Slot) const;
363   iterator end(unsigned Slot) const;
364
365   /// operator==/!= - Provide equality predicates.
366   bool operator==(const AttributeSet &RHS) const {
367     return pImpl == RHS.pImpl;
368   }
369   bool operator!=(const AttributeSet &RHS) const {
370     return pImpl != RHS.pImpl;
371   }
372
373   //===--------------------------------------------------------------------===//
374   // AttributeSet Introspection
375   //===--------------------------------------------------------------------===//
376
377   // FIXME: Remove this.
378   uint64_t Raw(unsigned Index) const;
379
380   /// \brief Return a raw pointer that uniquely identifies this attribute list.
381   void *getRawPointer() const {
382     return pImpl;
383   }
384
385   /// \brief Return true if there are no attributes.
386   bool isEmpty() const {
387     return getNumSlots() == 0;
388   }
389
390   /// \brief Return the number of slots used in this attribute list.  This is
391   /// the number of arguments that have an attribute set on them (including the
392   /// function itself).
393   unsigned getNumSlots() const;
394
395   /// \brief Return the index for the given slot.
396   unsigned getSlotIndex(unsigned Slot) const;
397
398   /// \brief Return the attributes at the given slot.
399   AttributeSet getSlotAttributes(unsigned Slot) const;
400
401   void dump() const;
402 };
403
404 //===----------------------------------------------------------------------===//
405 /// \class
406 /// \brief Provide DenseMapInfo for AttributeSet.
407 template<> struct DenseMapInfo<AttributeSet> {
408   static inline AttributeSet getEmptyKey() {
409     uintptr_t Val = static_cast<uintptr_t>(-1);
410     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
411     return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
412   }
413   static inline AttributeSet getTombstoneKey() {
414     uintptr_t Val = static_cast<uintptr_t>(-2);
415     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
416     return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
417   }
418   static unsigned getHashValue(AttributeSet AS) {
419     return (unsigned((uintptr_t)AS.pImpl) >> 4) ^
420            (unsigned((uintptr_t)AS.pImpl) >> 9);
421   }
422   static bool isEqual(AttributeSet LHS, AttributeSet RHS) { return LHS == RHS; }
423 };
424
425 //===----------------------------------------------------------------------===//
426 /// \class
427 /// \brief This class is used in conjunction with the Attribute::get method to
428 /// create an Attribute object. The object itself is uniquified. The Builder's
429 /// value, however, is not. So this can be used as a quick way to test for
430 /// equality, presence of attributes, etc.
431 class AttrBuilder {
432   std::bitset<Attribute::EndAttrKinds> Attrs;
433   std::map<std::string, std::string> TargetDepAttrs;
434   uint64_t Alignment;
435   uint64_t StackAlignment;
436   uint64_t DerefBytes;
437   uint64_t DerefOrNullBytes;
438 public:
439   AttrBuilder()
440       : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
441         DerefOrNullBytes(0) {}
442   explicit AttrBuilder(uint64_t Val)
443       : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
444         DerefOrNullBytes(0) {
445     addRawValue(Val);
446   }
447   AttrBuilder(const Attribute &A)
448       : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
449         DerefOrNullBytes(0) {
450     addAttribute(A);
451   }
452   AttrBuilder(AttributeSet AS, unsigned Idx);
453
454   void clear();
455
456   /// \brief Add an attribute to the builder.
457   AttrBuilder &addAttribute(Attribute::AttrKind Val);
458
459   /// \brief Add the Attribute object to the builder.
460   AttrBuilder &addAttribute(Attribute A);
461
462   /// \brief Add the target-dependent attribute to the builder.
463   AttrBuilder &addAttribute(StringRef A, StringRef V = StringRef());
464
465   /// \brief Remove an attribute from the builder.
466   AttrBuilder &removeAttribute(Attribute::AttrKind Val);
467
468   /// \brief Remove the attributes from the builder.
469   AttrBuilder &removeAttributes(AttributeSet A, uint64_t Index);
470
471   /// \brief Remove the target-dependent attribute to the builder.
472   AttrBuilder &removeAttribute(StringRef A);
473
474   /// \brief Add the attributes from the builder.
475   AttrBuilder &merge(const AttrBuilder &B);
476
477   /// \brief Remove the attributes from the builder.
478   AttrBuilder &remove(const AttrBuilder &B);
479
480   /// \brief \brief Return true if the builder has any attribute that's in the
481   /// specified builder.
482   bool overlaps(const AttrBuilder &B) const;
483
484   /// \brief Return true if the builder has the specified attribute.
485   bool contains(Attribute::AttrKind A) const {
486     assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!");
487     return Attrs[A];
488   }
489
490   /// \brief Return true if the builder has the specified target-dependent
491   /// attribute.
492   bool contains(StringRef A) const;
493
494   /// \brief Return true if the builder has IR-level attributes.
495   bool hasAttributes() const;
496
497   /// \brief Return true if the builder has any attribute that's in the
498   /// specified attribute.
499   bool hasAttributes(AttributeSet A, uint64_t Index) const;
500
501   /// \brief Return true if the builder has an alignment attribute.
502   bool hasAlignmentAttr() const;
503
504   /// \brief Retrieve the alignment attribute, if it exists.
505   uint64_t getAlignment() const { return Alignment; }
506
507   /// \brief Retrieve the stack alignment attribute, if it exists.
508   uint64_t getStackAlignment() const { return StackAlignment; }
509
510   /// \brief Retrieve the number of dereferenceable bytes, if the dereferenceable
511   /// attribute exists (zero is returned otherwise).
512   uint64_t getDereferenceableBytes() const { return DerefBytes; }
513
514   /// \brief Retrieve the number of dereferenceable_or_null bytes, if the
515   /// dereferenceable_or_null attribute exists (zero is returned otherwise).
516   uint64_t getDereferenceableOrNullBytes() const { return DerefOrNullBytes; }
517
518   /// \brief This turns an int alignment (which must be a power of 2) into the
519   /// form used internally in Attribute.
520   AttrBuilder &addAlignmentAttr(unsigned Align);
521
522   /// \brief This turns an int stack alignment (which must be a power of 2) into
523   /// the form used internally in Attribute.
524   AttrBuilder &addStackAlignmentAttr(unsigned Align);
525
526   /// \brief This turns the number of dereferenceable bytes into the form used
527   /// internally in Attribute.
528   AttrBuilder &addDereferenceableAttr(uint64_t Bytes);
529
530   /// \brief This turns the number of dereferenceable_or_null bytes into the
531   /// form used internally in Attribute.
532   AttrBuilder &addDereferenceableOrNullAttr(uint64_t Bytes);
533
534   /// \brief Return true if the builder contains no target-independent
535   /// attributes.
536   bool empty() const { return Attrs.none(); }
537
538   // Iterators for target-dependent attributes.
539   typedef std::pair<std::string, std::string>                td_type;
540   typedef std::map<std::string, std::string>::iterator       td_iterator;
541   typedef std::map<std::string, std::string>::const_iterator td_const_iterator;
542   typedef llvm::iterator_range<td_iterator>                  td_range;
543   typedef llvm::iterator_range<td_const_iterator>            td_const_range;
544
545   td_iterator td_begin()             { return TargetDepAttrs.begin(); }
546   td_iterator td_end()               { return TargetDepAttrs.end(); }
547
548   td_const_iterator td_begin() const { return TargetDepAttrs.begin(); }
549   td_const_iterator td_end() const   { return TargetDepAttrs.end(); }
550
551   td_range td_attrs() { return td_range(td_begin(), td_end()); }
552   td_const_range td_attrs() const {
553     return td_const_range(td_begin(), td_end());
554   }
555
556   bool td_empty() const              { return TargetDepAttrs.empty(); }
557
558   bool operator==(const AttrBuilder &B);
559   bool operator!=(const AttrBuilder &B) {
560     return !(*this == B);
561   }
562
563   // FIXME: Remove this in 4.0.
564
565   /// \brief Add the raw value to the internal representation.
566   AttrBuilder &addRawValue(uint64_t Val);
567 };
568
569 namespace AttributeFuncs {
570
571 /// \brief Which attributes cannot be applied to a type.
572 AttrBuilder typeIncompatible(const Type *Ty);
573
574 } // end AttributeFuncs namespace
575
576 } // end llvm namespace
577
578 #endif