Type.h revision 42a75517250017a52afb03a0ade03cbd49559fe5
1//===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#ifndef LLVM_TYPE_H
12#define LLVM_TYPE_H
13
14#include "llvm/AbstractTypeUser.h"
15#include "llvm/Support/Casting.h"
16#include "llvm/Support/DataTypes.h"
17#include "llvm/Support/Streams.h"
18#include "llvm/ADT/GraphTraits.h"
19#include "llvm/ADT/iterator"
20#include <string>
21#include <vector>
22
23namespace llvm {
24
25class ArrayType;
26class DerivedType;
27class FunctionType;
28class OpaqueType;
29class PointerType;
30class StructType;
31class PackedType;
32class TypeMapBase;
33
34/// This file contains the declaration of the Type class.  For more "Type" type
35/// stuff, look in DerivedTypes.h.
36///
37/// The instances of the Type class are immutable: once they are created,
38/// they are never changed.  Also note that only one instance of a particular
39/// type is ever created.  Thus seeing if two types are equal is a matter of
40/// doing a trivial pointer comparison. To enforce that no two equal instances
41/// are created, Type instances can only be created via static factory methods
42/// in class Type and in derived classes.
43///
44/// Once allocated, Types are never free'd, unless they are an abstract type
45/// that is resolved to a more concrete type.
46///
47/// Types themself don't have a name, and can be named either by:
48/// - using SymbolTable instance, typically from some Module,
49/// - using convenience methods in the Module class (which uses module's
50///    SymbolTable too).
51///
52/// Opaque types are simple derived types with no state.  There may be many
53/// different Opaque type objects floating around, but two are only considered
54/// identical if they are pointer equals of each other.  This allows us to have
55/// two opaque types that end up resolving to different concrete types later.
56///
57/// Opaque types are also kinda weird and scary and different because they have
58/// to keep a list of uses of the type.  When, through linking, parsing, or
59/// bytecode reading, they become resolved, they need to find and update all
60/// users of the unknown type, causing them to reference a new, more concrete
61/// type.  Opaque types are deleted when their use list dwindles to zero users.
62///
63/// @brief Root of type hierarchy
64class Type : public AbstractTypeUser {
65public:
66  ///===-------------------------------------------------------------------===//
67  /// Definitions of all of the base types for the Type system.  Based on this
68  /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
69  /// Note: If you add an element to this, you need to add an element to the
70  /// Type::getPrimitiveType function, or else things will break!
71  ///
72  enum TypeID {
73    // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
74    VoidTyID = 0,    ///<  0: type with no size
75    FloatTyID,       ///<  1: 32 bit floating point type
76    DoubleTyID,      ///<  2: 64 bit floating point type
77    LabelTyID,       ///<  3: Labels
78
79    // Derived types... see DerivedTypes.h file...
80    // Make sure FirstDerivedTyID stays up to date!!!
81    IntegerTyID,     ///<  4: Arbitrary bit width integers
82    FunctionTyID,    ///<  5: Functions
83    StructTyID,      ///<  6: Structures
84    PackedStructTyID,///<  7: Packed Structure. This is for bytecode only
85    ArrayTyID,       ///<  8: Arrays
86    PointerTyID,     ///<  9: Pointers
87    OpaqueTyID,      ///< 10: Opaque: type with unknown structure
88    PackedTyID,      ///< 11: SIMD 'packed' format, or other vector type
89
90    NumTypeIDs,                         // Must remain as last defined ID
91    LastPrimitiveTyID = LabelTyID,
92    FirstDerivedTyID = IntegerTyID
93  };
94
95private:
96  TypeID   ID : 8;    // The current base type of this type.
97  bool     Abstract : 1;  // True if type contains an OpaqueType
98  unsigned SubclassData : 23; //Space for subclasses to store data
99
100  /// RefCount - This counts the number of PATypeHolders that are pointing to
101  /// this type.  When this number falls to zero, if the type is abstract and
102  /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
103  /// derived types.
104  ///
105  mutable unsigned RefCount;
106
107  const Type *getForwardedTypeInternal() const;
108protected:
109  Type(const char *Name, TypeID id);
110  Type(TypeID id) : ID(id), Abstract(false), SubclassData(0), RefCount(0),
111                    ForwardType(0) {}
112  virtual ~Type() {
113    assert(AbstractTypeUsers.empty());
114  }
115
116  /// Types can become nonabstract later, if they are refined.
117  ///
118  inline void setAbstract(bool Val) { Abstract = Val; }
119
120  unsigned getRefCount() const { return RefCount; }
121
122  unsigned getSubclassData() const { return SubclassData; }
123  void setSubclassData(unsigned val) { SubclassData = val; }
124
125  /// ForwardType - This field is used to implement the union find scheme for
126  /// abstract types.  When types are refined to other types, this field is set
127  /// to the more refined type.  Only abstract types can be forwarded.
128  mutable const Type *ForwardType;
129
130  /// ContainedTys - The list of types contained by this one.  For example, this
131  /// includes the arguments of a function type, the elements of the structure,
132  /// the pointee of a pointer, etc.  Note that keeping this vector in the Type
133  /// class wastes some space for types that do not contain anything (such as
134  /// primitive types).  However, keeping it here allows the subtype_* members
135  /// to be implemented MUCH more efficiently, and dynamically very few types do
136  /// not contain any elements (most are derived).
137  std::vector<PATypeHandle> ContainedTys;
138
139  /// AbstractTypeUsers - Implement a list of the users that need to be notified
140  /// if I am a type, and I get resolved into a more concrete type.
141  ///
142  mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
143public:
144  void print(std::ostream &O) const;
145  void print(std::ostream *O) const { if (O) print(*O); }
146
147  /// @brief Debugging support: print to stderr
148  void dump() const;
149
150  //===--------------------------------------------------------------------===//
151  // Property accessors for dealing with types... Some of these virtual methods
152  // are defined in private classes defined in Type.cpp for primitive types.
153  //
154
155  /// getTypeID - Return the type id for the type.  This will return one
156  /// of the TypeID enum elements defined above.
157  ///
158  inline TypeID getTypeID() const { return ID; }
159
160  /// getDescription - Return the string representation of the type...
161  const std::string &getDescription() const;
162
163  /// isInteger - True if this is an instance of IntegerType.
164  ///
165  bool isInteger() const { return ID == IntegerTyID; }
166
167  /// isFloatingPoint - Return true if this is one of the two floating point
168  /// types
169  bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
170
171  /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
172  ///
173  bool isFPOrFPVector() const;
174
175  /// isAbstract - True if the type is either an Opaque type, or is a derived
176  /// type that includes an opaque type somewhere in it.
177  ///
178  inline bool isAbstract() const { return Abstract; }
179
180  /// canLosslesslyBitCastTo - Return true if this type could be converted
181  /// with a lossless BitCast to type 'Ty'. For example, uint to int. BitCasts
182  /// are valid for types of the same size only where no re-interpretation of
183  /// the bits is done.
184  /// @brief Determine if this type could be losslessly bitcast to Ty
185  bool canLosslesslyBitCastTo(const Type *Ty) const;
186
187
188  /// Here are some useful little methods to query what type derived types are
189  /// Note that all other types can just compare to see if this == Type::xxxTy;
190  ///
191  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
192  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
193
194  /// isFirstClassType - Return true if the value is holdable in a register.
195  ///
196  inline bool isFirstClassType() const {
197    return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
198            ID == IntegerTyID || ID == PointerTyID || ID == PackedTyID;
199  }
200
201  /// isSized - Return true if it makes sense to take the size of this type.  To
202  /// get the actual size for a particular target, it is reasonable to use the
203  /// TargetData subsystem to do this.
204  ///
205  bool isSized() const {
206    // If it's a primitive, it is always sized.
207    if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
208      return true;
209    // If it is not something that can have a size (e.g. a function or label),
210    // it doesn't have a size.
211    if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID &&
212        ID != PackedStructTyID)
213      return false;
214    // If it is something that can have a size and it's concrete, it definitely
215    // has a size, otherwise we have to try harder to decide.
216    return !isAbstract() || isSizedDerivedType();
217  }
218
219  /// getPrimitiveSize - Return the basic size of this type if it is a primitive
220  /// type.  These are fixed by LLVM and are not target dependent.  This will
221  /// return zero if the type does not have a size or is not a primitive type.
222  ///
223  unsigned getPrimitiveSizeInBits() const;
224
225  /// getIntegerTypeMask - Return a bitmask with ones set for all of the bits
226  /// that can be set by an unsigned version of this type.  This is 0xFF for
227  /// sbyte/ubyte, 0xFFFF for shorts, etc.
228  uint64_t getIntegerTypeMask() const {
229    assert(isInteger() && "This only works for integer types!");
230    return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
231  }
232
233  /// getForwaredType - Return the type that this type has been resolved to if
234  /// it has been resolved to anything.  This is used to implement the
235  /// union-find algorithm for type resolution, and shouldn't be used by general
236  /// purpose clients.
237  const Type *getForwardedType() const {
238    if (!ForwardType) return 0;
239    return getForwardedTypeInternal();
240  }
241
242  /// getVAArgsPromotedType - Return the type an argument of this type
243  /// will be promoted to if passed through a variable argument
244  /// function.
245  const Type *getVAArgsPromotedType() const {
246    if (ID == IntegerTyID && getSubclassData() < 32)
247      return Type::Int32Ty;
248    else if (ID == FloatTyID)
249      return Type::DoubleTy;
250    else
251      return this;
252  }
253
254  //===--------------------------------------------------------------------===//
255  // Type Iteration support
256  //
257  typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
258  subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
259  subtype_iterator subtype_end() const { return ContainedTys.end(); }
260
261  /// getContainedType - This method is used to implement the type iterator
262  /// (defined a the end of the file).  For derived types, this returns the
263  /// types 'contained' in the derived type.
264  ///
265  const Type *getContainedType(unsigned i) const {
266    assert(i < ContainedTys.size() && "Index out of range!");
267    return ContainedTys[i];
268  }
269
270  /// getNumContainedTypes - Return the number of types in the derived type.
271  ///
272  typedef std::vector<PATypeHandle>::size_type size_type;
273  size_type getNumContainedTypes() const { return ContainedTys.size(); }
274
275  //===--------------------------------------------------------------------===//
276  // Static members exported by the Type class itself.  Useful for getting
277  // instances of Type.
278  //
279
280  /// getPrimitiveType - Return a type based on an identifier.
281  static const Type *getPrimitiveType(TypeID IDNumber);
282
283  //===--------------------------------------------------------------------===//
284  // These are the builtin types that are always available...
285  //
286  static const Type *VoidTy, *LabelTy, *FloatTy, *DoubleTy;
287  static const Type *Int1Ty, *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
288
289  /// Methods for support type inquiry through isa, cast, and dyn_cast:
290  static inline bool classof(const Type *T) { return true; }
291
292  void addRef() const {
293    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
294    ++RefCount;
295  }
296
297  void dropRef() const {
298    assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
299    assert(RefCount && "No objects are currently referencing this object!");
300
301    // If this is the last PATypeHolder using this object, and there are no
302    // PATypeHandles using it, the type is dead, delete it now.
303    if (--RefCount == 0 && AbstractTypeUsers.empty())
304      delete this;
305  }
306
307  /// addAbstractTypeUser - Notify an abstract type that there is a new user of
308  /// it.  This function is called primarily by the PATypeHandle class.
309  ///
310  void addAbstractTypeUser(AbstractTypeUser *U) const {
311    assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
312    AbstractTypeUsers.push_back(U);
313  }
314
315  /// removeAbstractTypeUser - Notify an abstract type that a user of the class
316  /// no longer has a handle to the type.  This function is called primarily by
317  /// the PATypeHandle class.  When there are no users of the abstract type, it
318  /// is annihilated, because there is no way to get a reference to it ever
319  /// again.
320  ///
321  void removeAbstractTypeUser(AbstractTypeUser *U) const;
322
323private:
324  /// isSizedDerivedType - Derived types like structures and arrays are sized
325  /// iff all of the members of the type are sized as well.  Since asking for
326  /// their size is relatively uncommon, move this operation out of line.
327  bool isSizedDerivedType() const;
328
329  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
330  virtual void typeBecameConcrete(const DerivedType *AbsTy);
331
332protected:
333  // PromoteAbstractToConcrete - This is an internal method used to calculate
334  // change "Abstract" from true to false when types are refined.
335  void PromoteAbstractToConcrete();
336  friend class TypeMapBase;
337};
338
339//===----------------------------------------------------------------------===//
340// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
341// These are defined here because they MUST be inlined, yet are dependent on
342// the definition of the Type class.
343//
344inline void PATypeHandle::addUser() {
345  assert(Ty && "Type Handle has a null type!");
346  if (Ty->isAbstract())
347    Ty->addAbstractTypeUser(User);
348}
349inline void PATypeHandle::removeUser() {
350  if (Ty->isAbstract())
351    Ty->removeAbstractTypeUser(User);
352}
353
354// Define inline methods for PATypeHolder...
355
356inline void PATypeHolder::addRef() {
357  if (Ty->isAbstract())
358    Ty->addRef();
359}
360
361inline void PATypeHolder::dropRef() {
362  if (Ty->isAbstract())
363    Ty->dropRef();
364}
365
366
367//===----------------------------------------------------------------------===//
368// Provide specializations of GraphTraits to be able to treat a type as a
369// graph of sub types...
370
371template <> struct GraphTraits<Type*> {
372  typedef Type NodeType;
373  typedef Type::subtype_iterator ChildIteratorType;
374
375  static inline NodeType *getEntryNode(Type *T) { return T; }
376  static inline ChildIteratorType child_begin(NodeType *N) {
377    return N->subtype_begin();
378  }
379  static inline ChildIteratorType child_end(NodeType *N) {
380    return N->subtype_end();
381  }
382};
383
384template <> struct GraphTraits<const Type*> {
385  typedef const Type NodeType;
386  typedef Type::subtype_iterator ChildIteratorType;
387
388  static inline NodeType *getEntryNode(const Type *T) { return T; }
389  static inline ChildIteratorType child_begin(NodeType *N) {
390    return N->subtype_begin();
391  }
392  static inline ChildIteratorType child_end(NodeType *N) {
393    return N->subtype_end();
394  }
395};
396
397template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
398  return Ty.getTypeID() == Type::PointerTyID;
399}
400
401std::ostream &operator<<(std::ostream &OS, const Type &T);
402
403} // End llvm namespace
404
405#endif
406