00eb325cacda98417c3934625c387c948421baec
[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 Parameter attributes that do not apply to vararg call arguments.
126 const AttrConst VarArgsIncompatible = {StructRet_i};
127
128 /// @brief Attributes that are mutually incompatible.
129 const AttrConst MutuallyIncompatible[5] = {
130   {ByVal_i | Nest_i | StructRet_i},
131   {ByVal_i | Nest_i | InReg_i },
132   {ZExt_i  | SExt_i},
133   {ReadNone_i | ReadOnly_i},
134   {NoInline_i | AlwaysInline_i}
135 };
136
137 }  // namespace Attribute
138
139 /// AttributeImpl - The internal representation of the Attributes class. This is
140 /// uniquified.
141 class AttributesImpl;
142
143 /// Attributes - A bitset of attributes.
144 class Attributes {
145 public:
146   enum AttrVal {
147     None            = 0,   ///< No attributes have been set
148     ZExt            = 1,   ///< Zero extended before/after call
149     SExt            = 2,   ///< Sign extended before/after call
150     NoReturn        = 3,   ///< Mark the function as not returning
151     InReg           = 4,   ///< Force argument to be passed in register
152     StructRet       = 5,   ///< Hidden pointer to structure to return
153     NoUnwind        = 6,   ///< Function doesn't unwind stack
154     NoAlias         = 7,   ///< Considered to not alias after call
155     ByVal           = 8,   ///< Pass structure by value
156     Nest            = 9,   ///< Nested function static chain
157     ReadNone        = 10,  ///< Function does not access memory
158     ReadOnly        = 11,  ///< Function only reads from memory
159     NoInline        = 12,  ///< inline=never
160     AlwaysInline    = 13,  ///< inline=always
161     OptimizeForSize = 14,  ///< opt_size
162     StackProtect    = 15,  ///< Stack protection.
163     StackProtectReq = 16,  ///< Stack protection required.
164     Alignment       = 17,  ///< Alignment of parameter (5 bits)
165                            ///< stored as log2 of alignment with +1 bias
166                            ///< 0 means unaligned different from align 1
167     NoCapture       = 18,  ///< Function creates no aliases of pointer
168     NoRedZone       = 19,  ///< Disable redzone
169     NoImplicitFloat = 20,  ///< Disable implicit floating point insts
170     Naked           = 21,  ///< Naked function
171     InlineHint      = 22,  ///< Source said inlining was desirable
172     StackAlignment  = 23,  ///< Alignment of stack for function (3 bits)
173                            ///< stored as log2 of alignment with +1 bias 0
174                            ///< means unaligned (different from
175                            ///< alignstack={1))
176     ReturnsTwice    = 24,  ///< Function can return twice
177     UWTable         = 25,  ///< Function must be in a unwind table
178     NonLazyBind     = 26,  ///< Function is called early and/or
179                            ///< often, so lazy binding isn't worthwhile
180     AddressSafety   = 27   ///< Address safety checking is on.
181   };
182 private:
183   // Currently, we need less than 64 bits.
184   AttributesImpl Attrs;
185
186   explicit Attributes(AttributesImpl *A);
187 public:
188   Attributes() : Attrs(0) {}
189   explicit Attributes(uint64_t Val);
190   /*implicit*/ Attributes(Attribute::AttrConst Val);
191   Attributes(const Attributes &A);
192
193   class Builder {
194     friend class Attributes;
195     uint64_t Bits;
196   public:
197     Builder() : Bits(0) {}
198     Builder(const Attributes &A) : Bits(A.Raw()) {}
199
200     void clear() { Bits = 0; }
201
202     bool hasAttributes() const;
203     bool hasAttributes(const Attributes &A) const;
204     bool hasAlignmentAttr() const;
205
206     uint64_t getAlignment() const;
207
208     void addAttribute(Attributes::AttrVal Val);
209     void removeAttribute(Attributes::AttrVal Val);
210
211     void addAlignmentAttr(unsigned Align);
212     void addStackAlignmentAttr(unsigned Align);
213
214     void removeAttributes(const Attributes &A);
215
216     void removeAddressSafetyAttr();
217     void removeAlwaysInlineAttr();
218     void removeByValAttr();
219     void removeInlineHintAttr();
220     void removeInRegAttr();
221     void removeNakedAttr();
222     void removeNestAttr();
223     void removeNoAliasAttr();
224     void removeNoCaptureAttr();
225     void removeNoImplicitFloatAttr();
226     void removeNoInlineAttr();
227     void removeNonLazyBindAttr();
228     void removeNoRedZoneAttr();
229     void removeNoReturnAttr();
230     void removeNoUnwindAttr();
231     void removeOptimizeForSizeAttr();
232     void removeReadNoneAttr();
233     void removeReadOnlyAttr();
234     void removeReturnsTwiceAttr();
235     void removeSExtAttr();
236     void removeStackProtectAttr();
237     void removeStackProtectReqAttr();
238     void removeStructRetAttr();
239     void removeUWTableAttr();
240     void removeZExtAttr();
241
242     void removeAlignmentAttr();
243     void removeStackAlignmentAttr();
244   };
245
246   /// get - Return a uniquified Attributes object. This takes the uniquified
247   /// value from the Builder and wraps it in the Attributes class.
248   static Attributes get(Builder &B);
249   static Attributes get(LLVMContext &Context, Builder &B);
250
251   /// @brief Parameter attributes that do not apply to vararg call arguments.
252   bool hasIncompatibleWithVarArgsAttrs() const {
253     return hasAttribute(Attributes::StructRet);
254   }
255
256   /// @brief Return true if the attribute is present.
257   bool hasAttribute(AttrVal Val) const;
258
259   /// @brief Return true if attributes exist
260   bool hasAttributes() const {
261     return Attrs.hasAttributes();
262   }
263
264   /// @brief Return true if the attributes are a non-null intersection.
265   bool hasAttributes(const Attributes &A) const;
266
267   /// This returns the alignment field of an attribute as a byte alignment
268   /// value.
269   unsigned getAlignment() const;
270
271   /// This returns the stack alignment field of an attribute as a byte alignment
272   /// value.
273   unsigned getStackAlignment() const;
274
275   bool isEmptyOrSingleton() const;
276
277   // This is a "safe bool() operator".
278   operator const void *() const { return Attrs.Bits ? this : 0; }
279   bool operator == (const Attributes &A) const {
280     return Attrs.Bits == A.Attrs.Bits;
281   }
282   bool operator != (const Attributes &A) const {
283     return Attrs.Bits != A.Attrs.Bits;
284   }
285
286   Attributes operator | (const Attributes &A) const;
287   Attributes operator & (const Attributes &A) const;
288   Attributes operator ^ (const Attributes &A) const;
289   Attributes &operator |= (const Attributes &A);
290   Attributes &operator &= (const Attributes &A);
291   Attributes operator ~ () const;
292
293   uint64_t Raw() const;
294
295   /// constructAlignmentFromInt - This turns an int alignment (a power of 2,
296   /// normally) into the form used internally in Attributes.
297   static Attributes constructAlignmentFromInt(unsigned i) {
298     // Default alignment, allow the target to define how to align it.
299     if (i == 0)
300       return Attribute::None;
301
302     assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
303     assert(i <= 0x40000000 && "Alignment too large.");
304     return Attributes((Log2_32(i)+1) << 16);
305   }
306
307   /// constructStackAlignmentFromInt - This turns an int stack alignment (which
308   /// must be a power of 2) into the form used internally in Attributes.
309   static Attributes constructStackAlignmentFromInt(unsigned i) {
310     // Default alignment, allow the target to define how to align it.
311     if (i == 0)
312       return Attribute::None;
313
314     assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
315     assert(i <= 0x100 && "Alignment too large.");
316     return Attributes((Log2_32(i)+1) << 26);
317   }
318
319   /// @brief Which attributes cannot be applied to a type.
320   static Attributes typeIncompatible(Type *Ty);
321
322   /// encodeLLVMAttributesForBitcode - This returns an integer containing an
323   /// encoding of all the LLVM attributes found in the given attribute bitset.
324   /// Any change to this encoding is a breaking change to bitcode compatibility.
325   static uint64_t encodeLLVMAttributesForBitcode(Attributes Attrs) {
326     // FIXME: It doesn't make sense to store the alignment information as an
327     // expanded out value, we should store it as a log2 value.  However, we
328     // can't just change that here without breaking bitcode compatibility.  If
329     // this ever becomes a problem in practice, we should introduce new tag
330     // numbers in the bitcode file and have those tags use a more efficiently
331     // encoded alignment field.
332
333     // Store the alignment in the bitcode as a 16-bit raw value instead of a
334     // 5-bit log2 encoded value. Shift the bits above the alignment up by 11
335     // bits.
336     uint64_t EncodedAttrs = Attrs.Raw() & 0xffff;
337     if (Attrs.hasAttribute(Attributes::Alignment))
338       EncodedAttrs |= (1ULL << 16) <<
339         (((Attrs.Raw() & Attribute::Alignment_i) - 1) >> 16);
340     EncodedAttrs |= (Attrs.Raw() & (0xfffULL << 21)) << 11;
341     return EncodedAttrs;
342   }
343
344   /// decodeLLVMAttributesForBitcode - This returns an attribute bitset
345   /// containing the LLVM attributes that have been decoded from the given
346   /// integer.  This function must stay in sync with
347   /// 'encodeLLVMAttributesForBitcode'.
348   static Attributes decodeLLVMAttributesForBitcode(uint64_t EncodedAttrs) {
349     // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
350     // the bits above 31 down by 11 bits.
351     unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
352     assert((!Alignment || isPowerOf2_32(Alignment)) &&
353            "Alignment must be a power of two.");
354
355     Attributes Attrs(EncodedAttrs & 0xffff);
356     if (Alignment)
357       Attrs |= Attributes::constructAlignmentFromInt(Alignment);
358     Attrs |= Attributes((EncodedAttrs & (0xfffULL << 32)) >> 11);
359     return Attrs;
360   }
361
362   /// getAsString - The set of Attributes set in Attributes is converted to a
363   /// string of equivalent mnemonics. This is, presumably, for writing out the
364   /// mnemonics for the assembly writer.
365   /// @brief Convert attribute bits to text
366   std::string getAsString() const;
367 };
368
369 //===----------------------------------------------------------------------===//
370 // AttributeWithIndex
371 //===----------------------------------------------------------------------===//
372
373 /// AttributeWithIndex - This is just a pair of values to associate a set of
374 /// attributes with an index.
375 struct AttributeWithIndex {
376   Attributes Attrs;  ///< The attributes that are set, or'd together.
377   unsigned Index;    ///< Index of the parameter for which the attributes apply.
378                      ///< Index 0 is used for return value attributes.
379                      ///< Index ~0U is used for function attributes.
380
381   static AttributeWithIndex get(unsigned Idx, Attributes Attrs) {
382     AttributeWithIndex P;
383     P.Index = Idx;
384     P.Attrs = Attrs;
385     return P;
386   }
387 };
388
389 //===----------------------------------------------------------------------===//
390 // AttrListPtr Smart Pointer
391 //===----------------------------------------------------------------------===//
392
393 class AttributeListImpl;
394
395 /// AttrListPtr - This class manages the ref count for the opaque
396 /// AttributeListImpl object and provides accessors for it.
397 class AttrListPtr {
398   /// AttrList - The attributes that we are managing.  This can be null
399   /// to represent the empty attributes list.
400   AttributeListImpl *AttrList;
401 public:
402   AttrListPtr() : AttrList(0) {}
403   AttrListPtr(const AttrListPtr &P);
404   const AttrListPtr &operator=(const AttrListPtr &RHS);
405   ~AttrListPtr();
406
407   //===--------------------------------------------------------------------===//
408   // Attribute List Construction and Mutation
409   //===--------------------------------------------------------------------===//
410
411   /// get - Return a Attributes list with the specified parameters in it.
412   static AttrListPtr get(ArrayRef<AttributeWithIndex> Attrs);
413
414   /// addAttr - Add the specified attribute at the specified index to this
415   /// attribute list.  Since attribute lists are immutable, this
416   /// returns the new list.
417   AttrListPtr addAttr(unsigned Idx, Attributes Attrs) const;
418
419   /// removeAttr - Remove the specified attribute at the specified index from
420   /// this attribute list.  Since attribute lists are immutable, this
421   /// returns the new list.
422   AttrListPtr removeAttr(unsigned Idx, Attributes Attrs) const;
423
424   //===--------------------------------------------------------------------===//
425   // Attribute List Accessors
426   //===--------------------------------------------------------------------===//
427   /// getParamAttributes - The attributes for the specified index are
428   /// returned.
429   Attributes getParamAttributes(unsigned Idx) const {
430     return getAttributes(Idx);
431   }
432
433   /// getRetAttributes - The attributes for the ret value are
434   /// returned.
435   Attributes getRetAttributes() const {
436     return getAttributes(0);
437   }
438
439   /// getFnAttributes - The function attributes are returned.
440   Attributes getFnAttributes() const {
441     return getAttributes(~0U);
442   }
443
444   /// paramHasAttr - Return true if the specified parameter index has the
445   /// specified attribute set.
446   bool paramHasAttr(unsigned Idx, Attributes Attr) const {
447     return getAttributes(Idx).hasAttributes(Attr);
448   }
449
450   /// getParamAlignment - Return the alignment for the specified function
451   /// parameter.
452   unsigned getParamAlignment(unsigned Idx) const {
453     return getAttributes(Idx).getAlignment();
454   }
455
456   /// hasAttrSomewhere - Return true if the specified attribute is set for at
457   /// least one parameter or for the return value.
458   bool hasAttrSomewhere(Attributes Attr) const;
459
460   unsigned getNumAttrs() const;
461   Attributes &getAttributesAtIndex(unsigned i) const;
462
463   /// operator==/!= - Provide equality predicates.
464   bool operator==(const AttrListPtr &RHS) const
465   { return AttrList == RHS.AttrList; }
466   bool operator!=(const AttrListPtr &RHS) const
467   { return AttrList != RHS.AttrList; }
468
469   void dump() const;
470
471   //===--------------------------------------------------------------------===//
472   // Attribute List Introspection
473   //===--------------------------------------------------------------------===//
474
475   /// getRawPointer - Return a raw pointer that uniquely identifies this
476   /// attribute list.
477   void *getRawPointer() const {
478     return AttrList;
479   }
480
481   // Attributes are stored as a dense set of slots, where there is one
482   // slot for each argument that has an attribute.  This allows walking over the
483   // dense set instead of walking the sparse list of attributes.
484
485   /// isEmpty - Return true if there are no attributes.
486   ///
487   bool isEmpty() const {
488     return AttrList == 0;
489   }
490
491   /// getNumSlots - Return the number of slots used in this attribute list.
492   /// This is the number of arguments that have an attribute set on them
493   /// (including the function itself).
494   unsigned getNumSlots() const;
495
496   /// getSlot - Return the AttributeWithIndex at the specified slot.  This
497   /// holds a index number plus a set of attributes.
498   const AttributeWithIndex &getSlot(unsigned Slot) const;
499
500 private:
501   explicit AttrListPtr(AttributeListImpl *L);
502
503   /// getAttributes - The attributes for the specified index are
504   /// returned.  Attributes for the result are denoted with Idx = 0.
505   Attributes getAttributes(unsigned Idx) const;
506 };
507
508 } // End llvm namespace
509
510 #endif