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