Add accessor for the LLVMContext.
[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/DenseSet.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include <cassert>
23 #include <map>
24 #include <string>
25
26 namespace llvm {
27
28 class AttrBuilder;
29 class AttributeImpl;
30 class AttributeSetImpl;
31 class AttributeSetNode;
32 class Constant;
33 class LLVMContext;
34 class Type;
35
36 //===----------------------------------------------------------------------===//
37 /// \class
38 /// \brief Functions, function parameters, and return types can have attributes
39 /// to indicate how they should be treated by optimizations and code
40 /// generation. This class represents one of those attributes. It's light-weight
41 /// and should be passed around by-value.
42 class Attribute {
43 public:
44   /// This enumeration lists the attributes that can be associated with
45   /// parameters, function results, or the function itself.
46   ///
47   /// Note: The `uwtable' attribute is about the ABI or the user mandating an
48   /// entry in the unwind table. The `nounwind' attribute is about an exception
49   /// passing by the function.
50   ///
51   /// In a theoretical system that uses tables for profiling and SjLj for
52   /// exceptions, they would be fully independent. In a normal system that uses
53   /// tables for both, the semantics are:
54   ///
55   /// nil                = Needs an entry because an exception might pass by.
56   /// nounwind           = No need for an entry
57   /// uwtable            = Needs an entry because the ABI says so and because
58   ///                      an exception might pass by.
59   /// uwtable + nounwind = Needs an entry because the ABI says so.
60
61   enum AttrKind {
62     // IR-Level Attributes
63     None,                  ///< No attributes have been set
64     AddressSafety,         ///< Address safety checking is on.
65     Alignment,             ///< Alignment of parameter (5 bits)
66                            ///< stored as log2 of alignment with +1 bias
67                            ///< 0 means unaligned (different from align(1))
68     AlwaysInline,          ///< inline=always
69     ByVal,                 ///< Pass structure by value
70     InlineHint,            ///< Source said inlining was desirable
71     InReg,                 ///< Force argument to be passed in register
72     MinSize,               ///< Function must be optimized for size first
73     Naked,                 ///< Naked function
74     Nest,                  ///< Nested function static chain
75     NoAlias,               ///< Considered to not alias after call
76     NoCapture,             ///< Function creates no aliases of pointer
77     NoDuplicate,           ///< Call cannot be duplicated
78     NoImplicitFloat,       ///< Disable implicit floating point insts
79     NoInline,              ///< inline=never
80     NonLazyBind,           ///< Function is called early and/or
81                            ///< often, so lazy binding isn't worthwhile
82     NoRedZone,             ///< Disable redzone
83     NoReturn,              ///< Mark the function as not returning
84     NoUnwind,              ///< Function doesn't unwind stack
85     OptimizeForSize,       ///< opt_size
86     ReadNone,              ///< Function does not access memory
87     ReadOnly,              ///< Function only reads from memory
88     ReturnsTwice,          ///< Function can return twice
89     SExt,                  ///< Sign extended before/after call
90     StackAlignment,        ///< Alignment of stack for function (3 bits)
91                            ///< stored as log2 of alignment with +1 bias 0
92                            ///< means unaligned (different from
93                            ///< alignstack=(1))
94     StackProtect,          ///< Stack protection.
95     StackProtectReq,       ///< Stack protection required.
96     StackProtectStrong,    ///< Strong Stack protection.
97     StructRet,             ///< Hidden pointer to structure to return
98     UWTable,               ///< Function must be in a unwind table
99     ZExt,                  ///< Zero extended before/after call
100
101     EndAttrKinds,          ///< Sentinal value useful for loops
102
103     AttrKindEmptyKey,      ///< Empty key value for DenseMapInfo
104     AttrKindTombstoneKey   ///< Tombstone key value for DenseMapInfo
105   };
106 private:
107   AttributeImpl *pImpl;
108   Attribute(AttributeImpl *A) : pImpl(A) {}
109 public:
110   Attribute() : pImpl(0) {}
111
112   //===--------------------------------------------------------------------===//
113   // Attribute Construction
114   //===--------------------------------------------------------------------===//
115
116   /// \brief Return a uniquified Attribute object.
117   static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val = 0);
118   static Attribute get(LLVMContext &Context, StringRef Kind,
119                        StringRef Val = StringRef());
120
121   /// \brief Return a uniquified Attribute object that has the specific
122   /// alignment set.
123   static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align);
124   static Attribute getWithStackAlignment(LLVMContext &Context, uint64_t Align);
125
126   //===--------------------------------------------------------------------===//
127   // Attribute Accessors
128   //===--------------------------------------------------------------------===//
129
130   /// \brief Return true if the attribute is an Attribute::AttrKind type.
131   bool isEnumAttribute() const;
132
133   /// \brief Return true if the attribute is an alignment attribute.
134   bool isAlignAttribute() const;
135
136   /// \brief Return true if the attribute is a string (target-dependent)
137   /// attribute.
138   bool isStringAttribute() const;
139
140   /// \brief Return true if the attribute is present.
141   bool hasAttribute(AttrKind Val) const;
142
143   /// \brief Return true if the target-dependent attribute is present.
144   bool hasAttribute(StringRef Val) const;
145
146   /// \brief Return the attribute's kind as an enum (Attribute::AttrKind). This
147   /// requires the attribute to be an enum or alignment attribute.
148   Attribute::AttrKind getKindAsEnum() const;
149
150   /// \brief Return the attribute's value as an integer. This requires that the
151   /// attribute be an alignment attribute.
152   uint64_t getValueAsInt() const;
153
154   /// \brief Return the attribute's kind as a string. This requires the
155   /// attribute to be a string attribute.
156   StringRef getKindAsString() const;
157
158   /// \brief Return the attribute's value as a string. This requires the
159   /// attribute to be a string attribute.
160   StringRef getValueAsString() const;
161
162   /// \brief Returns the alignment field of an attribute as a byte alignment
163   /// value.
164   unsigned getAlignment() const;
165
166   /// \brief Returns the stack alignment field of an attribute as a byte
167   /// alignment value.
168   unsigned getStackAlignment() const;
169
170   /// \brief The Attribute is converted to a string of equivalent mnemonic. This
171   /// is, presumably, for writing out the mnemonics for the assembly writer.
172   std::string getAsString() const;
173
174   /// \brief Equality and non-equality operators.
175   bool operator==(Attribute A) const { return pImpl == A.pImpl; }
176   bool operator!=(Attribute A) const { return pImpl != A.pImpl; }
177
178   /// \brief Less-than operator. Useful for sorting the attributes list.
179   bool operator<(Attribute A) const;
180
181   void Profile(FoldingSetNodeID &ID) const {
182     ID.AddPointer(pImpl);
183   }
184 };
185
186 //===----------------------------------------------------------------------===//
187 /// \class
188 /// \brief Provide DenseMapInfo for Attribute::AttrKinds. This is used by
189 /// AttrBuilder.
190 template<> struct DenseMapInfo<Attribute::AttrKind> {
191   static inline Attribute::AttrKind getEmptyKey() {
192     return Attribute::AttrKindEmptyKey;
193   }
194   static inline Attribute::AttrKind getTombstoneKey() {
195     return Attribute::AttrKindTombstoneKey;
196   }
197   static unsigned getHashValue(const Attribute::AttrKind &Val) {
198     return Val * 37U;
199   }
200   static bool isEqual(const Attribute::AttrKind &LHS,
201                       const Attribute::AttrKind &RHS) {
202     return LHS == RHS;
203   }
204 };
205
206 //===----------------------------------------------------------------------===//
207 /// \class
208 /// \brief This class holds the attributes for a function, its return value, and
209 /// its parameters. You access the attributes for each of them via an index into
210 /// the AttributeSet object. The function attributes are at index
211 /// `AttributeSet::FunctionIndex', the return value is at index
212 /// `AttributeSet::ReturnIndex', and the attributes for the parameters start at
213 /// index `1'.
214 class AttributeSet {
215 public:
216   enum AttrIndex {
217     ReturnIndex = 0U,
218     FunctionIndex = ~0U
219   };
220 private:
221   friend class AttrBuilder;
222   friend class AttributeSetImpl;
223   template <typename Ty> friend struct DenseMapInfo;
224
225   /// \brief The attributes that we are managing. This can be null to represent
226   /// the empty attributes list.
227   AttributeSetImpl *pImpl;
228
229   /// \brief The attributes for the specified index are returned.
230   AttributeSetNode *getAttributes(unsigned Idx) const;
231
232   /// \brief Create an AttributeSet with the specified parameters in it.
233   static AttributeSet get(LLVMContext &C,
234                           ArrayRef<std::pair<unsigned, Attribute> > Attrs);
235   static AttributeSet get(LLVMContext &C,
236                           ArrayRef<std::pair<unsigned,
237                                              AttributeSetNode*> > Attrs);
238
239   static AttributeSet getImpl(LLVMContext &C,
240                               ArrayRef<std::pair<unsigned,
241                                                  AttributeSetNode*> > Attrs);
242
243
244   explicit AttributeSet(AttributeSetImpl *LI) : pImpl(LI) {}
245 public:
246   AttributeSet() : pImpl(0) {}
247   AttributeSet(const AttributeSet &P) : pImpl(P.pImpl) {}
248   const AttributeSet &operator=(const AttributeSet &RHS) {
249     pImpl = RHS.pImpl;
250     return *this;
251   }
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 Idx,
260                           ArrayRef<Attribute::AttrKind> Kind);
261   static AttributeSet get(LLVMContext &C, unsigned Idx, 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 Idx,
266                             Attribute::AttrKind Attr) const;
267
268   /// \brief Add attributes to the attribute set at the given index. Since
269   /// attribute sets are immutable, this returns a new set.
270   AttributeSet addAttributes(LLVMContext &C, unsigned Idx,
271                              AttributeSet Attrs) const;
272
273   /// \brief Remove the specified attribute at the specified index from this
274   /// attribute list. Since attribute lists are immutable, this returns the new
275   /// list.
276   AttributeSet removeAttribute(LLVMContext &C, unsigned Idx, 
277                                Attribute::AttrKind Attr) const;
278
279   /// \brief Remove the specified attributes at the specified index from this
280   /// attribute list. Since attribute lists are immutable, this returns the new
281   /// list.
282   AttributeSet removeAttributes(LLVMContext &C, unsigned Idx, 
283                                 AttributeSet Attrs) const;
284
285   //===--------------------------------------------------------------------===//
286   // AttributeSet Accessors
287   //===--------------------------------------------------------------------===//
288
289   /// \brief Retrieve the LLVM context.
290   LLVMContext &getContext() const;
291
292   /// \brief The attributes for the specified index are returned.
293   AttributeSet getParamAttributes(unsigned Idx) const;
294
295   /// \brief The attributes for the ret value are returned.
296   AttributeSet getRetAttributes() const;
297
298   /// \brief The function attributes are returned.
299   AttributeSet getFnAttributes() const;
300
301   /// \brief Return true if the attribute exists at the given index.
302   bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
303
304   /// \brief Return true if attribute exists at the given index.
305   bool hasAttributes(unsigned Index) const;
306
307   /// \brief Return true if the specified attribute is set for at least one
308   /// parameter or for the return value.
309   bool hasAttrSomewhere(Attribute::AttrKind Attr) const;
310
311   /// \brief Return the alignment for the specified function parameter.
312   unsigned getParamAlignment(unsigned Idx) const;
313
314   /// \brief Get the stack alignment.
315   unsigned getStackAlignment(unsigned Index) const;
316
317   /// \brief Return the attributes at the index as a string.
318   std::string getAsString(unsigned Index) const;
319
320   typedef ArrayRef<Attribute>::iterator iterator;
321
322   iterator begin(unsigned Idx) const;
323   iterator end(unsigned Idx) const;
324
325   /// operator==/!= - Provide equality predicates.
326   bool operator==(const AttributeSet &RHS) const {
327     return pImpl == RHS.pImpl;
328   }
329   bool operator!=(const AttributeSet &RHS) const {
330     return pImpl != RHS.pImpl;
331   }
332
333   //===--------------------------------------------------------------------===//
334   // AttributeSet Introspection
335   //===--------------------------------------------------------------------===//
336
337   // FIXME: Remove this.
338   uint64_t Raw(unsigned Index) const;
339
340   /// \brief Return a raw pointer that uniquely identifies this attribute list.
341   void *getRawPointer() const {
342     return pImpl;
343   }
344
345   /// \brief Return true if there are no attributes.
346   bool isEmpty() const {
347     return getNumSlots() == 0;
348   }
349
350   /// \brief Return the number of slots used in this attribute list.  This is
351   /// the number of arguments that have an attribute set on them (including the
352   /// function itself).
353   unsigned getNumSlots() const;
354
355   /// \brief Return the index for the given slot.
356   uint64_t getSlotIndex(unsigned Slot) const;
357
358   /// \brief Return the attributes at the given slot.
359   AttributeSet getSlotAttributes(unsigned Slot) const;
360
361   void dump() const;
362 };
363
364 //===----------------------------------------------------------------------===//
365 /// \class
366 /// \brief Provide DenseMapInfo for AttributeSet.
367 template<> struct DenseMapInfo<AttributeSet> {
368   static inline AttributeSet getEmptyKey() {
369     uintptr_t Val = static_cast<uintptr_t>(-1);
370     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
371     return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
372   }
373   static inline AttributeSet getTombstoneKey() {
374     uintptr_t Val = static_cast<uintptr_t>(-2);
375     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
376     return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
377   }
378   static unsigned getHashValue(AttributeSet AS) {
379     return (unsigned((uintptr_t)AS.pImpl) >> 4) ^
380            (unsigned((uintptr_t)AS.pImpl) >> 9);
381   }
382   static bool isEqual(AttributeSet LHS, AttributeSet RHS) { return LHS == RHS; }
383 };
384
385 //===----------------------------------------------------------------------===//
386 /// \class
387 /// \brief This class is used in conjunction with the Attribute::get method to
388 /// create an Attribute object. The object itself is uniquified. The Builder's
389 /// value, however, is not. So this can be used as a quick way to test for
390 /// equality, presence of attributes, etc.
391 class AttrBuilder {
392   DenseSet<Attribute::AttrKind> Attrs;
393   std::map<std::string, std::string> TargetDepAttrs;
394   uint64_t Alignment;
395   uint64_t StackAlignment;
396 public:
397   AttrBuilder() : Alignment(0), StackAlignment(0) {}
398   explicit AttrBuilder(uint64_t Val) : Alignment(0), StackAlignment(0) {
399     addRawValue(Val);
400   }
401   AttrBuilder(const Attribute &A) : Alignment(0), StackAlignment(0) {
402     addAttribute(A);
403   }
404   AttrBuilder(AttributeSet AS, unsigned Idx);
405   AttrBuilder(const AttrBuilder &B)
406     : Attrs(B.Attrs),
407       TargetDepAttrs(B.TargetDepAttrs.begin(), B.TargetDepAttrs.end()),
408       Alignment(B.Alignment), StackAlignment(B.StackAlignment) {}
409
410   void clear();
411
412   /// \brief Add an attribute to the builder.
413   AttrBuilder &addAttribute(Attribute::AttrKind Val);
414
415   /// \brief Add the Attribute object to the builder.
416   AttrBuilder &addAttribute(Attribute A);
417
418   /// \brief Add the target-dependent attribute to the builder.
419   AttrBuilder &addAttribute(StringRef A, StringRef V);
420
421   /// \brief Remove an attribute from the builder.
422   AttrBuilder &removeAttribute(Attribute::AttrKind Val);
423
424   /// \brief Remove the attributes from the builder.
425   AttrBuilder &removeAttributes(AttributeSet A, uint64_t Index);
426
427   /// \brief Remove the target-dependent attribute to the builder.
428   AttrBuilder &removeAttribute(StringRef A);
429
430   /// \brief Add the attributes from the builder.
431   AttrBuilder &merge(const AttrBuilder &B);
432
433   /// \brief Return true if the builder has the specified attribute.
434   bool contains(Attribute::AttrKind A) const;
435
436   /// \brief Return true if the builder has the specified target-dependent
437   /// attribute.
438   bool contains(StringRef A) const;
439
440   /// \brief Return true if the builder has IR-level attributes.
441   bool hasAttributes() const;
442
443   /// \brief Return true if the builder has any attribute that's in the
444   /// specified attribute.
445   bool hasAttributes(AttributeSet A, uint64_t Index) const;
446
447   /// \brief Return true if the builder has an alignment attribute.
448   bool hasAlignmentAttr() const;
449
450   /// \brief Retrieve the alignment attribute, if it exists.
451   uint64_t getAlignment() const { return Alignment; }
452
453   /// \brief Retrieve the stack alignment attribute, if it exists.
454   uint64_t getStackAlignment() const { return StackAlignment; }
455
456   /// \brief This turns an int alignment (which must be a power of 2) into the
457   /// form used internally in Attribute.
458   AttrBuilder &addAlignmentAttr(unsigned Align);
459
460   /// \brief This turns an int stack alignment (which must be a power of 2) into
461   /// the form used internally in Attribute.
462   AttrBuilder &addStackAlignmentAttr(unsigned Align);
463
464   // Iterators for target-independent attributes.
465   typedef DenseSet<Attribute::AttrKind>::iterator       iterator;
466   typedef DenseSet<Attribute::AttrKind>::const_iterator const_iterator;
467
468   iterator begin()             { return Attrs.begin(); }
469   iterator end()               { return Attrs.end(); }
470
471   const_iterator begin() const { return Attrs.begin(); }
472   const_iterator end() const   { return Attrs.end(); }
473
474   // Iterators for target-dependent attributes.
475   typedef std::pair<std::string, std::string>                td_type;
476   typedef std::map<std::string, std::string>::iterator       td_iterator;
477   typedef std::map<std::string, std::string>::const_iterator td_const_iterator;
478
479   td_iterator td_begin()             { return TargetDepAttrs.begin(); }
480   td_iterator td_end()               { return TargetDepAttrs.end(); }
481
482   td_const_iterator td_begin() const { return TargetDepAttrs.begin(); }
483   td_const_iterator td_end() const   { return TargetDepAttrs.end(); }
484
485   /// \brief Remove attributes that are used on functions only.
486   void removeFunctionOnlyAttrs() {
487     removeAttribute(Attribute::NoReturn)
488       .removeAttribute(Attribute::NoUnwind)
489       .removeAttribute(Attribute::ReadNone)
490       .removeAttribute(Attribute::ReadOnly)
491       .removeAttribute(Attribute::NoInline)
492       .removeAttribute(Attribute::AlwaysInline)
493       .removeAttribute(Attribute::OptimizeForSize)
494       .removeAttribute(Attribute::StackProtect)
495       .removeAttribute(Attribute::StackProtectReq)
496       .removeAttribute(Attribute::StackProtectStrong)
497       .removeAttribute(Attribute::NoRedZone)
498       .removeAttribute(Attribute::NoImplicitFloat)
499       .removeAttribute(Attribute::Naked)
500       .removeAttribute(Attribute::InlineHint)
501       .removeAttribute(Attribute::StackAlignment)
502       .removeAttribute(Attribute::UWTable)
503       .removeAttribute(Attribute::NonLazyBind)
504       .removeAttribute(Attribute::ReturnsTwice)
505       .removeAttribute(Attribute::AddressSafety)
506       .removeAttribute(Attribute::MinSize)
507       .removeAttribute(Attribute::NoDuplicate);
508   }
509
510   bool operator==(const AttrBuilder &B);
511   bool operator!=(const AttrBuilder &B) {
512     return !(*this == B);
513   }
514
515   // FIXME: Remove this in 4.0.
516
517   /// \brief Add the raw value to the internal representation.
518   AttrBuilder &addRawValue(uint64_t Val);
519 };
520
521 namespace AttributeFuncs {
522
523 /// \brief Which attributes cannot be applied to a type.
524 AttributeSet typeIncompatible(Type *Ty, uint64_t Index);
525
526 } // end AttributeFuncs namespace
527
528 } // end llvm namespace
529
530 #endif