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