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