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