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