Uniformize the names of type predicates: rather than having isFloatTy and
[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 "LLVMContextImpl.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Threading.h"
31 #include <algorithm>
32 #include <cstdarg>
33 using namespace llvm;
34
35 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
36 // created and later destroyed, all in an effort to make sure that there is only
37 // a single canonical version of a type.
38 //
39 // #define DEBUG_MERGE_TYPES 1
40
41 AbstractTypeUser::~AbstractTypeUser() {}
42
43 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
44   V->VTy = NewTy;
45 }
46
47 //===----------------------------------------------------------------------===//
48 //                         Type Class Implementation
49 //===----------------------------------------------------------------------===//
50
51 /// Because of the way Type subclasses are allocated, this function is necessary
52 /// to use the correct kind of "delete" operator to deallocate the Type object.
53 /// Some type objects (FunctionTy, StructTy, UnionTy) allocate additional space
54 /// after the space for their derived type to hold the contained types array of
55 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
56 /// allocated with the type object, decreasing allocations and eliminating the
57 /// need for a std::vector to be used in the Type class itself. 
58 /// @brief Type destruction function
59 void Type::destroy() const {
60
61   // Structures and Functions allocate their contained types past the end of
62   // the type object itself. These need to be destroyed differently than the
63   // other types.
64   if (isa<FunctionType>(this) || isa<StructType>(this) ||
65       isa<UnionType>(this)) {
66     // First, make sure we destruct any PATypeHandles allocated by these
67     // subclasses.  They must be manually destructed. 
68     for (unsigned i = 0; i < NumContainedTys; ++i)
69       ContainedTys[i].PATypeHandle::~PATypeHandle();
70
71     // Now call the destructor for the subclass directly because we're going
72     // to delete this as an array of char.
73     if (isa<FunctionType>(this))
74       static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
75     else if (isa<StructType>(this))
76       static_cast<const StructType*>(this)->StructType::~StructType();
77     else
78       static_cast<const UnionType*>(this)->UnionType::~UnionType();
79
80     // Finally, remove the memory as an array deallocation of the chars it was
81     // constructed from.
82     operator delete(const_cast<Type *>(this));
83
84     return;
85   } else if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
86     LLVMContextImpl *pImpl = this->getContext().pImpl;
87     pImpl->OpaqueTypes.erase(opaque_this);
88   }
89
90   // For all the other type subclasses, there is either no contained types or 
91   // just one (all Sequentials). For Sequentials, the PATypeHandle is not
92   // allocated past the type object, its included directly in the SequentialType
93   // class. This means we can safely just do "normal" delete of this object and
94   // all the destructors that need to run will be run.
95   delete this; 
96 }
97
98 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
99   switch (IDNumber) {
100   case VoidTyID      : return getVoidTy(C);
101   case FloatTyID     : return getFloatTy(C);
102   case DoubleTyID    : return getDoubleTy(C);
103   case X86_FP80TyID  : return getX86_FP80Ty(C);
104   case FP128TyID     : return getFP128Ty(C);
105   case PPC_FP128TyID : return getPPC_FP128Ty(C);
106   case LabelTyID     : return getLabelTy(C);
107   case MetadataTyID  : return getMetadataTy(C);
108   default:
109     return 0;
110   }
111 }
112
113 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
114   if (ID == IntegerTyID && getSubclassData() < 32)
115     return Type::getInt32Ty(C);
116   else if (ID == FloatTyID)
117     return Type::getDoubleTy(C);
118   else
119     return this;
120 }
121
122 /// getScalarType - If this is a vector type, return the element type,
123 /// otherwise return this.
124 const Type *Type::getScalarType() const {
125   if (const VectorType *VTy = dyn_cast<VectorType>(this))
126     return VTy->getElementType();
127   return this;
128 }
129
130 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
131 bool Type::isIntegerTy(unsigned Bitwidth) const {
132   return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
133 }
134
135 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
136 /// integer types.
137 ///
138 bool Type::isIntOrIntVectorTy() const {
139   if (isIntegerTy())
140     return true;
141   if (ID != Type::VectorTyID) return false;
142   
143   return cast<VectorType>(this)->getElementType()->isIntegerTy();
144 }
145
146 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
147 ///
148 bool Type::isFPOrFPVectorTy() 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()->isFloatingPointTy();
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(isFloatingPointTy() && "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) && !isa<UnionType>(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   LLVMContextImpl *pImpl = getContext().pImpl;
277   TypePrinting &Map =
278     isAbstract() ?
279       pImpl->AbstractTypeDescriptions :
280       pImpl->ConcreteTypeDescriptions;
281   
282   std::string DescStr;
283   raw_string_ostream DescOS(DescStr);
284   Map.print(this, DescOS);
285   return DescOS.str();
286 }
287
288
289 bool StructType::indexValid(const Value *V) const {
290   // Structure indexes require 32-bit integer constants.
291   if (V->getType()->isIntegerTy(32))
292     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
293       return indexValid(CU->getZExtValue());
294   return false;
295 }
296
297 bool StructType::indexValid(unsigned V) const {
298   return V < NumContainedTys;
299 }
300
301 // getTypeAtIndex - Given an index value into the type, return the type of the
302 // element.  For a structure type, this must be a constant value...
303 //
304 const Type *StructType::getTypeAtIndex(const Value *V) const {
305   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
306   return getTypeAtIndex(Idx);
307 }
308
309 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
310   assert(indexValid(Idx) && "Invalid structure index!");
311   return ContainedTys[Idx];
312 }
313
314
315 bool UnionType::indexValid(const Value *V) const {
316   // Union indexes require 32-bit integer constants.
317   if (V->getType()->isIntegerTy(32))
318     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
319       return indexValid(CU->getZExtValue());
320   return false;
321 }
322
323 bool UnionType::indexValid(unsigned V) const {
324   return V < NumContainedTys;
325 }
326
327 // getTypeAtIndex - Given an index value into the type, return the type of the
328 // element.  For a structure type, this must be a constant value...
329 //
330 const Type *UnionType::getTypeAtIndex(const Value *V) const {
331   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
332   return getTypeAtIndex(Idx);
333 }
334
335 const Type *UnionType::getTypeAtIndex(unsigned Idx) const {
336   assert(indexValid(Idx) && "Invalid structure index!");
337   return ContainedTys[Idx];
338 }
339
340 //===----------------------------------------------------------------------===//
341 //                          Primitive 'Type' data
342 //===----------------------------------------------------------------------===//
343
344 const Type *Type::getVoidTy(LLVMContext &C) {
345   return &C.pImpl->VoidTy;
346 }
347
348 const Type *Type::getLabelTy(LLVMContext &C) {
349   return &C.pImpl->LabelTy;
350 }
351
352 const Type *Type::getFloatTy(LLVMContext &C) {
353   return &C.pImpl->FloatTy;
354 }
355
356 const Type *Type::getDoubleTy(LLVMContext &C) {
357   return &C.pImpl->DoubleTy;
358 }
359
360 const Type *Type::getMetadataTy(LLVMContext &C) {
361   return &C.pImpl->MetadataTy;
362 }
363
364 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
365   return &C.pImpl->X86_FP80Ty;
366 }
367
368 const Type *Type::getFP128Ty(LLVMContext &C) {
369   return &C.pImpl->FP128Ty;
370 }
371
372 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
373   return &C.pImpl->PPC_FP128Ty;
374 }
375
376 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
377   return &C.pImpl->Int1Ty;
378 }
379
380 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
381   return &C.pImpl->Int8Ty;
382 }
383
384 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
385   return &C.pImpl->Int16Ty;
386 }
387
388 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
389   return &C.pImpl->Int32Ty;
390 }
391
392 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
393   return &C.pImpl->Int64Ty;
394 }
395
396 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
397   return getFloatTy(C)->getPointerTo(AS);
398 }
399
400 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
401   return getDoubleTy(C)->getPointerTo(AS);
402 }
403
404 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
405   return getX86_FP80Ty(C)->getPointerTo(AS);
406 }
407
408 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
409   return getFP128Ty(C)->getPointerTo(AS);
410 }
411
412 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
413   return getPPC_FP128Ty(C)->getPointerTo(AS);
414 }
415
416 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
417   return getInt1Ty(C)->getPointerTo(AS);
418 }
419
420 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
421   return getInt8Ty(C)->getPointerTo(AS);
422 }
423
424 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
425   return getInt16Ty(C)->getPointerTo(AS);
426 }
427
428 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
429   return getInt32Ty(C)->getPointerTo(AS);
430 }
431
432 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
433   return getInt64Ty(C)->getPointerTo(AS);
434 }
435
436 //===----------------------------------------------------------------------===//
437 //                          Derived Type Constructors
438 //===----------------------------------------------------------------------===//
439
440 /// isValidReturnType - Return true if the specified type is valid as a return
441 /// type.
442 bool FunctionType::isValidReturnType(const Type *RetTy) {
443   return RetTy->getTypeID() != LabelTyID &&
444          RetTy->getTypeID() != MetadataTyID;
445 }
446
447 /// isValidArgumentType - Return true if the specified type is valid as an
448 /// argument type.
449 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
450   return ArgTy->isFirstClassType() || isa<OpaqueType>(ArgTy);
451 }
452
453 FunctionType::FunctionType(const Type *Result,
454                            const std::vector<const Type*> &Params,
455                            bool IsVarArgs)
456   : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
457   ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
458   NumContainedTys = Params.size() + 1; // + 1 for result type
459   assert(isValidReturnType(Result) && "invalid return type for function");
460
461
462   bool isAbstract = Result->isAbstract();
463   new (&ContainedTys[0]) PATypeHandle(Result, this);
464
465   for (unsigned i = 0; i != Params.size(); ++i) {
466     assert(isValidArgumentType(Params[i]) &&
467            "Not a valid type for function argument!");
468     new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
469     isAbstract |= Params[i]->isAbstract();
470   }
471
472   // Calculate whether or not this type is abstract
473   setAbstract(isAbstract);
474 }
475
476 StructType::StructType(LLVMContext &C, 
477                        const std::vector<const Type*> &Types, bool isPacked)
478   : CompositeType(C, StructTyID) {
479   ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
480   NumContainedTys = Types.size();
481   setSubclassData(isPacked);
482   bool isAbstract = false;
483   for (unsigned i = 0; i < Types.size(); ++i) {
484     assert(Types[i] && "<null> type for structure field!");
485     assert(isValidElementType(Types[i]) &&
486            "Invalid type for structure element!");
487     new (&ContainedTys[i]) PATypeHandle(Types[i], this);
488     isAbstract |= Types[i]->isAbstract();
489   }
490
491   // Calculate whether or not this type is abstract
492   setAbstract(isAbstract);
493 }
494
495 UnionType::UnionType(LLVMContext &C,const Type* const* Types, unsigned NumTypes)
496   : CompositeType(C, UnionTyID) {
497   ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
498   NumContainedTys = NumTypes;
499   bool isAbstract = false;
500   for (unsigned i = 0; i < NumTypes; ++i) {
501     assert(Types[i] && "<null> type for union field!");
502     assert(isValidElementType(Types[i]) &&
503            "Invalid type for union element!");
504     new (&ContainedTys[i]) PATypeHandle(Types[i], this);
505     isAbstract |= Types[i]->isAbstract();
506   }
507
508   // Calculate whether or not this type is abstract
509   setAbstract(isAbstract);
510 }
511
512 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
513   : SequentialType(ArrayTyID, ElType) {
514   NumElements = NumEl;
515
516   // Calculate whether or not this type is abstract
517   setAbstract(ElType->isAbstract());
518 }
519
520 VectorType::VectorType(const Type *ElType, unsigned NumEl)
521   : SequentialType(VectorTyID, ElType) {
522   NumElements = NumEl;
523   setAbstract(ElType->isAbstract());
524   assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
525   assert(isValidElementType(ElType) &&
526          "Elements of a VectorType must be a primitive type");
527
528 }
529
530
531 PointerType::PointerType(const Type *E, unsigned AddrSpace)
532   : SequentialType(PointerTyID, E) {
533   AddressSpace = AddrSpace;
534   // Calculate whether or not this type is abstract
535   setAbstract(E->isAbstract());
536 }
537
538 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
539   setAbstract(true);
540 #ifdef DEBUG_MERGE_TYPES
541   DEBUG(dbgs() << "Derived new type: " << *this << "\n");
542 #endif
543 }
544
545 void PATypeHolder::destroy() {
546   Ty = 0;
547 }
548
549 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
550 // another (more concrete) type, we must eliminate all references to other
551 // types, to avoid some circular reference problems.
552 void DerivedType::dropAllTypeUses() {
553   if (NumContainedTys != 0) {
554     // The type must stay abstract.  To do this, we insert a pointer to a type
555     // that will never get resolved, thus will always be abstract.
556     ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
557
558     // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
559     // pick so long as it doesn't point back to this type.  We choose something
560     // concrete to avoid overhead for adding to AbstractTypeUser lists and
561     // stuff.
562     const Type *ConcreteTy = Type::getInt32Ty(getContext());
563     for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
564       ContainedTys[i] = ConcreteTy;
565   }
566 }
567
568
569 namespace {
570
571 /// TypePromotionGraph and graph traits - this is designed to allow us to do
572 /// efficient SCC processing of type graphs.  This is the exact same as
573 /// GraphTraits<Type*>, except that we pretend that concrete types have no
574 /// children to avoid processing them.
575 struct TypePromotionGraph {
576   Type *Ty;
577   TypePromotionGraph(Type *T) : Ty(T) {}
578 };
579
580 }
581
582 namespace llvm {
583   template <> struct GraphTraits<TypePromotionGraph> {
584     typedef Type NodeType;
585     typedef Type::subtype_iterator ChildIteratorType;
586
587     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
588     static inline ChildIteratorType child_begin(NodeType *N) {
589       if (N->isAbstract())
590         return N->subtype_begin();
591       else           // No need to process children of concrete types.
592         return N->subtype_end();
593     }
594     static inline ChildIteratorType child_end(NodeType *N) {
595       return N->subtype_end();
596     }
597   };
598 }
599
600
601 // PromoteAbstractToConcrete - This is a recursive function that walks a type
602 // graph calculating whether or not a type is abstract.
603 //
604 void Type::PromoteAbstractToConcrete() {
605   if (!isAbstract()) return;
606
607   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
608   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
609
610   for (; SI != SE; ++SI) {
611     std::vector<Type*> &SCC = *SI;
612
613     // Concrete types are leaves in the tree.  Since an SCC will either be all
614     // abstract or all concrete, we only need to check one type.
615     if (SCC[0]->isAbstract()) {
616       if (isa<OpaqueType>(SCC[0]))
617         return;     // Not going to be concrete, sorry.
618
619       // If all of the children of all of the types in this SCC are concrete,
620       // then this SCC is now concrete as well.  If not, neither this SCC, nor
621       // any parent SCCs will be concrete, so we might as well just exit.
622       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
623         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
624                E = SCC[i]->subtype_end(); CI != E; ++CI)
625           if ((*CI)->isAbstract())
626             // If the child type is in our SCC, it doesn't make the entire SCC
627             // abstract unless there is a non-SCC abstract type.
628             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
629               return;               // Not going to be concrete, sorry.
630
631       // Okay, we just discovered this whole SCC is now concrete, mark it as
632       // such!
633       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
634         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
635
636         SCC[i]->setAbstract(false);
637       }
638
639       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
640         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
641         // The type just became concrete, notify all users!
642         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
643       }
644     }
645   }
646 }
647
648
649 //===----------------------------------------------------------------------===//
650 //                      Type Structural Equality Testing
651 //===----------------------------------------------------------------------===//
652
653 // TypesEqual - Two types are considered structurally equal if they have the
654 // same "shape": Every level and element of the types have identical primitive
655 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
656 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
657 // that assumes that two graphs are the same until proven otherwise.
658 //
659 static bool TypesEqual(const Type *Ty, const Type *Ty2,
660                        std::map<const Type *, const Type *> &EqTypes) {
661   if (Ty == Ty2) return true;
662   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
663   if (isa<OpaqueType>(Ty))
664     return false;  // Two unequal opaque types are never equal
665
666   std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
667   if (It != EqTypes.end())
668     return It->second == Ty2;    // Looping back on a type, check for equality
669
670   // Otherwise, add the mapping to the table to make sure we don't get
671   // recursion on the types...
672   EqTypes.insert(It, std::make_pair(Ty, Ty2));
673
674   // Two really annoying special cases that breaks an otherwise nice simple
675   // algorithm is the fact that arraytypes have sizes that differentiates types,
676   // and that function types can be varargs or not.  Consider this now.
677   //
678   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
679     const IntegerType *ITy2 = cast<IntegerType>(Ty2);
680     return ITy->getBitWidth() == ITy2->getBitWidth();
681   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
682     const PointerType *PTy2 = cast<PointerType>(Ty2);
683     return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
684            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
685   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
686     const StructType *STy2 = cast<StructType>(Ty2);
687     if (STy->getNumElements() != STy2->getNumElements()) return false;
688     if (STy->isPacked() != STy2->isPacked()) return false;
689     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
690       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
691         return false;
692     return true;
693   } else if (const UnionType *UTy = dyn_cast<UnionType>(Ty)) {
694     const UnionType *UTy2 = cast<UnionType>(Ty2);
695     if (UTy->getNumElements() != UTy2->getNumElements()) return false;
696     for (unsigned i = 0, e = UTy2->getNumElements(); i != e; ++i)
697       if (!TypesEqual(UTy->getElementType(i), UTy2->getElementType(i), EqTypes))
698         return false;
699     return true;
700   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
701     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
702     return ATy->getNumElements() == ATy2->getNumElements() &&
703            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
704   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
705     const VectorType *PTy2 = cast<VectorType>(Ty2);
706     return PTy->getNumElements() == PTy2->getNumElements() &&
707            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
708   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
709     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
710     if (FTy->isVarArg() != FTy2->isVarArg() ||
711         FTy->getNumParams() != FTy2->getNumParams() ||
712         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
713       return false;
714     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
715       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
716         return false;
717     }
718     return true;
719   } else {
720     llvm_unreachable("Unknown derived type!");
721     return false;
722   }
723 }
724
725 namespace llvm { // in namespace llvm so findable by ADL
726 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
727   std::map<const Type *, const Type *> EqTypes;
728   return ::TypesEqual(Ty, Ty2, EqTypes);
729 }
730 }
731
732 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
733 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
734 // ever reach a non-abstract type, we know that we don't need to search the
735 // subgraph.
736 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
737                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
738   if (TargetTy == CurTy) return true;
739   if (!CurTy->isAbstract()) return false;
740
741   if (!VisitedTypes.insert(CurTy))
742     return false;  // Already been here.
743
744   for (Type::subtype_iterator I = CurTy->subtype_begin(),
745        E = CurTy->subtype_end(); I != E; ++I)
746     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
747       return true;
748   return false;
749 }
750
751 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
752                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
753   if (TargetTy == CurTy) return true;
754
755   if (!VisitedTypes.insert(CurTy))
756     return false;  // Already been here.
757
758   for (Type::subtype_iterator I = CurTy->subtype_begin(),
759        E = CurTy->subtype_end(); I != E; ++I)
760     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
761       return true;
762   return false;
763 }
764
765 /// TypeHasCycleThroughItself - Return true if the specified type has
766 /// a cycle back to itself.
767
768 namespace llvm { // in namespace llvm so it's findable by ADL
769 static bool TypeHasCycleThroughItself(const Type *Ty) {
770   SmallPtrSet<const Type*, 128> VisitedTypes;
771
772   if (Ty->isAbstract()) {  // Optimized case for abstract types.
773     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
774          I != E; ++I)
775       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
776         return true;
777   } else {
778     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
779          I != E; ++I)
780       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
781         return true;
782   }
783   return false;
784 }
785 }
786
787 //===----------------------------------------------------------------------===//
788 // Function Type Factory and Value Class...
789 //
790 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
791   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
792   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
793
794   // Check for the built-in integer types
795   switch (NumBits) {
796     case  1: return cast<IntegerType>(Type::getInt1Ty(C));
797     case  8: return cast<IntegerType>(Type::getInt8Ty(C));
798     case 16: return cast<IntegerType>(Type::getInt16Ty(C));
799     case 32: return cast<IntegerType>(Type::getInt32Ty(C));
800     case 64: return cast<IntegerType>(Type::getInt64Ty(C));
801     default: 
802       break;
803   }
804
805   LLVMContextImpl *pImpl = C.pImpl;
806   
807   IntegerValType IVT(NumBits);
808   IntegerType *ITy = 0;
809   
810   // First, see if the type is already in the table, for which
811   // a reader lock suffices.
812   ITy = pImpl->IntegerTypes.get(IVT);
813     
814   if (!ITy) {
815     // Value not found.  Derive a new type!
816     ITy = new IntegerType(C, NumBits);
817     pImpl->IntegerTypes.add(IVT, ITy);
818   }
819 #ifdef DEBUG_MERGE_TYPES
820   DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
821 #endif
822   return ITy;
823 }
824
825 bool IntegerType::isPowerOf2ByteWidth() const {
826   unsigned BitWidth = getBitWidth();
827   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
828 }
829
830 APInt IntegerType::getMask() const {
831   return APInt::getAllOnesValue(getBitWidth());
832 }
833
834 FunctionValType FunctionValType::get(const FunctionType *FT) {
835   // Build up a FunctionValType
836   std::vector<const Type *> ParamTypes;
837   ParamTypes.reserve(FT->getNumParams());
838   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
839     ParamTypes.push_back(FT->getParamType(i));
840   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
841 }
842
843
844 // FunctionType::get - The factory function for the FunctionType class...
845 FunctionType *FunctionType::get(const Type *ReturnType,
846                                 const std::vector<const Type*> &Params,
847                                 bool isVarArg) {
848   FunctionValType VT(ReturnType, Params, isVarArg);
849   FunctionType *FT = 0;
850   
851   LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
852   
853   FT = pImpl->FunctionTypes.get(VT);
854   
855   if (!FT) {
856     FT = (FunctionType*) operator new(sizeof(FunctionType) +
857                                     sizeof(PATypeHandle)*(Params.size()+1));
858     new (FT) FunctionType(ReturnType, Params, isVarArg);
859     pImpl->FunctionTypes.add(VT, FT);
860   }
861
862 #ifdef DEBUG_MERGE_TYPES
863   DEBUG(dbgs() << "Derived new type: " << FT << "\n");
864 #endif
865   return FT;
866 }
867
868 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
869   assert(ElementType && "Can't get array of <null> types!");
870   assert(isValidElementType(ElementType) && "Invalid type for array element!");
871
872   ArrayValType AVT(ElementType, NumElements);
873   ArrayType *AT = 0;
874
875   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
876   
877   AT = pImpl->ArrayTypes.get(AVT);
878       
879   if (!AT) {
880     // Value not found.  Derive a new type!
881     pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
882   }
883 #ifdef DEBUG_MERGE_TYPES
884   DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
885 #endif
886   return AT;
887 }
888
889 bool ArrayType::isValidElementType(const Type *ElemTy) {
890   return ElemTy->getTypeID() != VoidTyID && ElemTy->getTypeID() != LabelTyID &&
891          ElemTy->getTypeID() != MetadataTyID && !isa<FunctionType>(ElemTy);
892 }
893
894 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
895   assert(ElementType && "Can't get vector of <null> types!");
896
897   VectorValType PVT(ElementType, NumElements);
898   VectorType *PT = 0;
899   
900   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
901   
902   PT = pImpl->VectorTypes.get(PVT);
903     
904   if (!PT) {
905     pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
906   }
907 #ifdef DEBUG_MERGE_TYPES
908   DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
909 #endif
910   return PT;
911 }
912
913 bool VectorType::isValidElementType(const Type *ElemTy) {
914   return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
915          isa<OpaqueType>(ElemTy);
916 }
917
918 //===----------------------------------------------------------------------===//
919 // Struct Type Factory...
920 //
921
922 StructType *StructType::get(LLVMContext &Context,
923                             const std::vector<const Type*> &ETypes, 
924                             bool isPacked) {
925   StructValType STV(ETypes, isPacked);
926   StructType *ST = 0;
927   
928   LLVMContextImpl *pImpl = Context.pImpl;
929   
930   ST = pImpl->StructTypes.get(STV);
931     
932   if (!ST) {
933     // Value not found.  Derive a new type!
934     ST = (StructType*) operator new(sizeof(StructType) +
935                                     sizeof(PATypeHandle) * ETypes.size());
936     new (ST) StructType(Context, ETypes, isPacked);
937     pImpl->StructTypes.add(STV, ST);
938   }
939 #ifdef DEBUG_MERGE_TYPES
940   DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
941 #endif
942   return ST;
943 }
944
945 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
946   va_list ap;
947   std::vector<const llvm::Type*> StructFields;
948   va_start(ap, type);
949   while (type) {
950     StructFields.push_back(type);
951     type = va_arg(ap, llvm::Type*);
952   }
953   return llvm::StructType::get(Context, StructFields);
954 }
955
956 bool StructType::isValidElementType(const Type *ElemTy) {
957   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
958          !ElemTy->isMetadataTy() && !isa<FunctionType>(ElemTy);
959 }
960
961
962 //===----------------------------------------------------------------------===//
963 // Union Type Factory...
964 //
965
966 UnionType *UnionType::get(const Type* const* Types, unsigned NumTypes) {
967   assert(NumTypes > 0 && "union must have at least one member type!");
968   UnionValType UTV(Types, NumTypes);
969   UnionType *UT = 0;
970   
971   LLVMContextImpl *pImpl = Types[0]->getContext().pImpl;
972   
973   UT = pImpl->UnionTypes.get(UTV);
974     
975   if (!UT) {
976     // Value not found.  Derive a new type!
977     UT = (UnionType*) operator new(sizeof(UnionType) +
978                                    sizeof(PATypeHandle) * NumTypes);
979     new (UT) UnionType(Types[0]->getContext(), Types, NumTypes);
980     pImpl->UnionTypes.add(UTV, UT);
981   }
982 #ifdef DEBUG_MERGE_TYPES
983   DEBUG(dbgs() << "Derived new type: " << *UT << "\n");
984 #endif
985   return UT;
986 }
987
988 UnionType *UnionType::get(const Type *type, ...) {
989   va_list ap;
990   SmallVector<const llvm::Type*, 8> UnionFields;
991   va_start(ap, type);
992   while (type) {
993     UnionFields.push_back(type);
994     type = va_arg(ap, llvm::Type*);
995   }
996   unsigned NumTypes = UnionFields.size();
997   assert(NumTypes > 0 && "union must have at least one member type!");
998   return llvm::UnionType::get(&UnionFields[0], NumTypes);
999 }
1000
1001 bool UnionType::isValidElementType(const Type *ElemTy) {
1002   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
1003          !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
1004 }
1005
1006 int UnionType::getElementTypeIndex(const Type *ElemTy) const {
1007   int index = 0;
1008   for (UnionType::element_iterator I = element_begin(), E = element_end();
1009        I != E; ++I, ++index) {
1010      if (ElemTy == *I) return index;
1011   }
1012   
1013   return -1;
1014 }
1015
1016 //===----------------------------------------------------------------------===//
1017 // Pointer Type Factory...
1018 //
1019
1020 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1021   assert(ValueType && "Can't get a pointer to <null> type!");
1022   assert(ValueType->getTypeID() != VoidTyID &&
1023          "Pointer to void is not valid, use i8* instead!");
1024   assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1025   PointerValType PVT(ValueType, AddressSpace);
1026
1027   PointerType *PT = 0;
1028   
1029   LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
1030   
1031   PT = pImpl->PointerTypes.get(PVT);
1032   
1033   if (!PT) {
1034     // Value not found.  Derive a new type!
1035     pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
1036   }
1037 #ifdef DEBUG_MERGE_TYPES
1038   DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
1039 #endif
1040   return PT;
1041 }
1042
1043 const PointerType *Type::getPointerTo(unsigned addrs) const {
1044   return PointerType::get(this, addrs);
1045 }
1046
1047 bool PointerType::isValidElementType(const Type *ElemTy) {
1048   return ElemTy->getTypeID() != VoidTyID &&
1049          ElemTy->getTypeID() != LabelTyID &&
1050          ElemTy->getTypeID() != MetadataTyID;
1051 }
1052
1053
1054 //===----------------------------------------------------------------------===//
1055 // Opaque Type Factory...
1056 //
1057
1058 OpaqueType *OpaqueType::get(LLVMContext &C) {
1059   OpaqueType *OT = new OpaqueType(C);           // All opaque types are distinct
1060   
1061   LLVMContextImpl *pImpl = C.pImpl;
1062   pImpl->OpaqueTypes.insert(OT);
1063   return OT;
1064 }
1065
1066
1067
1068 //===----------------------------------------------------------------------===//
1069 //                     Derived Type Refinement Functions
1070 //===----------------------------------------------------------------------===//
1071
1072 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1073 // it.  This function is called primarily by the PATypeHandle class.
1074 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1075   assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1076   AbstractTypeUsers.push_back(U);
1077 }
1078
1079
1080 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1081 // no longer has a handle to the type.  This function is called primarily by
1082 // the PATypeHandle class.  When there are no users of the abstract type, it
1083 // is annihilated, because there is no way to get a reference to it ever again.
1084 //
1085 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1086   
1087   // Search from back to front because we will notify users from back to
1088   // front.  Also, it is likely that there will be a stack like behavior to
1089   // users that register and unregister users.
1090   //
1091   unsigned i;
1092   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1093     assert(i != 0 && "AbstractTypeUser not in user list!");
1094
1095   --i;  // Convert to be in range 0 <= i < size()
1096   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1097
1098   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1099
1100 #ifdef DEBUG_MERGE_TYPES
1101   DEBUG(dbgs() << "  remAbstractTypeUser[" << (void*)this << ", "
1102                << *this << "][" << i << "] User = " << U << "\n");
1103 #endif
1104
1105   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1106 #ifdef DEBUG_MERGE_TYPES
1107     DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1108                  << ">[" << (void*)this << "]" << "\n");
1109 #endif
1110   
1111   this->destroy();
1112   }
1113   
1114 }
1115
1116 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1117 // that the 'this' abstract type is actually equivalent to the NewType
1118 // specified. This causes all users of 'this' to switch to reference the more 
1119 // concrete type NewType and for 'this' to be deleted.  Only used for internal
1120 // callers.
1121 //
1122 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1123   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1124   assert(this != NewType && "Can't refine to myself!");
1125   assert(ForwardType == 0 && "This type has already been refined!");
1126
1127   LLVMContextImpl *pImpl = getContext().pImpl;
1128
1129   // The descriptions may be out of date.  Conservatively clear them all!
1130   pImpl->AbstractTypeDescriptions.clear();
1131
1132 #ifdef DEBUG_MERGE_TYPES
1133   DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1134                << *this << "] to [" << (void*)NewType << " "
1135                << *NewType << "]!\n");
1136 #endif
1137
1138   // Make sure to put the type to be refined to into a holder so that if IT gets
1139   // refined, that we will not continue using a dead reference...
1140   //
1141   PATypeHolder NewTy(NewType);
1142   // Any PATypeHolders referring to this type will now automatically forward to
1143   // the type we are resolved to.
1144   ForwardType = NewType;
1145   if (NewType->isAbstract())
1146     cast<DerivedType>(NewType)->addRef();
1147
1148   // Add a self use of the current type so that we don't delete ourself until
1149   // after the function exits.
1150   //
1151   PATypeHolder CurrentTy(this);
1152
1153   // To make the situation simpler, we ask the subclass to remove this type from
1154   // the type map, and to replace any type uses with uses of non-abstract types.
1155   // This dramatically limits the amount of recursive type trouble we can find
1156   // ourselves in.
1157   dropAllTypeUses();
1158
1159   // Iterate over all of the uses of this type, invoking callback.  Each user
1160   // should remove itself from our use list automatically.  We have to check to
1161   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1162   // will not cause users to drop off of the use list.  If we resolve to ourself
1163   // we succeed!
1164   //
1165   while (!AbstractTypeUsers.empty() && NewTy != this) {
1166     AbstractTypeUser *User = AbstractTypeUsers.back();
1167
1168     unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1169 #ifdef DEBUG_MERGE_TYPES
1170     DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1171                  << "] of abstract type [" << (void*)this << " "
1172                  << *this << "] to [" << (void*)NewTy.get() << " "
1173                  << *NewTy << "]!\n");
1174 #endif
1175     User->refineAbstractType(this, NewTy);
1176
1177     assert(AbstractTypeUsers.size() != OldSize &&
1178            "AbsTyUser did not remove self from user list!");
1179   }
1180
1181   // If we were successful removing all users from the type, 'this' will be
1182   // deleted when the last PATypeHolder is destroyed or updated from this type.
1183   // This may occur on exit of this function, as the CurrentTy object is
1184   // destroyed.
1185 }
1186
1187 // refineAbstractTypeTo - This function is used by external callers to notify
1188 // us that this abstract type is equivalent to another type.
1189 //
1190 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1191   // All recursive calls will go through unlockedRefineAbstractTypeTo,
1192   // to avoid deadlock problems.
1193   unlockedRefineAbstractTypeTo(NewType);
1194 }
1195
1196 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1197 // the current type has transitioned from being abstract to being concrete.
1198 //
1199 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1200 #ifdef DEBUG_MERGE_TYPES
1201   DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1202 #endif
1203
1204   unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1205   while (!AbstractTypeUsers.empty()) {
1206     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1207     ATU->typeBecameConcrete(this);
1208
1209     assert(AbstractTypeUsers.size() < OldSize-- &&
1210            "AbstractTypeUser did not remove itself from the use list!");
1211   }
1212 }
1213
1214 // refineAbstractType - Called when a contained type is found to be more
1215 // concrete - this could potentially change us from an abstract type to a
1216 // concrete type.
1217 //
1218 void FunctionType::refineAbstractType(const DerivedType *OldType,
1219                                       const Type *NewType) {
1220   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1221   pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1222 }
1223
1224 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1225   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1226   pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1227 }
1228
1229
1230 // refineAbstractType - Called when a contained type is found to be more
1231 // concrete - this could potentially change us from an abstract type to a
1232 // concrete type.
1233 //
1234 void ArrayType::refineAbstractType(const DerivedType *OldType,
1235                                    const Type *NewType) {
1236   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1237   pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1238 }
1239
1240 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1241   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1242   pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1243 }
1244
1245 // refineAbstractType - Called when a contained type is found to be more
1246 // concrete - this could potentially change us from an abstract type to a
1247 // concrete type.
1248 //
1249 void VectorType::refineAbstractType(const DerivedType *OldType,
1250                                    const Type *NewType) {
1251   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1252   pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1253 }
1254
1255 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1256   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1257   pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1258 }
1259
1260 // refineAbstractType - Called when a contained type is found to be more
1261 // concrete - this could potentially change us from an abstract type to a
1262 // concrete type.
1263 //
1264 void StructType::refineAbstractType(const DerivedType *OldType,
1265                                     const Type *NewType) {
1266   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1267   pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1268 }
1269
1270 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1271   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1272   pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1273 }
1274
1275 // refineAbstractType - Called when a contained type is found to be more
1276 // concrete - this could potentially change us from an abstract type to a
1277 // concrete type.
1278 //
1279 void UnionType::refineAbstractType(const DerivedType *OldType,
1280                                     const Type *NewType) {
1281   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1282   pImpl->UnionTypes.RefineAbstractType(this, OldType, NewType);
1283 }
1284
1285 void UnionType::typeBecameConcrete(const DerivedType *AbsTy) {
1286   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1287   pImpl->UnionTypes.TypeBecameConcrete(this, AbsTy);
1288 }
1289
1290 // refineAbstractType - Called when a contained type is found to be more
1291 // concrete - this could potentially change us from an abstract type to a
1292 // concrete type.
1293 //
1294 void PointerType::refineAbstractType(const DerivedType *OldType,
1295                                      const Type *NewType) {
1296   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1297   pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1298 }
1299
1300 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1301   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1302   pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1303 }
1304
1305 bool SequentialType::indexValid(const Value *V) const {
1306   if (isa<IntegerType>(V->getType())) 
1307     return true;
1308   return false;
1309 }
1310
1311 namespace llvm {
1312 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
1313   T.print(OS);
1314   return OS;
1315 }
1316 }