2a0fbc0ee13fe74d3365d7c070794b02b9cf0e16
[oota-llvm.git] / include / llvm / 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 // This file contains the simple types necessary to represent the
11 // attributes associated with functions and their calls.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ATTRIBUTES_H
16 #define LLVM_ATTRIBUTES_H
17
18 #include "llvm/AttributesImpl.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include <cassert>
22 #include <string>
23
24 namespace llvm {
25
26 class LLVMContext;
27 class Type;
28
29 namespace Attribute {
30
31 /// AttrConst - We use this proxy POD type to allow constructing Attributes
32 /// constants using initializer lists. Do not use this class directly.
33 struct AttrConst {
34   uint64_t v;
35   AttrConst operator | (const AttrConst Attrs) const {
36     AttrConst Res = {v | Attrs.v};
37     return Res;
38   }
39   AttrConst operator ~ () const {
40     AttrConst Res = {~v};
41     return Res;
42   }
43 };
44
45 /// Function parameters and results can have attributes to indicate how they
46 /// should be treated by optimizations and code generation. This enumeration
47 /// lists the attributes that can be associated with parameters, function
48 /// results or the function itself.
49 /// @brief Function attributes.
50
51 /// We declare AttrConst objects that will be used throughout the code and also
52 /// raw uint64_t objects with _i suffix to be used below for other constant
53 /// declarations. This is done to avoid static CTORs and at the same time to
54 /// keep type-safety of Attributes.
55 #define DECLARE_LLVM_ATTRIBUTE(name, value) \
56   const uint64_t name##_i = value; \
57   const AttrConst name = {value};
58
59 DECLARE_LLVM_ATTRIBUTE(None,0)    ///< No attributes have been set
60 DECLARE_LLVM_ATTRIBUTE(ZExt,1<<0) ///< Zero extended before/after call
61 DECLARE_LLVM_ATTRIBUTE(SExt,1<<1) ///< Sign extended before/after call
62 DECLARE_LLVM_ATTRIBUTE(NoReturn,1<<2) ///< Mark the function as not returning
63 DECLARE_LLVM_ATTRIBUTE(InReg,1<<3) ///< Force argument to be passed in register
64 DECLARE_LLVM_ATTRIBUTE(StructRet,1<<4) ///< Hidden pointer to structure to return
65 DECLARE_LLVM_ATTRIBUTE(NoUnwind,1<<5) ///< Function doesn't unwind stack
66 DECLARE_LLVM_ATTRIBUTE(NoAlias,1<<6) ///< Considered to not alias after call
67 DECLARE_LLVM_ATTRIBUTE(ByVal,1<<7) ///< Pass structure by value
68 DECLARE_LLVM_ATTRIBUTE(Nest,1<<8) ///< Nested function static chain
69 DECLARE_LLVM_ATTRIBUTE(ReadNone,1<<9) ///< Function does not access memory
70 DECLARE_LLVM_ATTRIBUTE(ReadOnly,1<<10) ///< Function only reads from memory
71 DECLARE_LLVM_ATTRIBUTE(NoInline,1<<11) ///< inline=never
72 DECLARE_LLVM_ATTRIBUTE(AlwaysInline,1<<12) ///< inline=always
73 DECLARE_LLVM_ATTRIBUTE(OptimizeForSize,1<<13) ///< opt_size
74 DECLARE_LLVM_ATTRIBUTE(StackProtect,1<<14) ///< Stack protection.
75 DECLARE_LLVM_ATTRIBUTE(StackProtectReq,1<<15) ///< Stack protection required.
76 DECLARE_LLVM_ATTRIBUTE(Alignment,31<<16) ///< Alignment of parameter (5 bits)
77                                      // stored as log2 of alignment with +1 bias
78                                      // 0 means unaligned different from align 1
79 DECLARE_LLVM_ATTRIBUTE(NoCapture,1<<21) ///< Function creates no aliases of pointer
80 DECLARE_LLVM_ATTRIBUTE(NoRedZone,1<<22) /// disable redzone
81 DECLARE_LLVM_ATTRIBUTE(NoImplicitFloat,1<<23) /// disable implicit floating point
82                                            /// instructions.
83 DECLARE_LLVM_ATTRIBUTE(Naked,1<<24) ///< Naked function
84 DECLARE_LLVM_ATTRIBUTE(InlineHint,1<<25) ///< source said inlining was
85                                            ///desirable
86 DECLARE_LLVM_ATTRIBUTE(StackAlignment,7<<26) ///< Alignment of stack for
87                                            ///function (3 bits) stored as log2
88                                            ///of alignment with +1 bias
89                                            ///0 means unaligned (different from
90                                            ///alignstack= {1))
91 DECLARE_LLVM_ATTRIBUTE(ReturnsTwice,1<<29) ///< Function can return twice
92 DECLARE_LLVM_ATTRIBUTE(UWTable,1<<30) ///< Function must be in a unwind
93                                            ///table
94 DECLARE_LLVM_ATTRIBUTE(NonLazyBind,1U<<31) ///< Function is called early and/or
95                                             /// often, so lazy binding isn't
96                                             /// worthwhile.
97 DECLARE_LLVM_ATTRIBUTE(AddressSafety,1ULL<<32) ///< Address safety checking is on.
98
99 #undef DECLARE_LLVM_ATTRIBUTE
100
101 /// Note that uwtable is about the ABI or the user mandating an entry in the
102 /// unwind table. The nounwind attribute is about an exception passing by the
103 /// function.
104 /// In a theoretical system that uses tables for profiling and sjlj for
105 /// exceptions, they would be fully independent. In a normal system that
106 /// uses tables for both, the semantics are:
107 /// nil                = Needs an entry because an exception might pass by.
108 /// nounwind           = No need for an entry
109 /// uwtable            = Needs an entry because the ABI says so and because
110 ///                      an exception might pass by.
111 /// uwtable + nounwind = Needs an entry because the ABI says so.
112
113 /// @brief Attributes that only apply to function parameters.
114 const AttrConst ParameterOnly = {ByVal_i | Nest_i |
115     StructRet_i | NoCapture_i};
116
117 /// @brief Attributes that may be applied to the function itself.  These cannot
118 /// be used on return values or function parameters.
119 const AttrConst FunctionOnly = {NoReturn_i | NoUnwind_i | ReadNone_i |
120   ReadOnly_i | NoInline_i | AlwaysInline_i | OptimizeForSize_i |
121   StackProtect_i | StackProtectReq_i | NoRedZone_i | NoImplicitFloat_i |
122   Naked_i | InlineHint_i | StackAlignment_i |
123   UWTable_i | NonLazyBind_i | ReturnsTwice_i | AddressSafety_i};
124
125 /// @brief Attributes that are mutually incompatible.
126 const AttrConst MutuallyIncompatible[5] = {
127   {ByVal_i | Nest_i | StructRet_i},
128   {ByVal_i | Nest_i | InReg_i },
129   {ZExt_i  | SExt_i},
130   {ReadNone_i | ReadOnly_i},
131   {NoInline_i | AlwaysInline_i}
132 };
133
134 }  // namespace Attribute
135
136 /// AttributeImpl - The internal representation of the Attributes class. This is
137 /// uniquified.
138 class AttributesImpl;
139
140 /// Attributes - A bitset of attributes.
141 class Attributes {
142 public:
143   enum AttrVal {
144     None            = 0,   ///< No attributes have been set
145     ZExt            = 1,   ///< Zero extended before/after call
146     SExt            = 2,   ///< Sign extended before/after call
147     NoReturn        = 3,   ///< Mark the function as not returning
148     InReg           = 4,   ///< Force argument to be passed in register
149     StructRet       = 5,   ///< Hidden pointer to structure to return
150     NoUnwind        = 6,   ///< Function doesn't unwind stack
151     NoAlias         = 7,   ///< Considered to not alias after call
152     ByVal           = 8,   ///< Pass structure by value
153     Nest            = 9,   ///< Nested function static chain
154     ReadNone        = 10,  ///< Function does not access memory
155     ReadOnly        = 11,  ///< Function only reads from memory
156     NoInline        = 12,  ///< inline=never
157     AlwaysInline    = 13,  ///< inline=always
158     OptimizeForSize = 14,  ///< opt_size
159     StackProtect    = 15,  ///< Stack protection.
160     StackProtectReq = 16,  ///< Stack protection required.
161     Alignment       = 17,  ///< Alignment of parameter (5 bits)
162                            ///< stored as log2 of alignment with +1 bias
163                            ///< 0 means unaligned different from align 1
164     NoCapture       = 18,  ///< Function creates no aliases of pointer
165     NoRedZone       = 19,  ///< Disable redzone
166     NoImplicitFloat = 20,  ///< Disable implicit floating point insts
167     Naked           = 21,  ///< Naked function
168     InlineHint      = 22,  ///< Source said inlining was desirable
169     StackAlignment  = 23,  ///< Alignment of stack for function (3 bits)
170                            ///< stored as log2 of alignment with +1 bias 0
171                            ///< means unaligned (different from
172                            ///< alignstack={1))
173     ReturnsTwice    = 24,  ///< Function can return twice
174     UWTable         = 25,  ///< Function must be in a unwind table
175     NonLazyBind     = 26,  ///< Function is called early and/or
176                            ///< often, so lazy binding isn't worthwhile
177     AddressSafety   = 27   ///< Address safety checking is on.
178   };
179 private:
180   AttributesImpl Attrs;
181
182   explicit Attributes(AttributesImpl *A);
183 public:
184   Attributes() : Attrs(0) {}
185   explicit Attributes(uint64_t Val);
186   /*implicit*/ Attributes(Attribute::AttrConst Val);
187   Attributes(const Attributes &A);
188
189   class Builder {
190     friend class Attributes;
191     uint64_t Bits;
192   public:
193     Builder() : Bits(0) {}
194     Builder(const Attributes &A) : Bits(A.Raw()) {}
195
196     void clear() { Bits = 0; }
197
198     bool hasAttributes() const;
199     bool hasAttributes(const Attributes &A) const;
200     bool hasAlignmentAttr() const;
201
202     uint64_t getAlignment() const;
203
204     void addAttribute(Attributes::AttrVal Val);
205     void removeAttribute(Attributes::AttrVal Val);
206
207     void addAlignmentAttr(unsigned Align);
208     void addStackAlignmentAttr(unsigned Align);
209
210     void removeAttributes(const Attributes &A);
211   };
212
213   /// get - Return a uniquified Attributes object. This takes the uniquified
214   /// value from the Builder and wraps it in the Attributes class.
215   static Attributes get(Builder &B);
216   static Attributes get(LLVMContext &Context, Builder &B);
217
218   /// @brief Parameter attributes that do not apply to vararg call arguments.
219   bool hasIncompatibleWithVarArgsAttrs() const {
220     return hasAttribute(Attributes::StructRet);
221   }
222
223   /// @brief Return true if the attribute is present.
224   bool hasAttribute(AttrVal Val) const;
225
226   /// @brief Return true if attributes exist
227   bool hasAttributes() const {
228     return Attrs.hasAttributes();
229   }
230
231   /// @brief Return true if the attributes are a non-null intersection.
232   bool hasAttributes(const Attributes &A) const;
233
234   /// This returns the alignment field of an attribute as a byte alignment
235   /// value.
236   unsigned getAlignment() const;
237
238   /// This returns the stack alignment field of an attribute as a byte alignment
239   /// value.
240   unsigned getStackAlignment() const;
241
242   bool isEmptyOrSingleton() const;
243
244   // This is a "safe bool() operator".
245   operator const void *() const { return Attrs.Bits ? this : 0; }
246   bool operator == (const Attributes &A) const {
247     return Attrs.Bits == A.Attrs.Bits;
248   }
249   bool operator != (const Attributes &A) const {
250     return Attrs.Bits != A.Attrs.Bits;
251   }
252
253   Attributes operator | (const Attributes &A) const;
254   Attributes operator & (const Attributes &A) const;
255   Attributes operator ^ (const Attributes &A) const;
256   Attributes &operator |= (const Attributes &A);
257   Attributes &operator &= (const Attributes &A);
258   Attributes operator ~ () const;
259
260   uint64_t Raw() const;
261
262   /// constructAlignmentFromInt - This turns an int alignment (a power of 2,
263   /// normally) into the form used internally in Attributes.
264   static Attributes constructAlignmentFromInt(unsigned i) {
265     // Default alignment, allow the target to define how to align it.
266     if (i == 0)
267       return Attribute::None;
268
269     assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
270     assert(i <= 0x40000000 && "Alignment too large.");
271     return Attributes((Log2_32(i)+1) << 16);
272   }
273
274   /// constructStackAlignmentFromInt - This turns an int stack alignment (which
275   /// must be a power of 2) into the form used internally in Attributes.
276   static Attributes constructStackAlignmentFromInt(unsigned i) {
277     // Default alignment, allow the target to define how to align it.
278     if (i == 0)
279       return Attribute::None;
280
281     assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
282     assert(i <= 0x100 && "Alignment too large.");
283     return Attributes((Log2_32(i)+1) << 26);
284   }
285
286   /// @brief Which attributes cannot be applied to a type.
287   static Attributes typeIncompatible(Type *Ty);
288
289   /// encodeLLVMAttributesForBitcode - This returns an integer containing an
290   /// encoding of all the LLVM attributes found in the given attribute bitset.
291   /// Any change to this encoding is a breaking change to bitcode compatibility.
292   static uint64_t encodeLLVMAttributesForBitcode(Attributes Attrs) {
293     // FIXME: It doesn't make sense to store the alignment information as an
294     // expanded out value, we should store it as a log2 value.  However, we
295     // can't just change that here without breaking bitcode compatibility.  If
296     // this ever becomes a problem in practice, we should introduce new tag
297     // numbers in the bitcode file and have those tags use a more efficiently
298     // encoded alignment field.
299
300     // Store the alignment in the bitcode as a 16-bit raw value instead of a
301     // 5-bit log2 encoded value. Shift the bits above the alignment up by 11
302     // bits.
303     uint64_t EncodedAttrs = Attrs.Raw() & 0xffff;
304     if (Attrs.hasAttribute(Attributes::Alignment))
305       EncodedAttrs |= (1ULL << 16) <<
306         (((Attrs.Raw() & Attribute::Alignment_i) - 1) >> 16);
307     EncodedAttrs |= (Attrs.Raw() & (0xfffULL << 21)) << 11;
308     return EncodedAttrs;
309   }
310
311   /// decodeLLVMAttributesForBitcode - This returns an attribute bitset
312   /// containing the LLVM attributes that have been decoded from the given
313   /// integer.  This function must stay in sync with
314   /// 'encodeLLVMAttributesForBitcode'.
315   static Attributes decodeLLVMAttributesForBitcode(uint64_t EncodedAttrs) {
316     // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
317     // the bits above 31 down by 11 bits.
318     unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
319     assert((!Alignment || isPowerOf2_32(Alignment)) &&
320            "Alignment must be a power of two.");
321
322     Attributes Attrs(EncodedAttrs & 0xffff);
323     if (Alignment)
324       Attrs |= Attributes::constructAlignmentFromInt(Alignment);
325     Attrs |= Attributes((EncodedAttrs & (0xfffULL << 32)) >> 11);
326     return Attrs;
327   }
328
329   /// getAsString - The set of Attributes set in Attributes is converted to a
330   /// string of equivalent mnemonics. This is, presumably, for writing out the
331   /// mnemonics for the assembly writer.
332   /// @brief Convert attribute bits to text
333   std::string getAsString() const;
334 };
335
336 //===----------------------------------------------------------------------===//
337 // AttributeWithIndex
338 //===----------------------------------------------------------------------===//
339
340 /// AttributeWithIndex - This is just a pair of values to associate a set of
341 /// attributes with an index.
342 struct AttributeWithIndex {
343   Attributes Attrs;  ///< The attributes that are set, or'd together.
344   unsigned Index;    ///< Index of the parameter for which the attributes apply.
345                      ///< Index 0 is used for return value attributes.
346                      ///< Index ~0U is used for function attributes.
347
348   static AttributeWithIndex get(unsigned Idx, Attributes Attrs) {
349     AttributeWithIndex P;
350     P.Index = Idx;
351     P.Attrs = Attrs;
352     return P;
353   }
354 };
355
356 //===----------------------------------------------------------------------===//
357 // AttrListPtr Smart Pointer
358 //===----------------------------------------------------------------------===//
359
360 class AttributeListImpl;
361
362 /// AttrListPtr - This class manages the ref count for the opaque
363 /// AttributeListImpl object and provides accessors for it.
364 class AttrListPtr {
365   /// AttrList - The attributes that we are managing.  This can be null
366   /// to represent the empty attributes list.
367   AttributeListImpl *AttrList;
368 public:
369   AttrListPtr() : AttrList(0) {}
370   AttrListPtr(const AttrListPtr &P);
371   const AttrListPtr &operator=(const AttrListPtr &RHS);
372   ~AttrListPtr();
373
374   //===--------------------------------------------------------------------===//
375   // Attribute List Construction and Mutation
376   //===--------------------------------------------------------------------===//
377
378   /// get - Return a Attributes list with the specified parameters in it.
379   static AttrListPtr get(ArrayRef<AttributeWithIndex> Attrs);
380
381   /// addAttr - Add the specified attribute at the specified index to this
382   /// attribute list.  Since attribute lists are immutable, this
383   /// returns the new list.
384   AttrListPtr addAttr(unsigned Idx, Attributes Attrs) const;
385
386   /// removeAttr - Remove the specified attribute at the specified index from
387   /// this attribute list.  Since attribute lists are immutable, this
388   /// returns the new list.
389   AttrListPtr removeAttr(unsigned Idx, Attributes Attrs) const;
390
391   //===--------------------------------------------------------------------===//
392   // Attribute List Accessors
393   //===--------------------------------------------------------------------===//
394   /// getParamAttributes - The attributes for the specified index are
395   /// returned.
396   Attributes getParamAttributes(unsigned Idx) const {
397     return getAttributes(Idx);
398   }
399
400   /// getRetAttributes - The attributes for the ret value are
401   /// returned.
402   Attributes getRetAttributes() const {
403     return getAttributes(0);
404   }
405
406   /// getFnAttributes - The function attributes are returned.
407   Attributes getFnAttributes() const {
408     return getAttributes(~0U);
409   }
410
411   /// paramHasAttr - Return true if the specified parameter index has the
412   /// specified attribute set.
413   bool paramHasAttr(unsigned Idx, Attributes Attr) const {
414     return getAttributes(Idx).hasAttributes(Attr);
415   }
416
417   /// getParamAlignment - Return the alignment for the specified function
418   /// parameter.
419   unsigned getParamAlignment(unsigned Idx) const {
420     return getAttributes(Idx).getAlignment();
421   }
422
423   /// hasAttrSomewhere - Return true if the specified attribute is set for at
424   /// least one parameter or for the return value.
425   bool hasAttrSomewhere(Attributes Attr) const;
426
427   unsigned getNumAttrs() const;
428   Attributes &getAttributesAtIndex(unsigned i) const;
429
430   /// operator==/!= - Provide equality predicates.
431   bool operator==(const AttrListPtr &RHS) const
432   { return AttrList == RHS.AttrList; }
433   bool operator!=(const AttrListPtr &RHS) const
434   { return AttrList != RHS.AttrList; }
435
436   void dump() const;
437
438   //===--------------------------------------------------------------------===//
439   // Attribute List Introspection
440   //===--------------------------------------------------------------------===//
441
442   /// getRawPointer - Return a raw pointer that uniquely identifies this
443   /// attribute list.
444   void *getRawPointer() const {
445     return AttrList;
446   }
447
448   // Attributes are stored as a dense set of slots, where there is one
449   // slot for each argument that has an attribute.  This allows walking over the
450   // dense set instead of walking the sparse list of attributes.
451
452   /// isEmpty - Return true if there are no attributes.
453   ///
454   bool isEmpty() const {
455     return AttrList == 0;
456   }
457
458   /// getNumSlots - Return the number of slots used in this attribute list.
459   /// This is the number of arguments that have an attribute set on them
460   /// (including the function itself).
461   unsigned getNumSlots() const;
462
463   /// getSlot - Return the AttributeWithIndex at the specified slot.  This
464   /// holds a index number plus a set of attributes.
465   const AttributeWithIndex &getSlot(unsigned Slot) const;
466
467 private:
468   explicit AttrListPtr(AttributeListImpl *L);
469
470   /// getAttributes - The attributes for the specified index are
471   /// returned.  Attributes for the result are denoted with Idx = 0.
472   Attributes getAttributes(unsigned Idx) const;
473 };
474
475 } // End llvm namespace
476
477 #endif