9ceed26e60287c027c7f398f5a448ff9956f3328
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Type class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/RWMutex.h"
29 #include "llvm/System/Threading.h"
30 #include <algorithm>
31 #include <cstdarg>
32 using namespace llvm;
33
34 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
35 // created and later destroyed, all in an effort to make sure that there is only
36 // a single canonical version of a type.
37 //
38 // #define DEBUG_MERGE_TYPES 1
39
40 AbstractTypeUser::~AbstractTypeUser() {}
41
42
43 //===----------------------------------------------------------------------===//
44 //                         Type Class Implementation
45 //===----------------------------------------------------------------------===//
46
47 // Lock used for guarding access to the type maps.
48 static ManagedStatic<sys::SmartMutex<true> > TypeMapLock;
49
50 // Recursive lock used for guarding access to AbstractTypeUsers.
51 // NOTE: The true template parameter means this will no-op when we're not in
52 // multithreaded mode.
53 static ManagedStatic<sys::SmartMutex<true> > AbstractTypeUsersLock;
54
55 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
56 // for types as they are needed.  Because resolution of types must invalidate
57 // all of the abstract type descriptions, we keep them in a seperate map to make
58 // this easy.
59 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
60 static ManagedStatic<TypePrinting> AbstractTypeDescriptions;
61
62 /// Because of the way Type subclasses are allocated, this function is necessary
63 /// to use the correct kind of "delete" operator to deallocate the Type object.
64 /// Some type objects (FunctionTy, StructTy) allocate additional space after 
65 /// the space for their derived type to hold the contained types array of
66 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
67 /// allocated with the type object, decreasing allocations and eliminating the
68 /// need for a std::vector to be used in the Type class itself. 
69 /// @brief Type destruction function
70 void Type::destroy() const {
71
72   // Structures and Functions allocate their contained types past the end of
73   // the type object itself. These need to be destroyed differently than the
74   // other types.
75   if (isa<FunctionType>(this) || isa<StructType>(this)) {
76     // First, make sure we destruct any PATypeHandles allocated by these
77     // subclasses.  They must be manually destructed. 
78     for (unsigned i = 0; i < NumContainedTys; ++i)
79       ContainedTys[i].PATypeHandle::~PATypeHandle();
80
81     // Now call the destructor for the subclass directly because we're going
82     // to delete this as an array of char.
83     if (isa<FunctionType>(this))
84       static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
85     else
86       static_cast<const StructType*>(this)->StructType::~StructType();
87
88     // Finally, remove the memory as an array deallocation of the chars it was
89     // constructed from.
90     operator delete(const_cast<Type *>(this));
91
92     return;
93   }
94
95   // For all the other type subclasses, there is either no contained types or 
96   // just one (all Sequentials). For Sequentials, the PATypeHandle is not
97   // allocated past the type object, its included directly in the SequentialType
98   // class. This means we can safely just do "normal" delete of this object and
99   // all the destructors that need to run will be run.
100   delete this; 
101 }
102
103 const Type *Type::getPrimitiveType(TypeID IDNumber) {
104   switch (IDNumber) {
105   case VoidTyID      : return VoidTy;
106   case FloatTyID     : return FloatTy;
107   case DoubleTyID    : return DoubleTy;
108   case X86_FP80TyID  : return X86_FP80Ty;
109   case FP128TyID     : return FP128Ty;
110   case PPC_FP128TyID : return PPC_FP128Ty;
111   case LabelTyID     : return LabelTy;
112   case MetadataTyID  : return MetadataTy;
113   default:
114     return 0;
115   }
116 }
117
118 const Type *Type::getVAArgsPromotedType() const {
119   if (ID == IntegerTyID && getSubclassData() < 32)
120     return Type::Int32Ty;
121   else if (ID == FloatTyID)
122     return Type::DoubleTy;
123   else
124     return this;
125 }
126
127 /// getScalarType - If this is a vector type, return the element type,
128 /// otherwise return this.
129 const Type *Type::getScalarType() const {
130   if (const VectorType *VTy = dyn_cast<VectorType>(this))
131     return VTy->getElementType();
132   return this;
133 }
134
135 /// isIntOrIntVector - Return true if this is an integer type or a vector of
136 /// integer types.
137 ///
138 bool Type::isIntOrIntVector() const {
139   if (isInteger())
140     return true;
141   if (ID != Type::VectorTyID) return false;
142   
143   return cast<VectorType>(this)->getElementType()->isInteger();
144 }
145
146 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
147 ///
148 bool Type::isFPOrFPVector() const {
149   if (ID == Type::FloatTyID || ID == Type::DoubleTyID || 
150       ID == Type::FP128TyID || ID == Type::X86_FP80TyID || 
151       ID == Type::PPC_FP128TyID)
152     return true;
153   if (ID != Type::VectorTyID) return false;
154   
155   return cast<VectorType>(this)->getElementType()->isFloatingPoint();
156 }
157
158 // canLosslesslyBitCastTo - Return true if this type can be converted to
159 // 'Ty' without any reinterpretation of bits.  For example, i8* to i32*.
160 //
161 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
162   // Identity cast means no change so return true
163   if (this == Ty) 
164     return true;
165   
166   // They are not convertible unless they are at least first class types
167   if (!this->isFirstClassType() || !Ty->isFirstClassType())
168     return false;
169
170   // Vector -> Vector conversions are always lossless if the two vector types
171   // have the same size, otherwise not.
172   if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
173     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
174       return thisPTy->getBitWidth() == thatPTy->getBitWidth();
175
176   // At this point we have only various mismatches of the first class types
177   // remaining and ptr->ptr. Just select the lossless conversions. Everything
178   // else is not lossless.
179   if (isa<PointerType>(this))
180     return isa<PointerType>(Ty);
181   return false;  // Other types have no identity values
182 }
183
184 unsigned Type::getPrimitiveSizeInBits() const {
185   switch (getTypeID()) {
186   case Type::FloatTyID: return 32;
187   case Type::DoubleTyID: return 64;
188   case Type::X86_FP80TyID: return 80;
189   case Type::FP128TyID: return 128;
190   case Type::PPC_FP128TyID: return 128;
191   case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
192   case Type::VectorTyID:  return cast<VectorType>(this)->getBitWidth();
193   default: return 0;
194   }
195 }
196
197 /// getScalarSizeInBits - If this is a vector type, return the
198 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
199 /// getPrimitiveSizeInBits value for this type.
200 unsigned Type::getScalarSizeInBits() const {
201   return getScalarType()->getPrimitiveSizeInBits();
202 }
203
204 /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
205 /// is only valid on floating point types.  If the FP type does not
206 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
207 int Type::getFPMantissaWidth() const {
208   if (const VectorType *VTy = dyn_cast<VectorType>(this))
209     return VTy->getElementType()->getFPMantissaWidth();
210   assert(isFloatingPoint() && "Not a floating point type!");
211   if (ID == FloatTyID) return 24;
212   if (ID == DoubleTyID) return 53;
213   if (ID == X86_FP80TyID) return 64;
214   if (ID == FP128TyID) return 113;
215   assert(ID == PPC_FP128TyID && "unknown fp type");
216   return -1;
217 }
218
219 /// isSizedDerivedType - Derived types like structures and arrays are sized
220 /// iff all of the members of the type are sized as well.  Since asking for
221 /// their size is relatively uncommon, move this operation out of line.
222 bool Type::isSizedDerivedType() const {
223   if (isa<IntegerType>(this))
224     return true;
225
226   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
227     return ATy->getElementType()->isSized();
228
229   if (const VectorType *PTy = dyn_cast<VectorType>(this))
230     return PTy->getElementType()->isSized();
231
232   if (!isa<StructType>(this)) 
233     return false;
234
235   // Okay, our struct is sized if all of the elements are...
236   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
237     if (!(*I)->isSized()) 
238       return false;
239
240   return true;
241 }
242
243 /// getForwardedTypeInternal - This method is used to implement the union-find
244 /// algorithm for when a type is being forwarded to another type.
245 const Type *Type::getForwardedTypeInternal() const {
246   assert(ForwardType && "This type is not being forwarded to another type!");
247
248   // Check to see if the forwarded type has been forwarded on.  If so, collapse
249   // the forwarding links.
250   const Type *RealForwardedType = ForwardType->getForwardedType();
251   if (!RealForwardedType)
252     return ForwardType;  // No it's not forwarded again
253
254   // Yes, it is forwarded again.  First thing, add the reference to the new
255   // forward type.
256   if (RealForwardedType->isAbstract())
257     cast<DerivedType>(RealForwardedType)->addRef();
258
259   // Now drop the old reference.  This could cause ForwardType to get deleted.
260   cast<DerivedType>(ForwardType)->dropRef();
261
262   // Return the updated type.
263   ForwardType = RealForwardedType;
264   return ForwardType;
265 }
266
267 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
268   llvm_unreachable("Attempting to refine a derived type!");
269 }
270 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
271   llvm_unreachable("DerivedType is already a concrete type!");
272 }
273
274
275 std::string Type::getDescription() const {
276   TypePrinting &Map =
277     isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
278   
279   std::string DescStr;
280   raw_string_ostream DescOS(DescStr);
281   Map.print(this, DescOS);
282   return DescOS.str();
283 }
284
285
286 bool StructType::indexValid(const Value *V) const {
287   // Structure indexes require 32-bit integer constants.
288   if (V->getType() == Type::Int32Ty)
289     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
290       return indexValid(CU->getZExtValue());
291   return false;
292 }
293
294 bool StructType::indexValid(unsigned V) const {
295   return V < NumContainedTys;
296 }
297
298 // getTypeAtIndex - Given an index value into the type, return the type of the
299 // element.  For a structure type, this must be a constant value...
300 //
301 const Type *StructType::getTypeAtIndex(const Value *V) const {
302   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
303   return getTypeAtIndex(Idx);
304 }
305
306 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
307   assert(indexValid(Idx) && "Invalid structure index!");
308   return ContainedTys[Idx];
309 }
310
311 //===----------------------------------------------------------------------===//
312 //                          Primitive 'Type' data
313 //===----------------------------------------------------------------------===//
314
315 const Type *Type::VoidTy       = new Type(Type::VoidTyID);
316 const Type *Type::FloatTy      = new Type(Type::FloatTyID);
317 const Type *Type::DoubleTy     = new Type(Type::DoubleTyID);
318 const Type *Type::X86_FP80Ty   = new Type(Type::X86_FP80TyID);
319 const Type *Type::FP128Ty      = new Type(Type::FP128TyID);
320 const Type *Type::PPC_FP128Ty  = new Type(Type::PPC_FP128TyID);
321 const Type *Type::LabelTy      = new Type(Type::LabelTyID);
322 const Type *Type::MetadataTy   = new Type(Type::MetadataTyID);
323
324 namespace {
325   struct BuiltinIntegerType : public IntegerType {
326     explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
327   };
328 }
329 const IntegerType *Type::Int1Ty  = new BuiltinIntegerType(1);
330 const IntegerType *Type::Int8Ty  = new BuiltinIntegerType(8);
331 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
332 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
333 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
334
335 //===----------------------------------------------------------------------===//
336 //                          Derived Type Constructors
337 //===----------------------------------------------------------------------===//
338
339 /// isValidReturnType - Return true if the specified type is valid as a return
340 /// type.
341 bool FunctionType::isValidReturnType(const Type *RetTy) {
342   if (RetTy->isFirstClassType()) {
343     if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
344       return PTy->getElementType() != Type::MetadataTy;
345     return true;
346   }
347   if (RetTy == Type::VoidTy || RetTy == Type::MetadataTy ||
348       isa<OpaqueType>(RetTy))
349     return true;
350   
351   // If this is a multiple return case, verify that each return is a first class
352   // value and that there is at least one value.
353   const StructType *SRetTy = dyn_cast<StructType>(RetTy);
354   if (SRetTy == 0 || SRetTy->getNumElements() == 0)
355     return false;
356   
357   for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
358     if (!SRetTy->getElementType(i)->isFirstClassType())
359       return false;
360   return true;
361 }
362
363 /// isValidArgumentType - Return true if the specified type is valid as an
364 /// argument type.
365 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
366   if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
367       (isa<PointerType>(ArgTy) &&
368        cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
369     return false;
370
371   return true;
372 }
373
374 FunctionType::FunctionType(const Type *Result,
375                            const std::vector<const Type*> &Params,
376                            bool IsVarArgs)
377   : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
378   ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
379   NumContainedTys = Params.size() + 1; // + 1 for result type
380   assert(isValidReturnType(Result) && "invalid return type for function");
381
382
383   bool isAbstract = Result->isAbstract();
384   new (&ContainedTys[0]) PATypeHandle(Result, this);
385
386   for (unsigned i = 0; i != Params.size(); ++i) {
387     assert(isValidArgumentType(Params[i]) &&
388            "Not a valid type for function argument!");
389     new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
390     isAbstract |= Params[i]->isAbstract();
391   }
392
393   // Calculate whether or not this type is abstract
394   setAbstract(isAbstract);
395 }
396
397 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
398   : CompositeType(StructTyID) {
399   ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
400   NumContainedTys = Types.size();
401   setSubclassData(isPacked);
402   bool isAbstract = false;
403   for (unsigned i = 0; i < Types.size(); ++i) {
404     assert(Types[i] && "<null> type for structure field!");
405     assert(isValidElementType(Types[i]) &&
406            "Invalid type for structure element!");
407     new (&ContainedTys[i]) PATypeHandle(Types[i], this);
408     isAbstract |= Types[i]->isAbstract();
409   }
410
411   // Calculate whether or not this type is abstract
412   setAbstract(isAbstract);
413 }
414
415 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
416   : SequentialType(ArrayTyID, ElType) {
417   NumElements = NumEl;
418
419   // Calculate whether or not this type is abstract
420   setAbstract(ElType->isAbstract());
421 }
422
423 VectorType::VectorType(const Type *ElType, unsigned NumEl)
424   : SequentialType(VectorTyID, ElType) {
425   NumElements = NumEl;
426   setAbstract(ElType->isAbstract());
427   assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
428   assert(isValidElementType(ElType) &&
429          "Elements of a VectorType must be a primitive type");
430
431 }
432
433
434 PointerType::PointerType(const Type *E, unsigned AddrSpace)
435   : SequentialType(PointerTyID, E) {
436   AddressSpace = AddrSpace;
437   // Calculate whether or not this type is abstract
438   setAbstract(E->isAbstract());
439 }
440
441 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
442   setAbstract(true);
443 #ifdef DEBUG_MERGE_TYPES
444   DOUT << "Derived new type: " << *this << "\n";
445 #endif
446 }
447
448 void PATypeHolder::destroy() {
449   Ty = 0;
450 }
451
452 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
453 // another (more concrete) type, we must eliminate all references to other
454 // types, to avoid some circular reference problems.
455 void DerivedType::dropAllTypeUses() {
456   if (NumContainedTys != 0) {
457     // The type must stay abstract.  To do this, we insert a pointer to a type
458     // that will never get resolved, thus will always be abstract.
459     static Type *AlwaysOpaqueTy = 0;
460     static PATypeHolder* Holder = 0;
461     Type *tmp = AlwaysOpaqueTy;
462     if (llvm_is_multithreaded()) {
463       sys::MemoryFence();
464       if (!tmp) {
465         llvm_acquire_global_lock();
466         tmp = AlwaysOpaqueTy;
467         if (!tmp) {
468           tmp = OpaqueType::get();
469           PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
470           sys::MemoryFence();
471           AlwaysOpaqueTy = tmp;
472           Holder = tmp2;
473         }
474       
475         llvm_release_global_lock();
476       }
477     } else {
478       AlwaysOpaqueTy = OpaqueType::get();
479       Holder = new PATypeHolder(AlwaysOpaqueTy);
480     } 
481         
482     ContainedTys[0] = AlwaysOpaqueTy;
483
484     // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
485     // pick so long as it doesn't point back to this type.  We choose something
486     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
487     for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
488       ContainedTys[i] = Type::Int32Ty;
489   }
490 }
491
492
493 namespace {
494
495 /// TypePromotionGraph and graph traits - this is designed to allow us to do
496 /// efficient SCC processing of type graphs.  This is the exact same as
497 /// GraphTraits<Type*>, except that we pretend that concrete types have no
498 /// children to avoid processing them.
499 struct TypePromotionGraph {
500   Type *Ty;
501   TypePromotionGraph(Type *T) : Ty(T) {}
502 };
503
504 }
505
506 namespace llvm {
507   template <> struct GraphTraits<TypePromotionGraph> {
508     typedef Type NodeType;
509     typedef Type::subtype_iterator ChildIteratorType;
510
511     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
512     static inline ChildIteratorType child_begin(NodeType *N) {
513       if (N->isAbstract())
514         return N->subtype_begin();
515       else           // No need to process children of concrete types.
516         return N->subtype_end();
517     }
518     static inline ChildIteratorType child_end(NodeType *N) {
519       return N->subtype_end();
520     }
521   };
522 }
523
524
525 // PromoteAbstractToConcrete - This is a recursive function that walks a type
526 // graph calculating whether or not a type is abstract.
527 //
528 void Type::PromoteAbstractToConcrete() {
529   if (!isAbstract()) return;
530
531   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
532   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
533
534   for (; SI != SE; ++SI) {
535     std::vector<Type*> &SCC = *SI;
536
537     // Concrete types are leaves in the tree.  Since an SCC will either be all
538     // abstract or all concrete, we only need to check one type.
539     if (SCC[0]->isAbstract()) {
540       if (isa<OpaqueType>(SCC[0]))
541         return;     // Not going to be concrete, sorry.
542
543       // If all of the children of all of the types in this SCC are concrete,
544       // then this SCC is now concrete as well.  If not, neither this SCC, nor
545       // any parent SCCs will be concrete, so we might as well just exit.
546       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
547         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
548                E = SCC[i]->subtype_end(); CI != E; ++CI)
549           if ((*CI)->isAbstract())
550             // If the child type is in our SCC, it doesn't make the entire SCC
551             // abstract unless there is a non-SCC abstract type.
552             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
553               return;               // Not going to be concrete, sorry.
554
555       // Okay, we just discovered this whole SCC is now concrete, mark it as
556       // such!
557       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
558         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
559
560         SCC[i]->setAbstract(false);
561       }
562
563       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
564         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
565         // The type just became concrete, notify all users!
566         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
567       }
568     }
569   }
570 }
571
572
573 //===----------------------------------------------------------------------===//
574 //                      Type Structural Equality Testing
575 //===----------------------------------------------------------------------===//
576
577 // TypesEqual - Two types are considered structurally equal if they have the
578 // same "shape": Every level and element of the types have identical primitive
579 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
580 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
581 // that assumes that two graphs are the same until proven otherwise.
582 //
583 static bool TypesEqual(const Type *Ty, const Type *Ty2,
584                        std::map<const Type *, const Type *> &EqTypes) {
585   if (Ty == Ty2) return true;
586   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
587   if (isa<OpaqueType>(Ty))
588     return false;  // Two unequal opaque types are never equal
589
590   std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
591   if (It != EqTypes.end())
592     return It->second == Ty2;    // Looping back on a type, check for equality
593
594   // Otherwise, add the mapping to the table to make sure we don't get
595   // recursion on the types...
596   EqTypes.insert(It, std::make_pair(Ty, Ty2));
597
598   // Two really annoying special cases that breaks an otherwise nice simple
599   // algorithm is the fact that arraytypes have sizes that differentiates types,
600   // and that function types can be varargs or not.  Consider this now.
601   //
602   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
603     const IntegerType *ITy2 = cast<IntegerType>(Ty2);
604     return ITy->getBitWidth() == ITy2->getBitWidth();
605   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
606     const PointerType *PTy2 = cast<PointerType>(Ty2);
607     return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
608            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
609   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
610     const StructType *STy2 = cast<StructType>(Ty2);
611     if (STy->getNumElements() != STy2->getNumElements()) return false;
612     if (STy->isPacked() != STy2->isPacked()) return false;
613     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
614       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
615         return false;
616     return true;
617   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
618     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
619     return ATy->getNumElements() == ATy2->getNumElements() &&
620            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
621   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
622     const VectorType *PTy2 = cast<VectorType>(Ty2);
623     return PTy->getNumElements() == PTy2->getNumElements() &&
624            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
625   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
626     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
627     if (FTy->isVarArg() != FTy2->isVarArg() ||
628         FTy->getNumParams() != FTy2->getNumParams() ||
629         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
630       return false;
631     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
632       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
633         return false;
634     }
635     return true;
636   } else {
637     llvm_unreachable("Unknown derived type!");
638     return false;
639   }
640 }
641
642 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
643   std::map<const Type *, const Type *> EqTypes;
644   return TypesEqual(Ty, Ty2, EqTypes);
645 }
646
647 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
648 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
649 // ever reach a non-abstract type, we know that we don't need to search the
650 // subgraph.
651 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
652                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
653   if (TargetTy == CurTy) return true;
654   if (!CurTy->isAbstract()) return false;
655
656   if (!VisitedTypes.insert(CurTy))
657     return false;  // Already been here.
658
659   for (Type::subtype_iterator I = CurTy->subtype_begin(),
660        E = CurTy->subtype_end(); I != E; ++I)
661     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
662       return true;
663   return false;
664 }
665
666 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
667                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
668   if (TargetTy == CurTy) return true;
669
670   if (!VisitedTypes.insert(CurTy))
671     return false;  // Already been here.
672
673   for (Type::subtype_iterator I = CurTy->subtype_begin(),
674        E = CurTy->subtype_end(); I != E; ++I)
675     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
676       return true;
677   return false;
678 }
679
680 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
681 /// back to itself.
682 static bool TypeHasCycleThroughItself(const Type *Ty) {
683   SmallPtrSet<const Type*, 128> VisitedTypes;
684
685   if (Ty->isAbstract()) {  // Optimized case for abstract types.
686     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
687          I != E; ++I)
688       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
689         return true;
690   } else {
691     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
692          I != E; ++I)
693       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
694         return true;
695   }
696   return false;
697 }
698
699 /// getSubElementHash - Generate a hash value for all of the SubType's of this
700 /// type.  The hash value is guaranteed to be zero if any of the subtypes are 
701 /// an opaque type.  Otherwise we try to mix them in as well as possible, but do
702 /// not look at the subtype's subtype's.
703 static unsigned getSubElementHash(const Type *Ty) {
704   unsigned HashVal = 0;
705   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
706        I != E; ++I) {
707     HashVal *= 32;
708     const Type *SubTy = I->get();
709     HashVal += SubTy->getTypeID();
710     switch (SubTy->getTypeID()) {
711     default: break;
712     case Type::OpaqueTyID: return 0;    // Opaque -> hash = 0 no matter what.
713     case Type::IntegerTyID:
714       HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
715       break;
716     case Type::FunctionTyID:
717       HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 
718                  cast<FunctionType>(SubTy)->isVarArg();
719       break;
720     case Type::ArrayTyID:
721       HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
722       break;
723     case Type::VectorTyID:
724       HashVal ^= cast<VectorType>(SubTy)->getNumElements();
725       break;
726     case Type::StructTyID:
727       HashVal ^= cast<StructType>(SubTy)->getNumElements();
728       break;
729     case Type::PointerTyID:
730       HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
731       break;
732     }
733   }
734   return HashVal ? HashVal : 1;  // Do not return zero unless opaque subty.
735 }
736
737 //===----------------------------------------------------------------------===//
738 //                       Derived Type Factory Functions
739 //===----------------------------------------------------------------------===//
740
741 namespace llvm {
742 class TypeMapBase {
743 protected:
744   /// TypesByHash - Keep track of types by their structure hash value.  Note
745   /// that we only keep track of types that have cycles through themselves in
746   /// this map.
747   ///
748   std::multimap<unsigned, PATypeHolder> TypesByHash;
749
750 public:
751   ~TypeMapBase() {
752     // PATypeHolder won't destroy non-abstract types.
753     // We can't destroy them by simply iterating, because
754     // they may contain references to each-other.
755 #if 0
756     for (std::multimap<unsigned, PATypeHolder>::iterator I
757          = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
758       Type *Ty = const_cast<Type*>(I->second.Ty);
759       I->second.destroy();
760       // We can't invoke destroy or delete, because the type may
761       // contain references to already freed types.
762       // So we have to destruct the object the ugly way.
763       if (Ty) {
764         Ty->AbstractTypeUsers.clear();
765         static_cast<const Type*>(Ty)->Type::~Type();
766         operator delete(Ty);
767       }
768     }
769 #endif
770   }
771
772   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
773     std::multimap<unsigned, PATypeHolder>::iterator I =
774       TypesByHash.lower_bound(Hash);
775     for (; I != TypesByHash.end() && I->first == Hash; ++I) {
776       if (I->second == Ty) {
777         TypesByHash.erase(I);
778         return;
779       }
780     }
781     
782     // This must be do to an opaque type that was resolved.  Switch down to hash
783     // code of zero.
784     assert(Hash && "Didn't find type entry!");
785     RemoveFromTypesByHash(0, Ty);
786   }
787   
788   /// TypeBecameConcrete - When Ty gets a notification that TheType just became
789   /// concrete, drop uses and make Ty non-abstract if we should.
790   void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
791     // If the element just became concrete, remove 'ty' from the abstract
792     // type user list for the type.  Do this for as many times as Ty uses
793     // OldType.
794     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
795          I != E; ++I)
796       if (I->get() == TheType)
797         TheType->removeAbstractTypeUser(Ty);
798     
799     // If the type is currently thought to be abstract, rescan all of our
800     // subtypes to see if the type has just become concrete!  Note that this
801     // may send out notifications to AbstractTypeUsers that types become
802     // concrete.
803     if (Ty->isAbstract())
804       Ty->PromoteAbstractToConcrete();
805   }
806 };
807 }
808
809
810 // TypeMap - Make sure that only one instance of a particular type may be
811 // created on any given run of the compiler... note that this involves updating
812 // our map if an abstract type gets refined somehow.
813 //
814 namespace llvm {
815 template<class ValType, class TypeClass>
816 class TypeMap : public TypeMapBase {
817   std::map<ValType, PATypeHolder> Map;
818 public:
819   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
820   ~TypeMap() { print("ON EXIT"); }
821
822   inline TypeClass *get(const ValType &V) {
823     iterator I = Map.find(V);
824     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
825   }
826
827   inline void add(const ValType &V, TypeClass *Ty) {
828     Map.insert(std::make_pair(V, Ty));
829
830     // If this type has a cycle, remember it.
831     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
832     print("add");
833   }
834   
835   /// RefineAbstractType - This method is called after we have merged a type
836   /// with another one.  We must now either merge the type away with
837   /// some other type or reinstall it in the map with it's new configuration.
838   void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
839                         const Type *NewType) {
840 #ifdef DEBUG_MERGE_TYPES
841     DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
842          << "], " << (void*)NewType << " [" << *NewType << "])\n";
843 #endif
844     
845     // Otherwise, we are changing one subelement type into another.  Clearly the
846     // OldType must have been abstract, making us abstract.
847     assert(Ty->isAbstract() && "Refining a non-abstract type!");
848     assert(OldType != NewType);
849
850     // Make a temporary type holder for the type so that it doesn't disappear on
851     // us when we erase the entry from the map.
852     PATypeHolder TyHolder = Ty;
853
854     // The old record is now out-of-date, because one of the children has been
855     // updated.  Remove the obsolete entry from the map.
856     unsigned NumErased = Map.erase(ValType::get(Ty));
857     assert(NumErased && "Element not found!"); NumErased = NumErased;
858
859     // Remember the structural hash for the type before we start hacking on it,
860     // in case we need it later.
861     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
862
863     // Find the type element we are refining... and change it now!
864     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
865       if (Ty->ContainedTys[i] == OldType)
866         Ty->ContainedTys[i] = NewType;
867     unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
868     
869     // If there are no cycles going through this node, we can do a simple,
870     // efficient lookup in the map, instead of an inefficient nasty linear
871     // lookup.
872     if (!TypeHasCycleThroughItself(Ty)) {
873       typename std::map<ValType, PATypeHolder>::iterator I;
874       bool Inserted;
875
876       tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
877       if (!Inserted) {
878         // Refined to a different type altogether?
879         RemoveFromTypesByHash(OldTypeHash, Ty);
880
881         // We already have this type in the table.  Get rid of the newly refined
882         // type.
883         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
884         Ty->unlockedRefineAbstractTypeTo(NewTy);
885         return;
886       }
887     } else {
888       // Now we check to see if there is an existing entry in the table which is
889       // structurally identical to the newly refined type.  If so, this type
890       // gets refined to the pre-existing type.
891       //
892       std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
893       tie(I, E) = TypesByHash.equal_range(NewTypeHash);
894       Entry = E;
895       for (; I != E; ++I) {
896         if (I->second == Ty) {
897           // Remember the position of the old type if we see it in our scan.
898           Entry = I;
899         } else {
900           if (TypesEqual(Ty, I->second)) {
901             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
902
903             // Remove the old entry form TypesByHash.  If the hash values differ
904             // now, remove it from the old place.  Otherwise, continue scanning
905             // withing this hashcode to reduce work.
906             if (NewTypeHash != OldTypeHash) {
907               RemoveFromTypesByHash(OldTypeHash, Ty);
908             } else {
909               if (Entry == E) {
910                 // Find the location of Ty in the TypesByHash structure if we
911                 // haven't seen it already.
912                 while (I->second != Ty) {
913                   ++I;
914                   assert(I != E && "Structure doesn't contain type??");
915                 }
916                 Entry = I;
917               }
918               TypesByHash.erase(Entry);
919             }
920             Ty->unlockedRefineAbstractTypeTo(NewTy);
921             return;
922           }
923         }
924       }
925
926       // If there is no existing type of the same structure, we reinsert an
927       // updated record into the map.
928       Map.insert(std::make_pair(ValType::get(Ty), Ty));
929     }
930
931     // If the hash codes differ, update TypesByHash
932     if (NewTypeHash != OldTypeHash) {
933       RemoveFromTypesByHash(OldTypeHash, Ty);
934       TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
935     }
936     
937     // If the type is currently thought to be abstract, rescan all of our
938     // subtypes to see if the type has just become concrete!  Note that this
939     // may send out notifications to AbstractTypeUsers that types become
940     // concrete.
941     if (Ty->isAbstract())
942       Ty->PromoteAbstractToConcrete();
943   }
944
945   void print(const char *Arg) const {
946 #ifdef DEBUG_MERGE_TYPES
947     DOUT << "TypeMap<>::" << Arg << " table contents:\n";
948     unsigned i = 0;
949     for (typename std::map<ValType, PATypeHolder>::const_iterator I
950            = Map.begin(), E = Map.end(); I != E; ++I)
951       DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
952            << *I->second.get() << "\n";
953 #endif
954   }
955
956   void dump() const { print("dump output"); }
957 };
958 }
959
960
961 //===----------------------------------------------------------------------===//
962 // Function Type Factory and Value Class...
963 //
964
965 //===----------------------------------------------------------------------===//
966 // Integer Type Factory...
967 //
968 namespace llvm {
969 class IntegerValType {
970   uint32_t bits;
971 public:
972   IntegerValType(uint16_t numbits) : bits(numbits) {}
973
974   static IntegerValType get(const IntegerType *Ty) {
975     return IntegerValType(Ty->getBitWidth());
976   }
977
978   static unsigned hashTypeStructure(const IntegerType *Ty) {
979     return (unsigned)Ty->getBitWidth();
980   }
981
982   inline bool operator<(const IntegerValType &IVT) const {
983     return bits < IVT.bits;
984   }
985 };
986 }
987
988 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
989
990 const IntegerType *IntegerType::get(unsigned NumBits) {
991   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
992   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
993
994   // Check for the built-in integer types
995   switch (NumBits) {
996     case  1: return cast<IntegerType>(Type::Int1Ty);
997     case  8: return cast<IntegerType>(Type::Int8Ty);
998     case 16: return cast<IntegerType>(Type::Int16Ty);
999     case 32: return cast<IntegerType>(Type::Int32Ty);
1000     case 64: return cast<IntegerType>(Type::Int64Ty);
1001     default: 
1002       break;
1003   }
1004   
1005   IntegerValType IVT(NumBits);
1006   IntegerType *ITy = 0;
1007   
1008   // First, see if the type is already in the table, for which
1009   // a reader lock suffices.
1010   sys::SmartScopedLock<true> L(*TypeMapLock);
1011   ITy = IntegerTypes->get(IVT);
1012     
1013   if (!ITy) {
1014     // Value not found.  Derive a new type!
1015     ITy = new IntegerType(NumBits);
1016     IntegerTypes->add(IVT, ITy);
1017   }
1018 #ifdef DEBUG_MERGE_TYPES
1019   DOUT << "Derived new type: " << *ITy << "\n";
1020 #endif
1021   return ITy;
1022 }
1023
1024 bool IntegerType::isPowerOf2ByteWidth() const {
1025   unsigned BitWidth = getBitWidth();
1026   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1027 }
1028
1029 APInt IntegerType::getMask() const {
1030   return APInt::getAllOnesValue(getBitWidth());
1031 }
1032
1033 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1034 //
1035 namespace llvm {
1036 class FunctionValType {
1037   const Type *RetTy;
1038   std::vector<const Type*> ArgTypes;
1039   bool isVarArg;
1040 public:
1041   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1042                   bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1043
1044   static FunctionValType get(const FunctionType *FT);
1045
1046   static unsigned hashTypeStructure(const FunctionType *FT) {
1047     unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1048     return Result;
1049   }
1050
1051   inline bool operator<(const FunctionValType &MTV) const {
1052     if (RetTy < MTV.RetTy) return true;
1053     if (RetTy > MTV.RetTy) return false;
1054     if (isVarArg < MTV.isVarArg) return true;
1055     if (isVarArg > MTV.isVarArg) return false;
1056     if (ArgTypes < MTV.ArgTypes) return true;
1057     if (ArgTypes > MTV.ArgTypes) return false;
1058     return false;
1059   }
1060 };
1061 }
1062
1063 // Define the actual map itself now...
1064 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1065
1066 FunctionValType FunctionValType::get(const FunctionType *FT) {
1067   // Build up a FunctionValType
1068   std::vector<const Type *> ParamTypes;
1069   ParamTypes.reserve(FT->getNumParams());
1070   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1071     ParamTypes.push_back(FT->getParamType(i));
1072   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1073 }
1074
1075
1076 // FunctionType::get - The factory function for the FunctionType class...
1077 FunctionType *FunctionType::get(const Type *ReturnType,
1078                                 const std::vector<const Type*> &Params,
1079                                 bool isVarArg) {
1080   FunctionValType VT(ReturnType, Params, isVarArg);
1081   FunctionType *FT = 0;
1082   
1083   sys::SmartScopedLock<true> L(*TypeMapLock);
1084   FT = FunctionTypes->get(VT);
1085   
1086   if (!FT) {
1087     FT = (FunctionType*) operator new(sizeof(FunctionType) +
1088                                     sizeof(PATypeHandle)*(Params.size()+1));
1089     new (FT) FunctionType(ReturnType, Params, isVarArg);
1090     FunctionTypes->add(VT, FT);
1091   }
1092
1093 #ifdef DEBUG_MERGE_TYPES
1094   DOUT << "Derived new type: " << FT << "\n";
1095 #endif
1096   return FT;
1097 }
1098
1099 //===----------------------------------------------------------------------===//
1100 // Array Type Factory...
1101 //
1102 namespace llvm {
1103 class ArrayValType {
1104   const Type *ValTy;
1105   uint64_t Size;
1106 public:
1107   ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1108
1109   static ArrayValType get(const ArrayType *AT) {
1110     return ArrayValType(AT->getElementType(), AT->getNumElements());
1111   }
1112
1113   static unsigned hashTypeStructure(const ArrayType *AT) {
1114     return (unsigned)AT->getNumElements();
1115   }
1116
1117   inline bool operator<(const ArrayValType &MTV) const {
1118     if (Size < MTV.Size) return true;
1119     return Size == MTV.Size && ValTy < MTV.ValTy;
1120   }
1121 };
1122 }
1123
1124 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1125
1126 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1127   assert(ElementType && "Can't get array of <null> types!");
1128   assert(isValidElementType(ElementType) && "Invalid type for array element!");
1129
1130   ArrayValType AVT(ElementType, NumElements);
1131   ArrayType *AT = 0;
1132   
1133   sys::SmartScopedLock<true> L(*TypeMapLock);
1134   AT = ArrayTypes->get(AVT);
1135       
1136   if (!AT) {
1137     // Value not found.  Derive a new type!
1138     ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1139   }
1140 #ifdef DEBUG_MERGE_TYPES
1141   DOUT << "Derived new type: " << *AT << "\n";
1142 #endif
1143   return AT;
1144 }
1145
1146 bool ArrayType::isValidElementType(const Type *ElemTy) {
1147   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1148       ElemTy == Type::MetadataTy)
1149     return false;
1150
1151   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1152     if (PTy->getElementType() == Type::MetadataTy)
1153       return false;
1154
1155   return true;
1156 }
1157
1158
1159 //===----------------------------------------------------------------------===//
1160 // Vector Type Factory...
1161 //
1162 namespace llvm {
1163 class VectorValType {
1164   const Type *ValTy;
1165   unsigned Size;
1166 public:
1167   VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1168
1169   static VectorValType get(const VectorType *PT) {
1170     return VectorValType(PT->getElementType(), PT->getNumElements());
1171   }
1172
1173   static unsigned hashTypeStructure(const VectorType *PT) {
1174     return PT->getNumElements();
1175   }
1176
1177   inline bool operator<(const VectorValType &MTV) const {
1178     if (Size < MTV.Size) return true;
1179     return Size == MTV.Size && ValTy < MTV.ValTy;
1180   }
1181 };
1182 }
1183
1184 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1185
1186 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1187   assert(ElementType && "Can't get vector of <null> types!");
1188
1189   VectorValType PVT(ElementType, NumElements);
1190   VectorType *PT = 0;
1191   
1192   sys::SmartScopedLock<true> L(*TypeMapLock);
1193   PT = VectorTypes->get(PVT);
1194     
1195   if (!PT) {
1196     VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1197   }
1198 #ifdef DEBUG_MERGE_TYPES
1199   DOUT << "Derived new type: " << *PT << "\n";
1200 #endif
1201   return PT;
1202 }
1203
1204 bool VectorType::isValidElementType(const Type *ElemTy) {
1205   if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
1206       isa<OpaqueType>(ElemTy))
1207     return true;
1208
1209   return false;
1210 }
1211
1212 //===----------------------------------------------------------------------===//
1213 // Struct Type Factory...
1214 //
1215
1216 namespace llvm {
1217 // StructValType - Define a class to hold the key that goes into the TypeMap
1218 //
1219 class StructValType {
1220   std::vector<const Type*> ElTypes;
1221   bool packed;
1222 public:
1223   StructValType(const std::vector<const Type*> &args, bool isPacked)
1224     : ElTypes(args), packed(isPacked) {}
1225
1226   static StructValType get(const StructType *ST) {
1227     std::vector<const Type *> ElTypes;
1228     ElTypes.reserve(ST->getNumElements());
1229     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1230       ElTypes.push_back(ST->getElementType(i));
1231
1232     return StructValType(ElTypes, ST->isPacked());
1233   }
1234
1235   static unsigned hashTypeStructure(const StructType *ST) {
1236     return ST->getNumElements();
1237   }
1238
1239   inline bool operator<(const StructValType &STV) const {
1240     if (ElTypes < STV.ElTypes) return true;
1241     else if (ElTypes > STV.ElTypes) return false;
1242     else return (int)packed < (int)STV.packed;
1243   }
1244 };
1245 }
1246
1247 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1248
1249 StructType *StructType::get(const std::vector<const Type*> &ETypes, 
1250                             bool isPacked) {
1251   StructValType STV(ETypes, isPacked);
1252   StructType *ST = 0;
1253   
1254   sys::SmartScopedLock<true> L(*TypeMapLock);
1255   ST = StructTypes->get(STV);
1256     
1257   if (!ST) {
1258     // Value not found.  Derive a new type!
1259     ST = (StructType*) operator new(sizeof(StructType) +
1260                                     sizeof(PATypeHandle) * ETypes.size());
1261     new (ST) StructType(ETypes, isPacked);
1262     StructTypes->add(STV, ST);
1263   }
1264 #ifdef DEBUG_MERGE_TYPES
1265   DOUT << "Derived new type: " << *ST << "\n";
1266 #endif
1267   return ST;
1268 }
1269
1270 StructType *StructType::get(const Type *type, ...) {
1271   va_list ap;
1272   std::vector<const llvm::Type*> StructFields;
1273   va_start(ap, type);
1274   while (type) {
1275     StructFields.push_back(type);
1276     type = va_arg(ap, llvm::Type*);
1277   }
1278   return llvm::StructType::get(StructFields);
1279 }
1280
1281 bool StructType::isValidElementType(const Type *ElemTy) {
1282   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1283       ElemTy == Type::MetadataTy)
1284     return false;
1285
1286   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1287     if (PTy->getElementType() == Type::MetadataTy)
1288       return false;
1289
1290   return true;
1291 }
1292
1293
1294 //===----------------------------------------------------------------------===//
1295 // Pointer Type Factory...
1296 //
1297
1298 // PointerValType - Define a class to hold the key that goes into the TypeMap
1299 //
1300 namespace llvm {
1301 class PointerValType {
1302   const Type *ValTy;
1303   unsigned AddressSpace;
1304 public:
1305   PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1306
1307   static PointerValType get(const PointerType *PT) {
1308     return PointerValType(PT->getElementType(), PT->getAddressSpace());
1309   }
1310
1311   static unsigned hashTypeStructure(const PointerType *PT) {
1312     return getSubElementHash(PT);
1313   }
1314
1315   bool operator<(const PointerValType &MTV) const {
1316     if (AddressSpace < MTV.AddressSpace) return true;
1317     return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1318   }
1319 };
1320 }
1321
1322 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1323
1324 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1325   assert(ValueType && "Can't get a pointer to <null> type!");
1326   assert(ValueType != Type::VoidTy &&
1327          "Pointer to void is not valid, use i8* instead!");
1328   assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1329   PointerValType PVT(ValueType, AddressSpace);
1330
1331   PointerType *PT = 0;
1332   
1333   sys::SmartScopedLock<true> L(*TypeMapLock);
1334   PT = PointerTypes->get(PVT);
1335   
1336   if (!PT) {
1337     // Value not found.  Derive a new type!
1338     PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1339   }
1340 #ifdef DEBUG_MERGE_TYPES
1341   DOUT << "Derived new type: " << *PT << "\n";
1342 #endif
1343   return PT;
1344 }
1345
1346 PointerType *Type::getPointerTo(unsigned addrs) const {
1347   return PointerType::get(this, addrs);
1348 }
1349
1350 bool PointerType::isValidElementType(const Type *ElemTy) {
1351   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
1352     return false;
1353
1354   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1355     if (PTy->getElementType() == Type::MetadataTy)
1356       return false;
1357
1358   return true;
1359 }
1360
1361
1362 //===----------------------------------------------------------------------===//
1363 //                     Derived Type Refinement Functions
1364 //===----------------------------------------------------------------------===//
1365
1366 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1367 // it.  This function is called primarily by the PATypeHandle class.
1368 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1369   assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1370   AbstractTypeUsersLock->acquire();
1371   AbstractTypeUsers.push_back(U);
1372   AbstractTypeUsersLock->release();
1373 }
1374
1375
1376 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1377 // no longer has a handle to the type.  This function is called primarily by
1378 // the PATypeHandle class.  When there are no users of the abstract type, it
1379 // is annihilated, because there is no way to get a reference to it ever again.
1380 //
1381 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1382   AbstractTypeUsersLock->acquire();
1383   
1384   // Search from back to front because we will notify users from back to
1385   // front.  Also, it is likely that there will be a stack like behavior to
1386   // users that register and unregister users.
1387   //
1388   unsigned i;
1389   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1390     assert(i != 0 && "AbstractTypeUser not in user list!");
1391
1392   --i;  // Convert to be in range 0 <= i < size()
1393   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1394
1395   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1396
1397 #ifdef DEBUG_MERGE_TYPES
1398   DOUT << "  remAbstractTypeUser[" << (void*)this << ", "
1399        << *this << "][" << i << "] User = " << U << "\n";
1400 #endif
1401
1402   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1403 #ifdef DEBUG_MERGE_TYPES
1404     DOUT << "DELETEing unused abstract type: <" << *this
1405          << ">[" << (void*)this << "]" << "\n";
1406 #endif
1407   
1408   this->destroy();
1409   }
1410   
1411   AbstractTypeUsersLock->release();
1412 }
1413
1414 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1415 // that the 'this' abstract type is actually equivalent to the NewType
1416 // specified. This causes all users of 'this' to switch to reference the more 
1417 // concrete type NewType and for 'this' to be deleted.  Only used for internal
1418 // callers.
1419 //
1420 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1421   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1422   assert(this != NewType && "Can't refine to myself!");
1423   assert(ForwardType == 0 && "This type has already been refined!");
1424
1425   // The descriptions may be out of date.  Conservatively clear them all!
1426   if (AbstractTypeDescriptions.isConstructed())
1427     AbstractTypeDescriptions->clear();
1428
1429 #ifdef DEBUG_MERGE_TYPES
1430   DOUT << "REFINING abstract type [" << (void*)this << " "
1431        << *this << "] to [" << (void*)NewType << " "
1432        << *NewType << "]!\n";
1433 #endif
1434
1435   // Make sure to put the type to be refined to into a holder so that if IT gets
1436   // refined, that we will not continue using a dead reference...
1437   //
1438   PATypeHolder NewTy(NewType);
1439   // Any PATypeHolders referring to this type will now automatically forward o
1440   // the type we are resolved to.
1441   ForwardType = NewType;
1442   if (NewType->isAbstract())
1443     cast<DerivedType>(NewType)->addRef();
1444
1445   // Add a self use of the current type so that we don't delete ourself until
1446   // after the function exits.
1447   //
1448   PATypeHolder CurrentTy(this);
1449
1450   // To make the situation simpler, we ask the subclass to remove this type from
1451   // the type map, and to replace any type uses with uses of non-abstract types.
1452   // This dramatically limits the amount of recursive type trouble we can find
1453   // ourselves in.
1454   dropAllTypeUses();
1455
1456   // Iterate over all of the uses of this type, invoking callback.  Each user
1457   // should remove itself from our use list automatically.  We have to check to
1458   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1459   // will not cause users to drop off of the use list.  If we resolve to ourself
1460   // we succeed!
1461   //
1462   AbstractTypeUsersLock->acquire();
1463   while (!AbstractTypeUsers.empty() && NewTy != this) {
1464     AbstractTypeUser *User = AbstractTypeUsers.back();
1465
1466     unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1467 #ifdef DEBUG_MERGE_TYPES
1468     DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1469          << "] of abstract type [" << (void*)this << " "
1470          << *this << "] to [" << (void*)NewTy.get() << " "
1471          << *NewTy << "]!\n";
1472 #endif
1473     User->refineAbstractType(this, NewTy);
1474
1475     assert(AbstractTypeUsers.size() != OldSize &&
1476            "AbsTyUser did not remove self from user list!");
1477   }
1478   AbstractTypeUsersLock->release();
1479
1480   // If we were successful removing all users from the type, 'this' will be
1481   // deleted when the last PATypeHolder is destroyed or updated from this type.
1482   // This may occur on exit of this function, as the CurrentTy object is
1483   // destroyed.
1484 }
1485
1486 // refineAbstractTypeTo - This function is used by external callers to notify
1487 // us that this abstract type is equivalent to another type.
1488 //
1489 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1490   // All recursive calls will go through unlockedRefineAbstractTypeTo,
1491   // to avoid deadlock problems.
1492   sys::SmartScopedLock<true> L(*TypeMapLock);
1493   unlockedRefineAbstractTypeTo(NewType);
1494 }
1495
1496 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1497 // the current type has transitioned from being abstract to being concrete.
1498 //
1499 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1500 #ifdef DEBUG_MERGE_TYPES
1501   DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1502 #endif
1503
1504   AbstractTypeUsersLock->acquire();
1505   unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1506   while (!AbstractTypeUsers.empty()) {
1507     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1508     ATU->typeBecameConcrete(this);
1509
1510     assert(AbstractTypeUsers.size() < OldSize-- &&
1511            "AbstractTypeUser did not remove itself from the use list!");
1512   }
1513   AbstractTypeUsersLock->release();
1514 }
1515
1516 // refineAbstractType - Called when a contained type is found to be more
1517 // concrete - this could potentially change us from an abstract type to a
1518 // concrete type.
1519 //
1520 void FunctionType::refineAbstractType(const DerivedType *OldType,
1521                                       const Type *NewType) {
1522   FunctionTypes->RefineAbstractType(this, OldType, NewType);
1523 }
1524
1525 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1526   FunctionTypes->TypeBecameConcrete(this, AbsTy);
1527 }
1528
1529
1530 // refineAbstractType - Called when a contained type is found to be more
1531 // concrete - this could potentially change us from an abstract type to a
1532 // concrete type.
1533 //
1534 void ArrayType::refineAbstractType(const DerivedType *OldType,
1535                                    const Type *NewType) {
1536   ArrayTypes->RefineAbstractType(this, OldType, NewType);
1537 }
1538
1539 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1540   ArrayTypes->TypeBecameConcrete(this, AbsTy);
1541 }
1542
1543 // refineAbstractType - Called when a contained type is found to be more
1544 // concrete - this could potentially change us from an abstract type to a
1545 // concrete type.
1546 //
1547 void VectorType::refineAbstractType(const DerivedType *OldType,
1548                                    const Type *NewType) {
1549   VectorTypes->RefineAbstractType(this, OldType, NewType);
1550 }
1551
1552 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1553   VectorTypes->TypeBecameConcrete(this, AbsTy);
1554 }
1555
1556 // refineAbstractType - Called when a contained type is found to be more
1557 // concrete - this could potentially change us from an abstract type to a
1558 // concrete type.
1559 //
1560 void StructType::refineAbstractType(const DerivedType *OldType,
1561                                     const Type *NewType) {
1562   StructTypes->RefineAbstractType(this, OldType, NewType);
1563 }
1564
1565 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1566   StructTypes->TypeBecameConcrete(this, AbsTy);
1567 }
1568
1569 // refineAbstractType - Called when a contained type is found to be more
1570 // concrete - this could potentially change us from an abstract type to a
1571 // concrete type.
1572 //
1573 void PointerType::refineAbstractType(const DerivedType *OldType,
1574                                      const Type *NewType) {
1575   PointerTypes->RefineAbstractType(this, OldType, NewType);
1576 }
1577
1578 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1579   PointerTypes->TypeBecameConcrete(this, AbsTy);
1580 }
1581
1582 bool SequentialType::indexValid(const Value *V) const {
1583   if (isa<IntegerType>(V->getType())) 
1584     return true;
1585   return false;
1586 }
1587
1588 namespace llvm {
1589 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1590   if (T == 0)
1591     OS << "<null> value!\n";
1592   else
1593     T->print(OS);
1594   return OS;
1595 }
1596
1597 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1598   T.print(OS);
1599   return OS;
1600 }
1601
1602 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
1603   T.print(OS);
1604   return OS;
1605 }
1606 }