Add comment
[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 wierd 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 // Opaque types are considered to be first-class types.
33 // 
34 //===----------------------------------------------------------------------===//
35
36 #ifndef LLVM_TYPE_H
37 #define LLVM_TYPE_H
38
39 #include "AbstractTypeUser.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/ADT/GraphTraits.h"
42 #include "llvm/ADT/iterator"
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
55 class Type {
56 public:
57   ///===-------------------------------------------------------------------===//
58   /// Definitions of all of the base types for the Type system.  Based on this
59   /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
60   /// Note: If you add an element to this, you need to add an element to the 
61   /// Type::getPrimitiveType function, or else things will break!
62   ///
63   enum TypeID {
64     // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
65     VoidTyID = 0  , BoolTyID,           //  0, 1: Basics...
66     UByteTyID     , SByteTyID,          //  2, 3: 8 bit types...
67     UShortTyID    , ShortTyID,          //  4, 5: 16 bit types...
68     UIntTyID      , IntTyID,            //  6, 7: 32 bit types...
69     ULongTyID     , LongTyID,           //  8, 9: 64 bit types...
70     FloatTyID     , DoubleTyID,         // 10,11: Floating point types...
71     LabelTyID     ,                     // 12   : Labels... 
72
73     // Derived types... see DerivedTypes.h file...
74     // Make sure FirstDerivedTyID stays up to date!!!
75     FunctionTyID  , StructTyID,         // Functions... Structs...
76     ArrayTyID     , PointerTyID,        // Array... pointer...
77     OpaqueTyID,                         // Opaque type instances...
78     PackedTyID,                         // SIMD 'packed' format... 
79     //...
80
81     NumTypeIDs,                         // Must remain as last defined ID
82     LastPrimitiveTyID = LabelTyID,
83     FirstDerivedTyID = FunctionTyID,
84   };
85
86 private:
87   TypeID   ID : 8;    // The current base type of this type.
88   bool     Abstract;  // True if type contains an OpaqueType
89
90   /// RefCount - This counts the number of PATypeHolders that are pointing to
91   /// this type.  When this number falls to zero, if the type is abstract and
92   /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
93   /// derived types.
94   ///
95   mutable unsigned RefCount;
96
97   const Type *getForwardedTypeInternal() const;
98 protected:
99   Type(const std::string& Name, TypeID id);
100   virtual ~Type() {}
101
102   /// Types can become nonabstract later, if they are refined.
103   ///
104   inline void setAbstract(bool Val) { Abstract = Val; }
105
106   // PromoteAbstractToConcrete - This is an internal method used to calculate
107   // change "Abstract" from true to false when types are refined.
108   void PromoteAbstractToConcrete();
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 public:
127   virtual void print(std::ostream &O) const;
128
129   /// @brief Debugging support: print to stderr
130   virtual void dump() const;
131
132   //===--------------------------------------------------------------------===//
133   // Property accessors for dealing with types... Some of these virtual methods
134   // are defined in private classes defined in Type.cpp for primitive types.
135   //
136
137   /// getTypeID - Return the type id for the type.  This will return one
138   /// of the TypeID enum elements defined above.
139   ///
140   inline TypeID getTypeID() const { return ID; }
141
142   /// getDescription - Return the string representation of the type...
143   const std::string &getDescription() const;
144
145   /// isSigned - Return whether an integral numeric type is signed.  This is
146   /// true for SByteTy, ShortTy, IntTy, LongTy.  Note that this is not true for
147   /// Float and Double.
148   ///
149   bool isSigned() const {
150     return ID == SByteTyID || ID == ShortTyID || 
151            ID == IntTyID || ID == LongTyID; 
152   }
153   
154   /// isUnsigned - Return whether a numeric type is unsigned.  This is not quite
155   /// the complement of isSigned... nonnumeric types return false as they do
156   /// with isSigned.  This returns true for UByteTy, UShortTy, UIntTy, and
157   /// ULongTy
158   /// 
159   bool isUnsigned() const {
160     return ID == UByteTyID || ID == UShortTyID || 
161            ID == UIntTyID || ID == ULongTyID; 
162   }
163
164   /// isInteger - Equivalent to isSigned() || isUnsigned()
165   ///
166   bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
167
168   /// isIntegral - Returns true if this is an integral type, which is either
169   /// BoolTy or one of the Integer types.
170   ///
171   bool isIntegral() const { return isInteger() || this == BoolTy; }
172
173   /// isFloatingPoint - Return true if this is one of the two floating point
174   /// types
175   bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
176
177   /// isAbstract - True if the type is either an Opaque type, or is a derived
178   /// type that includes an opaque type somewhere in it.  
179   ///
180   inline bool isAbstract() const { return Abstract; }
181
182   /// isLosslesslyConvertibleTo - Return true if this type can be converted to
183   /// 'Ty' without any reinterpretation of bits.  For example, uint to int.
184   ///
185   bool isLosslesslyConvertibleTo(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   /// Note that we consider opaque types to be first class, as they may be
196   /// resolved to a first class type later.
197   inline bool isFirstClassType() const {
198     return (ID != VoidTyID && ID <= LastPrimitiveTyID) || 
199             ID == PointerTyID || ID == PackedTyID || ID == OpaqueTyID;
200   }
201
202   /// isSized - Return true if it makes sense to take the size of this type.  To
203   /// get the actual size for a particular target, it is reasonable to use the
204   /// TargetData subsystem to do this.
205   ///
206   bool isSized() const {
207     return (ID >= BoolTyID && ID <= DoubleTyID) || ID == PointerTyID || 
208            isSizedDerivedType();
209   }
210
211   /// getPrimitiveSize - Return the basic size of this type if it is a primitive
212   /// type.  These are fixed by LLVM and are not target dependent.  This will
213   /// return zero if the type does not have a size or is not a primitive type.
214   ///
215   unsigned getPrimitiveSize() const;
216
217   /// getUnsignedVersion - If this is an integer type, return the unsigned
218   /// variant of this type.  For example int -> uint.
219   const Type *getUnsignedVersion() const;
220
221   /// getSignedVersion - If this is an integer type, return the signed variant
222   /// of this type.  For example uint -> int.
223   const Type *getSignedVersion() const;
224
225   /// getForwaredType - Return the type that this type has been resolved to if
226   /// it has been resolved to anything.  This is used to implement the
227   /// union-find algorithm for type resolution, and shouldn't be used by general
228   /// purpose clients.
229   const Type *getForwardedType() const {
230     if (!ForwardType) return 0;
231     return getForwardedTypeInternal();
232   }
233
234   //===--------------------------------------------------------------------===//
235   // Type Iteration support
236   //
237   typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
238   subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
239   subtype_iterator subtype_end() const { return ContainedTys.end(); }
240
241   /// getContainedType - This method is used to implement the type iterator
242   /// (defined a the end of the file).  For derived types, this returns the
243   /// types 'contained' in the derived type.
244   ///
245   const Type *getContainedType(unsigned i) const {
246     assert(i < ContainedTys.size() && "Index out of range!");
247     return ContainedTys[i];
248   }
249
250   /// getNumContainedTypes - Return the number of types in the derived type.
251   ///
252   unsigned getNumContainedTypes() const { return ContainedTys.size(); }
253
254   //===--------------------------------------------------------------------===//
255   // Static members exported by the Type class itself.  Useful for getting
256   // instances of Type.
257   //
258
259   /// getPrimitiveType - Return a type based on an identifier.
260   static const Type *getPrimitiveType(TypeID IDNumber);
261
262   //===--------------------------------------------------------------------===//
263   // These are the builtin types that are always available...
264   //
265   static Type *VoidTy , *BoolTy;
266   static Type *SByteTy, *UByteTy,
267               *ShortTy, *UShortTy,
268               *IntTy  , *UIntTy, 
269               *LongTy , *ULongTy;
270   static Type *FloatTy, *DoubleTy;
271
272   static Type* LabelTy;
273
274   /// Methods for support type inquiry through isa, cast, and dyn_cast:
275   static inline bool classof(const Type *T) { return true; }
276
277 #include "llvm/Type.def"
278
279   // Virtual methods used by callbacks below.  These should only be implemented
280   // in the DerivedType class.
281   virtual void addAbstractTypeUser(AbstractTypeUser *U) const {
282     abort(); // Only on derived types!
283   }
284   virtual void removeAbstractTypeUser(AbstractTypeUser *U) const {
285     abort(); // Only on derived types!
286   }
287
288   void addRef() const {
289     assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
290     ++RefCount;
291   }
292   
293   void dropRef() const {
294     assert(isAbstract() && "Cannot drop a refernce to a non-abstract type!");
295     assert(RefCount && "No objects are currently referencing this object!");
296
297     // If this is the last PATypeHolder using this object, and there are no
298     // PATypeHandles using it, the type is dead, delete it now.
299     if (--RefCount == 0)
300       RefCountIsZero();
301   }
302 private:
303   /// isSizedDerivedType - Derived types like structures and arrays are sized
304   /// iff all of the members of the type are sized as well.  Since asking for
305   /// their size is relatively uncommon, move this operation out of line.
306   bool isSizedDerivedType() const;
307
308   virtual void RefCountIsZero() const {
309     abort(); // only on derived types!
310   }
311
312 };
313
314 //===----------------------------------------------------------------------===//
315 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
316 // These are defined here because they MUST be inlined, yet are dependent on 
317 // the definition of the Type class.  Of course Type derives from Value, which
318 // contains an AbstractTypeUser instance, so there is no good way to factor out
319 // the code.  Hence this bit of uglyness.
320 //
321 // In the long term, Type should not derive from Value, allowing
322 // AbstractTypeUser.h to #include Type.h, allowing us to eliminate this
323 // nastyness entirely.
324 //
325 inline void PATypeHandle::addUser() {
326   assert(Ty && "Type Handle has a null type!");
327   if (Ty->isAbstract())
328     Ty->addAbstractTypeUser(User);
329 }
330 inline void PATypeHandle::removeUser() {
331   if (Ty->isAbstract())
332     Ty->removeAbstractTypeUser(User);
333 }
334
335 inline void PATypeHandle::removeUserFromConcrete() {
336   if (!Ty->isAbstract())
337     Ty->removeAbstractTypeUser(User);
338 }
339
340 // Define inline methods for PATypeHolder...
341
342 inline void PATypeHolder::addRef() {
343   if (Ty->isAbstract())
344     Ty->addRef();
345 }
346
347 inline void PATypeHolder::dropRef() {
348   if (Ty->isAbstract())
349     Ty->dropRef();
350 }
351
352 /// get - This implements the forwarding part of the union-find algorithm for
353 /// abstract types.  Before every access to the Type*, we check to see if the
354 /// type we are pointing to is forwarding to a new type.  If so, we drop our
355 /// reference to the type.
356 ///
357 inline Type* PATypeHolder::get() const {
358   const Type *NewTy = Ty->getForwardedType();
359   if (!NewTy) return const_cast<Type*>(Ty);
360   return *const_cast<PATypeHolder*>(this) = NewTy;
361 }
362
363
364
365 //===----------------------------------------------------------------------===//
366 // Provide specializations of GraphTraits to be able to treat a type as a 
367 // graph of sub types...
368
369 template <> struct GraphTraits<Type*> {
370   typedef Type NodeType;
371   typedef Type::subtype_iterator ChildIteratorType;
372
373   static inline NodeType *getEntryNode(Type *T) { return T; }
374   static inline ChildIteratorType child_begin(NodeType *N) { 
375     return N->subtype_begin(); 
376   }
377   static inline ChildIteratorType child_end(NodeType *N) { 
378     return N->subtype_end();
379   }
380 };
381
382 template <> struct GraphTraits<const Type*> {
383   typedef const Type NodeType;
384   typedef Type::subtype_iterator ChildIteratorType;
385
386   static inline NodeType *getEntryNode(const Type *T) { return T; }
387   static inline ChildIteratorType child_begin(NodeType *N) { 
388     return N->subtype_begin(); 
389   }
390   static inline ChildIteratorType child_end(NodeType *N) { 
391     return N->subtype_end();
392   }
393 };
394
395 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) { 
396   return Ty.getTypeID() == Type::PointerTyID;
397 }
398
399 std::ostream &operator<<(std::ostream &OS, const Type &T);
400
401 } // End llvm namespace
402
403 #endif