e2a0a7ee395a2303b8106c19bc66a91e6fb62c48
[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     Convergent,            ///< Can only be moved to control-equivalent blocks
77     InlineHint,            ///< Source said inlining was desirable
78     InReg,                 ///< Force argument to be passed in register
79     JumpTable,             ///< Build jump-instruction tables and replace refs.
80     MinSize,               ///< Function must be optimized for size first
81     Naked,                 ///< Naked function
82     Nest,                  ///< Nested function static chain
83     NoAlias,               ///< Considered to not alias after call
84     NoBuiltin,             ///< Callee isn't recognized as a builtin
85     NoCapture,             ///< Function creates no aliases of pointer
86     NoDuplicate,           ///< Call cannot be duplicated
87     NoImplicitFloat,       ///< Disable implicit floating point insts
88     NoInline,              ///< inline=never
89     NonLazyBind,           ///< Function is called early and/or
90                            ///< often, so lazy binding isn't worthwhile
91     NonNull,               ///< Pointer is known to be not null
92     Dereferenceable,       ///< Pointer is known to be dereferenceable
93     DereferenceableOrNull, ///< Pointer is either null or dereferenceable
94     NoRedZone,             ///< Disable redzone
95     NoReturn,              ///< Mark the function as not returning
96     NoUnwind,              ///< Function doesn't unwind stack
97     OptimizeForSize,       ///< opt_size
98     OptimizeNone,          ///< Function must not be optimized.
99     ReadNone,              ///< Function does not access memory
100     ReadOnly,              ///< Function only reads from memory
101     Returned,              ///< Return value is always equal to this argument
102     ReturnsTwice,          ///< Function can return twice
103     SExt,                  ///< Sign extended before/after call
104     StackAlignment,        ///< Alignment of stack for function (3 bits)
105                            ///< stored as log2 of alignment with +1 bias 0
106                            ///< means unaligned (different from
107                            ///< alignstack=(1))
108     StackProtect,          ///< Stack protection.
109     StackProtectReq,       ///< Stack protection required.
110     StackProtectStrong,    ///< Strong Stack protection.
111     StructRet,             ///< Hidden pointer to structure to return
112     SanitizeAddress,       ///< AddressSanitizer is on.
113     SanitizeThread,        ///< ThreadSanitizer is on.
114     SanitizeMemory,        ///< MemorySanitizer is on.
115     UWTable,               ///< Function must be in a unwind table
116     ZExt,                  ///< Zero extended before/after call
117
118     EndAttrKinds           ///< Sentinal value useful for loops
119   };
120 private:
121   AttributeImpl *pImpl;
122   Attribute(AttributeImpl *A) : pImpl(A) {}
123 public:
124   Attribute() : pImpl(nullptr) {}
125
126   //===--------------------------------------------------------------------===//
127   // Attribute Construction
128   //===--------------------------------------------------------------------===//
129
130   /// \brief Return a uniquified Attribute object.
131   static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val = 0);
132   static Attribute get(LLVMContext &Context, StringRef Kind,
133                        StringRef Val = StringRef());
134
135   /// \brief Return a uniquified Attribute object that has the specific
136   /// alignment set.
137   static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align);
138   static Attribute getWithStackAlignment(LLVMContext &Context, uint64_t Align);
139   static Attribute getWithDereferenceableBytes(LLVMContext &Context,
140                                               uint64_t Bytes);
141   static Attribute getWithDereferenceableOrNullBytes(LLVMContext &Context,
142                                                      uint64_t Bytes);
143
144   //===--------------------------------------------------------------------===//
145   // Attribute Accessors
146   //===--------------------------------------------------------------------===//
147
148   /// \brief Return true if the attribute is an Attribute::AttrKind type.
149   bool isEnumAttribute() const;
150
151   /// \brief Return true if the attribute is an integer attribute.
152   bool isIntAttribute() const;
153
154   /// \brief Return true if the attribute is a string (target-dependent)
155   /// attribute.
156   bool isStringAttribute() const;
157
158   /// \brief Return true if the attribute is present.
159   bool hasAttribute(AttrKind Val) const;
160
161   /// \brief Return true if the target-dependent attribute is present.
162   bool hasAttribute(StringRef Val) const;
163
164   /// \brief Return the attribute's kind as an enum (Attribute::AttrKind). This
165   /// requires the attribute to be an enum or alignment attribute.
166   Attribute::AttrKind getKindAsEnum() const;
167
168   /// \brief Return the attribute's value as an integer. This requires that the
169   /// attribute be an alignment attribute.
170   uint64_t getValueAsInt() const;
171
172   /// \brief Return the attribute's kind as a string. This requires the
173   /// attribute to be a string attribute.
174   StringRef getKindAsString() const;
175
176   /// \brief Return the attribute's value as a string. This requires the
177   /// attribute to be a string attribute.
178   StringRef getValueAsString() const;
179
180   /// \brief Returns the alignment field of an attribute as a byte alignment
181   /// value.
182   unsigned getAlignment() const;
183
184   /// \brief Returns the stack alignment field of an attribute as a byte
185   /// alignment value.
186   unsigned getStackAlignment() const;
187
188   /// \brief Returns the number of dereferenceable bytes from the
189   /// dereferenceable attribute (or zero if unknown).
190   uint64_t getDereferenceableBytes() const;
191
192   /// \brief Returns the number of dereferenceable_or_null bytes from the
193   /// dereferenceable_or_null attribute (or zero if unknown).
194   uint64_t getDereferenceableOrNullBytes() const;
195
196   /// \brief The Attribute is converted to a string of equivalent mnemonic. This
197   /// is, presumably, for writing out the mnemonics for the assembly writer.
198   std::string getAsString(bool InAttrGrp = false) const;
199
200   /// \brief Equality and non-equality operators.
201   bool operator==(Attribute A) const { return pImpl == A.pImpl; }
202   bool operator!=(Attribute A) const { return pImpl != A.pImpl; }
203
204   /// \brief Less-than operator. Useful for sorting the attributes list.
205   bool operator<(Attribute A) const;
206
207   void Profile(FoldingSetNodeID &ID) const {
208     ID.AddPointer(pImpl);
209   }
210 };
211
212 //===----------------------------------------------------------------------===//
213 /// \class
214 /// \brief This class holds the attributes for a function, its return value, and
215 /// its parameters. You access the attributes for each of them via an index into
216 /// the AttributeSet object. The function attributes are at index
217 /// `AttributeSet::FunctionIndex', the return value is at index
218 /// `AttributeSet::ReturnIndex', and the attributes for the parameters start at
219 /// index `1'.
220 class AttributeSet {
221 public:
222   enum AttrIndex : unsigned {
223     ReturnIndex = 0U,
224     FunctionIndex = ~0U
225   };
226 private:
227   friend class AttrBuilder;
228   friend class AttributeSetImpl;
229   template <typename Ty> friend struct DenseMapInfo;
230
231   /// \brief The attributes that we are managing. This can be null to represent
232   /// the empty attributes list.
233   AttributeSetImpl *pImpl;
234
235   /// \brief The attributes for the specified index are returned.
236   AttributeSetNode *getAttributes(unsigned Index) const;
237
238   /// \brief Create an AttributeSet with the specified parameters in it.
239   static AttributeSet get(LLVMContext &C,
240                           ArrayRef<std::pair<unsigned, Attribute> > Attrs);
241   static AttributeSet get(LLVMContext &C,
242                           ArrayRef<std::pair<unsigned,
243                                              AttributeSetNode*> > Attrs);
244
245   static AttributeSet getImpl(LLVMContext &C,
246                               ArrayRef<std::pair<unsigned,
247                                                  AttributeSetNode*> > Attrs);
248
249
250   explicit AttributeSet(AttributeSetImpl *LI) : pImpl(LI) {}
251 public:
252   AttributeSet() : pImpl(nullptr) {}
253
254   //===--------------------------------------------------------------------===//
255   // AttributeSet Construction and Mutation
256   //===--------------------------------------------------------------------===//
257
258   /// \brief Return an AttributeSet with the specified parameters in it.
259   static AttributeSet get(LLVMContext &C, ArrayRef<AttributeSet> Attrs);
260   static AttributeSet get(LLVMContext &C, unsigned Index,
261                           ArrayRef<Attribute::AttrKind> Kind);
262   static AttributeSet get(LLVMContext &C, unsigned Index, const AttrBuilder &B);
263
264   /// \brief Add an attribute to the attribute set at the given index. Because
265   /// attribute sets are immutable, this returns a new set.
266   AttributeSet addAttribute(LLVMContext &C, unsigned Index,
267                             Attribute::AttrKind Attr) const;
268
269   /// \brief Add an attribute to the attribute set at the given index. Because
270   /// attribute sets are immutable, this returns a new set.
271   AttributeSet addAttribute(LLVMContext &C, unsigned Index,
272                             StringRef Kind) const;
273   AttributeSet addAttribute(LLVMContext &C, unsigned Index,
274                             StringRef Kind, StringRef Value) const;
275
276   /// \brief Add attributes to the attribute set at the given index. Because
277   /// attribute sets are immutable, this returns a new set.
278   AttributeSet addAttributes(LLVMContext &C, unsigned Index,
279                              AttributeSet Attrs) const;
280
281   /// \brief Remove the specified attribute at the specified index from this
282   /// attribute list. Because attribute lists are immutable, this returns the
283   /// new list.
284   AttributeSet removeAttribute(LLVMContext &C, unsigned Index, 
285                                Attribute::AttrKind Attr) const;
286
287   /// \brief Remove the specified attributes at the specified index from this
288   /// attribute list. Because attribute lists are immutable, this returns the
289   /// new list.
290   AttributeSet removeAttributes(LLVMContext &C, unsigned Index, 
291                                 AttributeSet Attrs) const;
292
293   /// \brief Remove the specified attributes at the specified index from this
294   /// attribute list. Because attribute lists are immutable, this returns the
295   /// new list.
296   AttributeSet removeAttributes(LLVMContext &C, unsigned Index,
297                                 const AttrBuilder &Attrs) const;
298
299   /// \brief Add the dereferenceable attribute to the attribute set at the given
300   /// index. Because attribute sets are immutable, this returns a new set.
301   AttributeSet addDereferenceableAttr(LLVMContext &C, unsigned Index,
302                                       uint64_t Bytes) const;
303
304   /// \brief Add the dereferenceable_or_null attribute to the attribute set at
305   /// the given index. Because attribute sets are immutable, this returns a new
306   /// set.
307   AttributeSet addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index,
308                                             uint64_t Bytes) const;
309
310   //===--------------------------------------------------------------------===//
311   // AttributeSet Accessors
312   //===--------------------------------------------------------------------===//
313
314   /// \brief Retrieve the LLVM context.
315   LLVMContext &getContext() const;
316
317   /// \brief The attributes for the specified index are returned.
318   AttributeSet getParamAttributes(unsigned Index) const;
319
320   /// \brief The attributes for the ret value are returned.
321   AttributeSet getRetAttributes() const;
322
323   /// \brief The function attributes are returned.
324   AttributeSet getFnAttributes() const;
325
326   /// \brief Return true if the attribute exists at the given index.
327   bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
328
329   /// \brief Return true if the attribute exists at the given index.
330   bool hasAttribute(unsigned Index, StringRef Kind) const;
331
332   /// \brief Return true if attribute exists at the given index.
333   bool hasAttributes(unsigned Index) const;
334
335   /// \brief Return true if the specified attribute is set for at least one
336   /// parameter or for the return value.
337   bool hasAttrSomewhere(Attribute::AttrKind Attr) const;
338
339   /// \brief Return the attribute object that exists at the given index.
340   Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const;
341
342   /// \brief Return the attribute object that exists at the given index.
343   Attribute getAttribute(unsigned Index, StringRef Kind) const;
344
345   /// \brief Return the alignment for the specified function parameter.
346   unsigned getParamAlignment(unsigned Index) const;
347
348   /// \brief Get the stack alignment.
349   unsigned getStackAlignment(unsigned Index) const;
350
351   /// \brief Get the number of dereferenceable bytes (or zero if unknown).
352   uint64_t getDereferenceableBytes(unsigned Index) const;
353
354   /// \brief Get the number of dereferenceable_or_null bytes (or zero if
355   /// unknown).
356   uint64_t getDereferenceableOrNullBytes(unsigned Index) const;
357
358   /// \brief Return the attributes at the index as a string.
359   std::string getAsString(unsigned Index, bool InAttrGrp = false) const;
360
361   typedef ArrayRef<Attribute>::iterator iterator;
362
363   iterator begin(unsigned Slot) const;
364   iterator end(unsigned Slot) const;
365
366   /// operator==/!= - Provide equality predicates.
367   bool operator==(const AttributeSet &RHS) const {
368     return pImpl == RHS.pImpl;
369   }
370   bool operator!=(const AttributeSet &RHS) const {
371     return pImpl != RHS.pImpl;
372   }
373
374   //===--------------------------------------------------------------------===//
375   // AttributeSet Introspection
376   //===--------------------------------------------------------------------===//
377
378   // FIXME: Remove this.
379   uint64_t Raw(unsigned Index) const;
380
381   /// \brief Return a raw pointer that uniquely identifies this attribute list.
382   void *getRawPointer() const {
383     return pImpl;
384   }
385
386   /// \brief Return true if there are no attributes.
387   bool isEmpty() const {
388     return getNumSlots() == 0;
389   }
390
391   /// \brief Return the number of slots used in this attribute list.  This is
392   /// the number of arguments that have an attribute set on them (including the
393   /// function itself).
394   unsigned getNumSlots() const;
395
396   /// \brief Return the index for the given slot.
397   unsigned getSlotIndex(unsigned Slot) const;
398
399   /// \brief Return the attributes at the given slot.
400   AttributeSet getSlotAttributes(unsigned Slot) const;
401
402   void dump() const;
403 };
404
405 //===----------------------------------------------------------------------===//
406 /// \class
407 /// \brief Provide DenseMapInfo for AttributeSet.
408 template<> struct DenseMapInfo<AttributeSet> {
409   static inline AttributeSet getEmptyKey() {
410     uintptr_t Val = static_cast<uintptr_t>(-1);
411     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
412     return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
413   }
414   static inline AttributeSet getTombstoneKey() {
415     uintptr_t Val = static_cast<uintptr_t>(-2);
416     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
417     return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
418   }
419   static unsigned getHashValue(AttributeSet AS) {
420     return (unsigned((uintptr_t)AS.pImpl) >> 4) ^
421            (unsigned((uintptr_t)AS.pImpl) >> 9);
422   }
423   static bool isEqual(AttributeSet LHS, AttributeSet RHS) { return LHS == RHS; }
424 };
425
426 //===----------------------------------------------------------------------===//
427 /// \class
428 /// \brief This class is used in conjunction with the Attribute::get method to
429 /// create an Attribute object. The object itself is uniquified. The Builder's
430 /// value, however, is not. So this can be used as a quick way to test for
431 /// equality, presence of attributes, etc.
432 class AttrBuilder {
433   std::bitset<Attribute::EndAttrKinds> Attrs;
434   std::map<std::string, std::string> TargetDepAttrs;
435   uint64_t Alignment;
436   uint64_t StackAlignment;
437   uint64_t DerefBytes;
438   uint64_t DerefOrNullBytes;
439 public:
440   AttrBuilder()
441       : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
442         DerefOrNullBytes(0) {}
443   explicit AttrBuilder(uint64_t Val)
444       : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
445         DerefOrNullBytes(0) {
446     addRawValue(Val);
447   }
448   AttrBuilder(const Attribute &A)
449       : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
450         DerefOrNullBytes(0) {
451     addAttribute(A);
452   }
453   AttrBuilder(AttributeSet AS, unsigned Idx);
454
455   void clear();
456
457   /// \brief Add an attribute to the builder.
458   AttrBuilder &addAttribute(Attribute::AttrKind Val);
459
460   /// \brief Add the Attribute object to the builder.
461   AttrBuilder &addAttribute(Attribute A);
462
463   /// \brief Add the target-dependent attribute to the builder.
464   AttrBuilder &addAttribute(StringRef A, StringRef V = StringRef());
465
466   /// \brief Remove an attribute from the builder.
467   AttrBuilder &removeAttribute(Attribute::AttrKind Val);
468
469   /// \brief Remove the attributes from the builder.
470   AttrBuilder &removeAttributes(AttributeSet A, uint64_t Index);
471
472   /// \brief Remove the target-dependent attribute to the builder.
473   AttrBuilder &removeAttribute(StringRef A);
474
475   /// \brief Add the attributes from the builder.
476   AttrBuilder &merge(const AttrBuilder &B);
477
478   /// \brief Remove the attributes from the builder.
479   AttrBuilder &remove(const AttrBuilder &B);
480
481   /// \brief Return true if the builder has any attribute that's in the
482   /// specified builder.
483   bool overlaps(const AttrBuilder &B) const;
484
485   /// \brief Return true if the builder has the specified attribute.
486   bool contains(Attribute::AttrKind A) const {
487     assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!");
488     return Attrs[A];
489   }
490
491   /// \brief Return true if the builder has the specified target-dependent
492   /// attribute.
493   bool contains(StringRef A) const;
494
495   /// \brief Return true if the builder has IR-level attributes.
496   bool hasAttributes() const;
497
498   /// \brief Return true if the builder has any attribute that's in the
499   /// specified attribute.
500   bool hasAttributes(AttributeSet A, uint64_t Index) const;
501
502   /// \brief Return true if the builder has an alignment attribute.
503   bool hasAlignmentAttr() const;
504
505   /// \brief Retrieve the alignment attribute, if it exists.
506   uint64_t getAlignment() const { return Alignment; }
507
508   /// \brief Retrieve the stack alignment attribute, if it exists.
509   uint64_t getStackAlignment() const { return StackAlignment; }
510
511   /// \brief Retrieve the number of dereferenceable bytes, if the dereferenceable
512   /// attribute exists (zero is returned otherwise).
513   uint64_t getDereferenceableBytes() const { return DerefBytes; }
514
515   /// \brief Retrieve the number of dereferenceable_or_null bytes, if the
516   /// dereferenceable_or_null attribute exists (zero is returned otherwise).
517   uint64_t getDereferenceableOrNullBytes() const { return DerefOrNullBytes; }
518
519   /// \brief This turns an int alignment (which must be a power of 2) into the
520   /// form used internally in Attribute.
521   AttrBuilder &addAlignmentAttr(unsigned Align);
522
523   /// \brief This turns an int stack alignment (which must be a power of 2) into
524   /// the form used internally in Attribute.
525   AttrBuilder &addStackAlignmentAttr(unsigned Align);
526
527   /// \brief This turns the number of dereferenceable bytes into the form used
528   /// internally in Attribute.
529   AttrBuilder &addDereferenceableAttr(uint64_t Bytes);
530
531   /// \brief This turns the number of dereferenceable_or_null bytes into the
532   /// form used internally in Attribute.
533   AttrBuilder &addDereferenceableOrNullAttr(uint64_t Bytes);
534
535   /// \brief Return true if the builder contains no target-independent
536   /// attributes.
537   bool empty() const { return Attrs.none(); }
538
539   // Iterators for target-dependent attributes.
540   typedef std::pair<std::string, std::string>                td_type;
541   typedef std::map<std::string, std::string>::iterator       td_iterator;
542   typedef std::map<std::string, std::string>::const_iterator td_const_iterator;
543   typedef llvm::iterator_range<td_iterator>                  td_range;
544   typedef llvm::iterator_range<td_const_iterator>            td_const_range;
545
546   td_iterator td_begin()             { return TargetDepAttrs.begin(); }
547   td_iterator td_end()               { return TargetDepAttrs.end(); }
548
549   td_const_iterator td_begin() const { return TargetDepAttrs.begin(); }
550   td_const_iterator td_end() const   { return TargetDepAttrs.end(); }
551
552   td_range td_attrs() { return td_range(td_begin(), td_end()); }
553   td_const_range td_attrs() const {
554     return td_const_range(td_begin(), td_end());
555   }
556
557   bool td_empty() const              { return TargetDepAttrs.empty(); }
558
559   bool operator==(const AttrBuilder &B);
560   bool operator!=(const AttrBuilder &B) {
561     return !(*this == B);
562   }
563
564   // FIXME: Remove this in 4.0.
565
566   /// \brief Add the raw value to the internal representation.
567   AttrBuilder &addRawValue(uint64_t Val);
568 };
569
570 namespace AttributeFuncs {
571
572 /// \brief Which attributes cannot be applied to a type.
573 AttrBuilder typeIncompatible(const Type *Ty);
574
575 } // end AttributeFuncs namespace
576
577 } // end llvm namespace
578
579 #endif