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