LLVM API Documentation

Type.cpp

Go to the documentation of this file.
00001 //===-- Type.cpp - Implement the Type class -------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Type class for the VMCore library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/AbstractTypeUser.h"
00015 #include "llvm/DerivedTypes.h"
00016 #include "llvm/SymbolTable.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/ADT/DepthFirstIterator.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/ADT/SCCIterator.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/Support/MathExtras.h"
00023 #include <algorithm>
00024 #include <iostream>
00025 using namespace llvm;
00026 
00027 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
00028 // created and later destroyed, all in an effort to make sure that there is only
00029 // a single canonical version of a type.
00030 //
00031 //#define DEBUG_MERGE_TYPES 1
00032 
00033 AbstractTypeUser::~AbstractTypeUser() {}
00034 
00035 //===----------------------------------------------------------------------===//
00036 //                         Type Class Implementation
00037 //===----------------------------------------------------------------------===//
00038 
00039 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
00040 // for types as they are needed.  Because resolution of types must invalidate
00041 // all of the abstract type descriptions, we keep them in a seperate map to make
00042 // this easy.
00043 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
00044 static std::map<const Type*, std::string> AbstractTypeDescriptions;
00045 
00046 Type::Type(const char *Name, TypeID id)
00047   : ID(id), Abstract(false),  RefCount(0), ForwardType(0) {
00048   assert(Name && Name[0] && "Should use other ctor if no name!");
00049   ConcreteTypeDescriptions[this] = Name;
00050 }
00051 
00052 
00053 const Type *Type::getPrimitiveType(TypeID IDNumber) {
00054   switch (IDNumber) {
00055   case VoidTyID  : return VoidTy;
00056   case BoolTyID  : return BoolTy;
00057   case UByteTyID : return UByteTy;
00058   case SByteTyID : return SByteTy;
00059   case UShortTyID: return UShortTy;
00060   case ShortTyID : return ShortTy;
00061   case UIntTyID  : return UIntTy;
00062   case IntTyID   : return IntTy;
00063   case ULongTyID : return ULongTy;
00064   case LongTyID  : return LongTy;
00065   case FloatTyID : return FloatTy;
00066   case DoubleTyID: return DoubleTy;
00067   case LabelTyID : return LabelTy;
00068   default:
00069     return 0;
00070   }
00071 }
00072 
00073 // isLosslesslyConvertibleTo - Return true if this type can be converted to
00074 // 'Ty' without any reinterpretation of bits.  For example, uint to int.
00075 //
00076 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
00077   if (this == Ty) return true;
00078   
00079   // Packed type conversions are always bitwise.
00080   if (isa<PackedType>(this) && isa<PackedType>(Ty))
00081     return true;
00082   
00083   if ((!isPrimitiveType()    && !isa<PointerType>(this)) ||
00084       (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
00085 
00086   if (getTypeID() == Ty->getTypeID())
00087     return true;  // Handles identity cast, and cast of differing pointer types
00088 
00089   // Now we know that they are two differing primitive or pointer types
00090   switch (getTypeID()) {
00091   case Type::UByteTyID:   return Ty == Type::SByteTy;
00092   case Type::SByteTyID:   return Ty == Type::UByteTy;
00093   case Type::UShortTyID:  return Ty == Type::ShortTy;
00094   case Type::ShortTyID:   return Ty == Type::UShortTy;
00095   case Type::UIntTyID:    return Ty == Type::IntTy;
00096   case Type::IntTyID:     return Ty == Type::UIntTy;
00097   case Type::ULongTyID:   return Ty == Type::LongTy;
00098   case Type::LongTyID:    return Ty == Type::ULongTy;
00099   case Type::PointerTyID: return isa<PointerType>(Ty);
00100   default:
00101     return false;  // Other types have no identity values
00102   }
00103 }
00104 
00105 /// getUnsignedVersion - If this is an integer type, return the unsigned
00106 /// variant of this type.  For example int -> uint.
00107 const Type *Type::getUnsignedVersion() const {
00108   switch (getTypeID()) {
00109   default:
00110     assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
00111   case Type::UByteTyID:
00112   case Type::SByteTyID:   return Type::UByteTy;
00113   case Type::UShortTyID:
00114   case Type::ShortTyID:   return Type::UShortTy;
00115   case Type::UIntTyID:
00116   case Type::IntTyID:     return Type::UIntTy;
00117   case Type::ULongTyID:
00118   case Type::LongTyID:    return Type::ULongTy;
00119   }
00120 }
00121 
00122 /// getSignedVersion - If this is an integer type, return the signed variant
00123 /// of this type.  For example uint -> int.
00124 const Type *Type::getSignedVersion() const {
00125   switch (getTypeID()) {
00126   default:
00127     assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
00128   case Type::UByteTyID:
00129   case Type::SByteTyID:   return Type::SByteTy;
00130   case Type::UShortTyID:
00131   case Type::ShortTyID:   return Type::ShortTy;
00132   case Type::UIntTyID:
00133   case Type::IntTyID:     return Type::IntTy;
00134   case Type::ULongTyID:
00135   case Type::LongTyID:    return Type::LongTy;
00136   }
00137 }
00138 
00139 
00140 // getPrimitiveSize - Return the basic size of this type if it is a primitive
00141 // type.  These are fixed by LLVM and are not target dependent.  This will
00142 // return zero if the type does not have a size or is not a primitive type.
00143 //
00144 unsigned Type::getPrimitiveSize() const {
00145   switch (getTypeID()) {
00146   case Type::BoolTyID:
00147   case Type::SByteTyID:
00148   case Type::UByteTyID: return 1;
00149   case Type::UShortTyID:
00150   case Type::ShortTyID: return 2;
00151   case Type::FloatTyID:
00152   case Type::IntTyID:
00153   case Type::UIntTyID: return 4;
00154   case Type::LongTyID:
00155   case Type::ULongTyID:
00156   case Type::DoubleTyID: return 8;
00157   default: return 0;
00158   }
00159 }
00160 
00161 unsigned Type::getPrimitiveSizeInBits() const {
00162   switch (getTypeID()) {
00163   case Type::BoolTyID:  return 1;
00164   case Type::SByteTyID:
00165   case Type::UByteTyID: return 8;
00166   case Type::UShortTyID:
00167   case Type::ShortTyID: return 16;
00168   case Type::FloatTyID:
00169   case Type::IntTyID:
00170   case Type::UIntTyID: return 32;
00171   case Type::LongTyID:
00172   case Type::ULongTyID:
00173   case Type::DoubleTyID: return 64;
00174   default: return 0;
00175   }
00176 }
00177 
00178 /// isSizedDerivedType - Derived types like structures and arrays are sized
00179 /// iff all of the members of the type are sized as well.  Since asking for
00180 /// their size is relatively uncommon, move this operation out of line.
00181 bool Type::isSizedDerivedType() const {
00182   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
00183     return ATy->getElementType()->isSized();
00184 
00185   if (const PackedType *PTy = dyn_cast<PackedType>(this))
00186     return PTy->getElementType()->isSized();
00187 
00188   if (!isa<StructType>(this)) return false;
00189 
00190   // Okay, our struct is sized if all of the elements are...
00191   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
00192     if (!(*I)->isSized()) return false;
00193 
00194   return true;
00195 }
00196 
00197 /// getForwardedTypeInternal - This method is used to implement the union-find
00198 /// algorithm for when a type is being forwarded to another type.
00199 const Type *Type::getForwardedTypeInternal() const {
00200   assert(ForwardType && "This type is not being forwarded to another type!");
00201 
00202   // Check to see if the forwarded type has been forwarded on.  If so, collapse
00203   // the forwarding links.
00204   const Type *RealForwardedType = ForwardType->getForwardedType();
00205   if (!RealForwardedType)
00206     return ForwardType;  // No it's not forwarded again
00207 
00208   // Yes, it is forwarded again.  First thing, add the reference to the new
00209   // forward type.
00210   if (RealForwardedType->isAbstract())
00211     cast<DerivedType>(RealForwardedType)->addRef();
00212 
00213   // Now drop the old reference.  This could cause ForwardType to get deleted.
00214   cast<DerivedType>(ForwardType)->dropRef();
00215 
00216   // Return the updated type.
00217   ForwardType = RealForwardedType;
00218   return ForwardType;
00219 }
00220 
00221 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
00222   abort();
00223 }
00224 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
00225   abort();
00226 }
00227 
00228 
00229 // getTypeDescription - This is a recursive function that walks a type hierarchy
00230 // calculating the description for a type.
00231 //
00232 static std::string getTypeDescription(const Type *Ty,
00233                                       std::vector<const Type *> &TypeStack) {
00234   if (isa<OpaqueType>(Ty)) {                     // Base case for the recursion
00235     std::map<const Type*, std::string>::iterator I =
00236       AbstractTypeDescriptions.lower_bound(Ty);
00237     if (I != AbstractTypeDescriptions.end() && I->first == Ty)
00238       return I->second;
00239     std::string Desc = "opaque";
00240     AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
00241     return Desc;
00242   }
00243 
00244   if (!Ty->isAbstract()) {                       // Base case for the recursion
00245     std::map<const Type*, std::string>::iterator I =
00246       ConcreteTypeDescriptions.find(Ty);
00247     if (I != ConcreteTypeDescriptions.end()) return I->second;
00248   }
00249 
00250   // Check to see if the Type is already on the stack...
00251   unsigned Slot = 0, CurSize = TypeStack.size();
00252   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
00253 
00254   // This is another base case for the recursion.  In this case, we know
00255   // that we have looped back to a type that we have previously visited.
00256   // Generate the appropriate upreference to handle this.
00257   //
00258   if (Slot < CurSize)
00259     return "\\" + utostr(CurSize-Slot);         // Here's the upreference
00260 
00261   // Recursive case: derived types...
00262   std::string Result;
00263   TypeStack.push_back(Ty);    // Add us to the stack..
00264 
00265   switch (Ty->getTypeID()) {
00266   case Type::FunctionTyID: {
00267     const FunctionType *FTy = cast<FunctionType>(Ty);
00268     Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
00269     for (FunctionType::param_iterator I = FTy->param_begin(),
00270            E = FTy->param_end(); I != E; ++I) {
00271       if (I != FTy->param_begin())
00272         Result += ", ";
00273       Result += getTypeDescription(*I, TypeStack);
00274     }
00275     if (FTy->isVarArg()) {
00276       if (FTy->getNumParams()) Result += ", ";
00277       Result += "...";
00278     }
00279     Result += ")";
00280     break;
00281   }
00282   case Type::StructTyID: {
00283     const StructType *STy = cast<StructType>(Ty);
00284     Result = "{ ";
00285     for (StructType::element_iterator I = STy->element_begin(),
00286            E = STy->element_end(); I != E; ++I) {
00287       if (I != STy->element_begin())
00288         Result += ", ";
00289       Result += getTypeDescription(*I, TypeStack);
00290     }
00291     Result += " }";
00292     break;
00293   }
00294   case Type::PointerTyID: {
00295     const PointerType *PTy = cast<PointerType>(Ty);
00296     Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
00297     break;
00298   }
00299   case Type::ArrayTyID: {
00300     const ArrayType *ATy = cast<ArrayType>(Ty);
00301     unsigned NumElements = ATy->getNumElements();
00302     Result = "[";
00303     Result += utostr(NumElements) + " x ";
00304     Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
00305     break;
00306   }
00307   case Type::PackedTyID: {
00308     const PackedType *PTy = cast<PackedType>(Ty);
00309     unsigned NumElements = PTy->getNumElements();
00310     Result = "<";
00311     Result += utostr(NumElements) + " x ";
00312     Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
00313     break;
00314   }
00315   default:
00316     Result = "<error>";
00317     assert(0 && "Unhandled type in getTypeDescription!");
00318   }
00319 
00320   TypeStack.pop_back();       // Remove self from stack...
00321 
00322   return Result;
00323 }
00324 
00325 
00326 
00327 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
00328                                           const Type *Ty) {
00329   std::map<const Type*, std::string>::iterator I = Map.find(Ty);
00330   if (I != Map.end()) return I->second;
00331 
00332   std::vector<const Type *> TypeStack;
00333   std::string Result = getTypeDescription(Ty, TypeStack);
00334   return Map[Ty] = Result;
00335 }
00336 
00337 
00338 const std::string &Type::getDescription() const {
00339   if (isAbstract())
00340     return getOrCreateDesc(AbstractTypeDescriptions, this);
00341   else
00342     return getOrCreateDesc(ConcreteTypeDescriptions, this);
00343 }
00344 
00345 
00346 bool StructType::indexValid(const Value *V) const {
00347   // Structure indexes require unsigned integer constants.
00348   if (V->getType() == Type::UIntTy)
00349     if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
00350       return CU->getValue() < ContainedTys.size();
00351   return false;
00352 }
00353 
00354 // getTypeAtIndex - Given an index value into the type, return the type of the
00355 // element.  For a structure type, this must be a constant value...
00356 //
00357 const Type *StructType::getTypeAtIndex(const Value *V) const {
00358   assert(indexValid(V) && "Invalid structure index!");
00359   unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
00360   return ContainedTys[Idx];
00361 }
00362 
00363 
00364 //===----------------------------------------------------------------------===//
00365 //                           Static 'Type' data
00366 //===----------------------------------------------------------------------===//
00367 
00368 namespace {
00369   struct PrimType : public Type {
00370     PrimType(const char *S, TypeID ID) : Type(S, ID) {}
00371   };
00372 }
00373 
00374 static PrimType TheVoidTy  ("void"  , Type::VoidTyID);
00375 static PrimType TheBoolTy  ("bool"  , Type::BoolTyID);
00376 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
00377 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
00378 static PrimType TheShortTy ("short" , Type::ShortTyID);
00379 static PrimType TheUShortTy("ushort", Type::UShortTyID);
00380 static PrimType TheIntTy   ("int"   , Type::IntTyID);
00381 static PrimType TheUIntTy  ("uint"  , Type::UIntTyID);
00382 static PrimType TheLongTy  ("long"  , Type::LongTyID);
00383 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
00384 static PrimType TheFloatTy ("float" , Type::FloatTyID);
00385 static PrimType TheDoubleTy("double", Type::DoubleTyID);
00386 static PrimType TheLabelTy ("label" , Type::LabelTyID);
00387 
00388 Type *Type::VoidTy   = &TheVoidTy;
00389 Type *Type::BoolTy   = &TheBoolTy;
00390 Type *Type::SByteTy  = &TheSByteTy;
00391 Type *Type::UByteTy  = &TheUByteTy;
00392 Type *Type::ShortTy  = &TheShortTy;
00393 Type *Type::UShortTy = &TheUShortTy;
00394 Type *Type::IntTy    = &TheIntTy;
00395 Type *Type::UIntTy   = &TheUIntTy;
00396 Type *Type::LongTy   = &TheLongTy;
00397 Type *Type::ULongTy  = &TheULongTy;
00398 Type *Type::FloatTy  = &TheFloatTy;
00399 Type *Type::DoubleTy = &TheDoubleTy;
00400 Type *Type::LabelTy  = &TheLabelTy;
00401 
00402 
00403 //===----------------------------------------------------------------------===//
00404 //                          Derived Type Constructors
00405 //===----------------------------------------------------------------------===//
00406 
00407 FunctionType::FunctionType(const Type *Result,
00408                            const std::vector<const Type*> &Params,
00409                            bool IsVarArgs) : DerivedType(FunctionTyID),
00410                                              isVarArgs(IsVarArgs) {
00411   assert((Result->isFirstClassType() || Result == Type::VoidTy ||
00412          isa<OpaqueType>(Result)) &&
00413          "LLVM functions cannot return aggregates");
00414   bool isAbstract = Result->isAbstract();
00415   ContainedTys.reserve(Params.size()+1);
00416   ContainedTys.push_back(PATypeHandle(Result, this));
00417 
00418   for (unsigned i = 0; i != Params.size(); ++i) {
00419     assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
00420            "Function arguments must be value types!");
00421 
00422     ContainedTys.push_back(PATypeHandle(Params[i], this));
00423     isAbstract |= Params[i]->isAbstract();
00424   }
00425 
00426   // Calculate whether or not this type is abstract
00427   setAbstract(isAbstract);
00428 }
00429 
00430 StructType::StructType(const std::vector<const Type*> &Types)
00431   : CompositeType(StructTyID) {
00432   ContainedTys.reserve(Types.size());
00433   bool isAbstract = false;
00434   for (unsigned i = 0; i < Types.size(); ++i) {
00435     assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
00436     ContainedTys.push_back(PATypeHandle(Types[i], this));
00437     isAbstract |= Types[i]->isAbstract();
00438   }
00439 
00440   // Calculate whether or not this type is abstract
00441   setAbstract(isAbstract);
00442 }
00443 
00444 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
00445   : SequentialType(ArrayTyID, ElType) {
00446   NumElements = NumEl;
00447 
00448   // Calculate whether or not this type is abstract
00449   setAbstract(ElType->isAbstract());
00450 }
00451 
00452 PackedType::PackedType(const Type *ElType, unsigned NumEl)
00453   : SequentialType(PackedTyID, ElType) {
00454   NumElements = NumEl;
00455 
00456   assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
00457   assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
00458          "Elements of a PackedType must be a primitive type");
00459 }
00460 
00461 
00462 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
00463   // Calculate whether or not this type is abstract
00464   setAbstract(E->isAbstract());
00465 }
00466 
00467 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
00468   setAbstract(true);
00469 #ifdef DEBUG_MERGE_TYPES
00470   std::cerr << "Derived new type: " << *this << "\n";
00471 #endif
00472 }
00473 
00474 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
00475 // another (more concrete) type, we must eliminate all references to other
00476 // types, to avoid some circular reference problems.
00477 void DerivedType::dropAllTypeUses() {
00478   if (!ContainedTys.empty()) {
00479     // The type must stay abstract.  To do this, we insert a pointer to a type
00480     // that will never get resolved, thus will always be abstract.
00481     static Type *AlwaysOpaqueTy = OpaqueType::get();
00482     static PATypeHolder Holder(AlwaysOpaqueTy);
00483     ContainedTys[0] = AlwaysOpaqueTy;
00484 
00485     // Change the rest of the types to be intty's.  It doesn't matter what we
00486     // pick so long as it doesn't point back to this type.  We choose something
00487     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
00488     for (unsigned i = 1, e = ContainedTys.size(); i != e; ++i)
00489       ContainedTys[i] = Type::IntTy;
00490   }
00491 }
00492 
00493 
00494 
00495 /// TypePromotionGraph and graph traits - this is designed to allow us to do
00496 /// efficient SCC processing of type graphs.  This is the exact same as
00497 /// GraphTraits<Type*>, except that we pretend that concrete types have no
00498 /// children to avoid processing them.
00499 struct TypePromotionGraph {
00500   Type *Ty;
00501   TypePromotionGraph(Type *T) : Ty(T) {}
00502 };
00503 
00504 namespace llvm {
00505   template <> struct GraphTraits<TypePromotionGraph> {
00506     typedef Type NodeType;
00507     typedef Type::subtype_iterator ChildIteratorType;
00508 
00509     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
00510     static inline ChildIteratorType child_begin(NodeType *N) {
00511       if (N->isAbstract())
00512         return N->subtype_begin();
00513       else           // No need to process children of concrete types.
00514         return N->subtype_end();
00515     }
00516     static inline ChildIteratorType child_end(NodeType *N) {
00517       return N->subtype_end();
00518     }
00519   };
00520 }
00521 
00522 
00523 // PromoteAbstractToConcrete - This is a recursive function that walks a type
00524 // graph calculating whether or not a type is abstract.
00525 //
00526 void Type::PromoteAbstractToConcrete() {
00527   if (!isAbstract()) return;
00528 
00529   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
00530   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
00531 
00532   for (; SI != SE; ++SI) {
00533     std::vector<Type*> &SCC = *SI;
00534 
00535     // Concrete types are leaves in the tree.  Since an SCC will either be all
00536     // abstract or all concrete, we only need to check one type.
00537     if (SCC[0]->isAbstract()) {
00538       if (isa<OpaqueType>(SCC[0]))
00539         return;     // Not going to be concrete, sorry.
00540 
00541       // If all of the children of all of the types in this SCC are concrete,
00542       // then this SCC is now concrete as well.  If not, neither this SCC, nor
00543       // any parent SCCs will be concrete, so we might as well just exit.
00544       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
00545         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
00546                E = SCC[i]->subtype_end(); CI != E; ++CI)
00547           if ((*CI)->isAbstract())
00548             // If the child type is in our SCC, it doesn't make the entire SCC
00549             // abstract unless there is a non-SCC abstract type.
00550             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
00551               return;               // Not going to be concrete, sorry.
00552 
00553       // Okay, we just discovered this whole SCC is now concrete, mark it as
00554       // such!
00555       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
00556         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
00557 
00558         SCC[i]->setAbstract(false);
00559       }
00560 
00561       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
00562         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
00563         // The type just became concrete, notify all users!
00564         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
00565       }
00566     }
00567   }
00568 }
00569 
00570 
00571 //===----------------------------------------------------------------------===//
00572 //                      Type Structural Equality Testing
00573 //===----------------------------------------------------------------------===//
00574 
00575 // TypesEqual - Two types are considered structurally equal if they have the
00576 // same "shape": Every level and element of the types have identical primitive
00577 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
00578 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
00579 // that assumes that two graphs are the same until proven otherwise.
00580 //
00581 static bool TypesEqual(const Type *Ty, const Type *Ty2,
00582                        std::map<const Type *, const Type *> &EqTypes) {
00583   if (Ty == Ty2) return true;
00584   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
00585   if (isa<OpaqueType>(Ty))
00586     return false;  // Two unequal opaque types are never equal
00587 
00588   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
00589   if (It != EqTypes.end() && It->first == Ty)
00590     return It->second == Ty2;    // Looping back on a type, check for equality
00591 
00592   // Otherwise, add the mapping to the table to make sure we don't get
00593   // recursion on the types...
00594   EqTypes.insert(It, std::make_pair(Ty, Ty2));
00595 
00596   // Two really annoying special cases that breaks an otherwise nice simple
00597   // algorithm is the fact that arraytypes have sizes that differentiates types,
00598   // and that function types can be varargs or not.  Consider this now.
00599   //
00600   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
00601     return TypesEqual(PTy->getElementType(),
00602                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
00603   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
00604     const StructType *STy2 = cast<StructType>(Ty2);
00605     if (STy->getNumElements() != STy2->getNumElements()) return false;
00606     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
00607       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
00608         return false;
00609     return true;
00610   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00611     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
00612     return ATy->getNumElements() == ATy2->getNumElements() &&
00613            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
00614   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
00615     const PackedType *PTy2 = cast<PackedType>(Ty2);
00616     return PTy->getNumElements() == PTy2->getNumElements() &&
00617            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
00618   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
00619     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
00620     if (FTy->isVarArg() != FTy2->isVarArg() ||
00621         FTy->getNumParams() != FTy2->getNumParams() ||
00622         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
00623       return false;
00624     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
00625       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
00626         return false;
00627     return true;
00628   } else {
00629     assert(0 && "Unknown derived type!");
00630     return false;
00631   }
00632 }
00633 
00634 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
00635   std::map<const Type *, const Type *> EqTypes;
00636   return TypesEqual(Ty, Ty2, EqTypes);
00637 }
00638 
00639 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
00640 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
00641 // ever reach a non-abstract type, we know that we don't need to search the
00642 // subgraph.
00643 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
00644                                 std::set<const Type*> &VisitedTypes) {
00645   if (TargetTy == CurTy) return true;
00646   if (!CurTy->isAbstract()) return false;
00647 
00648   if (!VisitedTypes.insert(CurTy).second)
00649     return false;  // Already been here.
00650 
00651   for (Type::subtype_iterator I = CurTy->subtype_begin(),
00652        E = CurTy->subtype_end(); I != E; ++I)
00653     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
00654       return true;
00655   return false;
00656 }
00657 
00658 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
00659                                         std::set<const Type*> &VisitedTypes) {
00660   if (TargetTy == CurTy) return true;
00661 
00662   if (!VisitedTypes.insert(CurTy).second)
00663     return false;  // Already been here.
00664 
00665   for (Type::subtype_iterator I = CurTy->subtype_begin(),
00666        E = CurTy->subtype_end(); I != E; ++I)
00667     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
00668       return true;
00669   return false;
00670 }
00671 
00672 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
00673 /// back to itself.
00674 static bool TypeHasCycleThroughItself(const Type *Ty) {
00675   std::set<const Type*> VisitedTypes;
00676 
00677   if (Ty->isAbstract()) {  // Optimized case for abstract types.
00678     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
00679          I != E; ++I)
00680       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
00681         return true;
00682   } else {
00683     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
00684          I != E; ++I)
00685       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
00686         return true;
00687   }
00688   return false;
00689 }
00690 
00691 /// getSubElementHash - Generate a hash value for all of the SubType's of this
00692 /// type.  The hash value is guaranteed to be zero if any of the subtypes are 
00693 /// an opaque type.  Otherwise we try to mix them in as well as possible, but do
00694 /// not look at the subtype's subtype's.
00695 static unsigned getSubElementHash(const Type *Ty) {
00696   unsigned HashVal = 0;
00697   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
00698        I != E; ++I) {
00699     HashVal *= 32;
00700     const Type *SubTy = I->get();
00701     HashVal += SubTy->getTypeID();
00702     switch (SubTy->getTypeID()) {
00703     default: break;
00704     case Type::OpaqueTyID: return 0;    // Opaque -> hash = 0 no matter what.
00705     case Type::FunctionTyID:
00706       HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 
00707                  cast<FunctionType>(SubTy)->isVarArg();
00708       break;
00709     case Type::ArrayTyID:
00710       HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
00711       break;
00712     case Type::PackedTyID:
00713       HashVal ^= cast<PackedType>(SubTy)->getNumElements();
00714       break;
00715     case Type::StructTyID:
00716       HashVal ^= cast<StructType>(SubTy)->getNumElements();
00717       break;
00718     }
00719   }
00720   return HashVal ? HashVal : 1;  // Do not return zero unless opaque subty.
00721 }
00722 
00723 //===----------------------------------------------------------------------===//
00724 //                       Derived Type Factory Functions
00725 //===----------------------------------------------------------------------===//
00726 
00727 namespace llvm {
00728 class TypeMapBase {
00729 protected:
00730   /// TypesByHash - Keep track of types by their structure hash value.  Note
00731   /// that we only keep track of types that have cycles through themselves in
00732   /// this map.
00733   ///
00734   std::multimap<unsigned, PATypeHolder> TypesByHash;
00735 
00736 public:
00737   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
00738     std::multimap<unsigned, PATypeHolder>::iterator I =
00739       TypesByHash.lower_bound(Hash);
00740     for (; I != TypesByHash.end() && I->first == Hash; ++I) {
00741       if (I->second == Ty) {
00742         TypesByHash.erase(I);
00743         return;
00744       }
00745     }
00746     
00747     // This must be do to an opaque type that was resolved.  Switch down to hash
00748     // code of zero.
00749     assert(Hash && "Didn't find type entry!");
00750     RemoveFromTypesByHash(0, Ty);
00751   }
00752   
00753   /// TypeBecameConcrete - When Ty gets a notification that TheType just became
00754   /// concrete, drop uses and make Ty non-abstract if we should.
00755   void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
00756     // If the element just became concrete, remove 'ty' from the abstract
00757     // type user list for the type.  Do this for as many times as Ty uses
00758     // OldType.
00759     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
00760          I != E; ++I)
00761       if (I->get() == TheType)
00762         TheType->removeAbstractTypeUser(Ty);
00763     
00764     // If the type is currently thought to be abstract, rescan all of our
00765     // subtypes to see if the type has just become concrete!  Note that this
00766     // may send out notifications to AbstractTypeUsers that types become
00767     // concrete.
00768     if (Ty->isAbstract())
00769       Ty->PromoteAbstractToConcrete();
00770   }
00771 };
00772 }
00773 
00774 
00775 // TypeMap - Make sure that only one instance of a particular type may be
00776 // created on any given run of the compiler... note that this involves updating
00777 // our map if an abstract type gets refined somehow.
00778 //
00779 namespace llvm {
00780 template<class ValType, class TypeClass>
00781 class TypeMap : public TypeMapBase {
00782   std::map<ValType, PATypeHolder> Map;
00783 public:
00784   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
00785   ~TypeMap() { print("ON EXIT"); }
00786 
00787   inline TypeClass *get(const ValType &V) {
00788     iterator I = Map.find(V);
00789     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
00790   }
00791 
00792   inline void add(const ValType &V, TypeClass *Ty) {
00793     Map.insert(std::make_pair(V, Ty));
00794 
00795     // If this type has a cycle, remember it.
00796     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
00797     print("add");
00798   }
00799   
00800   void clear(std::vector<Type *> &DerivedTypes) {
00801     for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(),
00802          E = Map.end(); I != E; ++I)
00803       DerivedTypes.push_back(I->second.get());
00804     TypesByHash.clear();
00805     Map.clear();
00806   }
00807 
00808  /// RefineAbstractType - This method is called after we have merged a type
00809   /// with another one.  We must now either merge the type away with
00810   /// some other type or reinstall it in the map with it's new configuration.
00811   void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
00812                         const Type *NewType) {
00813 #ifdef DEBUG_MERGE_TYPES
00814     std::cerr << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
00815     << "], " << (void*)NewType << " [" << *NewType << "])\n";
00816 #endif
00817     
00818     // Otherwise, we are changing one subelement type into another.  Clearly the
00819     // OldType must have been abstract, making us abstract.
00820     assert(Ty->isAbstract() && "Refining a non-abstract type!");
00821     assert(OldType != NewType);
00822 
00823     // Make a temporary type holder for the type so that it doesn't disappear on
00824     // us when we erase the entry from the map.
00825     PATypeHolder TyHolder = Ty;
00826 
00827     // The old record is now out-of-date, because one of the children has been
00828     // updated.  Remove the obsolete entry from the map.
00829     unsigned NumErased = Map.erase(ValType::get(Ty));
00830     assert(NumErased && "Element not found!");
00831 
00832     // Remember the structural hash for the type before we start hacking on it,
00833     // in case we need it later.
00834     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
00835 
00836     // Find the type element we are refining... and change it now!
00837     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
00838       if (Ty->ContainedTys[i] == OldType)
00839         Ty->ContainedTys[i] = NewType;
00840     unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
00841     
00842     // If there are no cycles going through this node, we can do a simple,
00843     // efficient lookup in the map, instead of an inefficient nasty linear
00844     // lookup.
00845     if (!TypeHasCycleThroughItself(Ty)) {
00846       typename std::map<ValType, PATypeHolder>::iterator I;
00847       bool Inserted;
00848 
00849       tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
00850       if (!Inserted) {
00851         // Refined to a different type altogether?
00852         RemoveFromTypesByHash(OldTypeHash, Ty);
00853 
00854         // We already have this type in the table.  Get rid of the newly refined
00855         // type.
00856         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
00857         Ty->refineAbstractTypeTo(NewTy);
00858         return;
00859       }
00860     } else {
00861       // Now we check to see if there is an existing entry in the table which is
00862       // structurally identical to the newly refined type.  If so, this type
00863       // gets refined to the pre-existing type.
00864       //
00865       std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
00866       tie(I, E) = TypesByHash.equal_range(NewTypeHash);
00867       Entry = E;
00868       for (; I != E; ++I) {
00869         if (I->second == Ty) {
00870           // Remember the position of the old type if we see it in our scan.
00871           Entry = I;
00872         } else {
00873           if (TypesEqual(Ty, I->second)) {
00874             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
00875 
00876             // Remove the old entry form TypesByHash.  If the hash values differ
00877             // now, remove it from the old place.  Otherwise, continue scanning
00878             // withing this hashcode to reduce work.
00879             if (NewTypeHash != OldTypeHash) {
00880               RemoveFromTypesByHash(OldTypeHash, Ty);
00881             } else {
00882               if (Entry == E) {
00883                 // Find the location of Ty in the TypesByHash structure if we
00884                 // haven't seen it already.
00885                 while (I->second != Ty) {
00886                   ++I;
00887                   assert(I != E && "Structure doesn't contain type??");
00888                 }
00889                 Entry = I;
00890               }
00891               TypesByHash.erase(Entry);
00892             }
00893             Ty->refineAbstractTypeTo(NewTy);
00894             return;
00895           }
00896         }
00897       }
00898 
00899       // If there is no existing type of the same structure, we reinsert an
00900       // updated record into the map.
00901       Map.insert(std::make_pair(ValType::get(Ty), Ty));
00902     }
00903 
00904     // If the hash codes differ, update TypesByHash
00905     if (NewTypeHash != OldTypeHash) {
00906       RemoveFromTypesByHash(OldTypeHash, Ty);
00907       TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
00908     }
00909     
00910     // If the type is currently thought to be abstract, rescan all of our
00911     // subtypes to see if the type has just become concrete!  Note that this
00912     // may send out notifications to AbstractTypeUsers that types become
00913     // concrete.
00914     if (Ty->isAbstract())
00915       Ty->PromoteAbstractToConcrete();
00916   }
00917 
00918   void print(const char *Arg) const {
00919 #ifdef DEBUG_MERGE_TYPES
00920     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
00921     unsigned i = 0;
00922     for (typename std::map<ValType, PATypeHolder>::const_iterator I
00923            = Map.begin(), E = Map.end(); I != E; ++I)
00924       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
00925                 << *I->second.get() << "\n";
00926 #endif
00927   }
00928 
00929   void dump() const { print("dump output"); }
00930 };
00931 }
00932 
00933 
00934 //===----------------------------------------------------------------------===//
00935 // Function Type Factory and Value Class...
00936 //
00937 
00938 // FunctionValType - Define a class to hold the key that goes into the TypeMap
00939 //
00940 namespace llvm {
00941 class FunctionValType {
00942   const Type *RetTy;
00943   std::vector<const Type*> ArgTypes;
00944   bool isVarArg;
00945 public:
00946   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
00947                   bool IVA) : RetTy(ret), isVarArg(IVA) {
00948     for (unsigned i = 0; i < args.size(); ++i)
00949       ArgTypes.push_back(args[i]);
00950   }
00951 
00952   static FunctionValType get(const FunctionType *FT);
00953 
00954   static unsigned hashTypeStructure(const FunctionType *FT) {
00955     return FT->getNumParams()*2+FT->isVarArg();
00956   }
00957 
00958   // Subclass should override this... to update self as usual
00959   void doRefinement(const DerivedType *OldType, const Type *NewType) {
00960     if (RetTy == OldType) RetTy = NewType;
00961     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
00962       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
00963   }
00964 
00965   inline bool operator<(const FunctionValType &MTV) const {
00966     if (RetTy < MTV.RetTy) return true;
00967     if (RetTy > MTV.RetTy) return false;
00968 
00969     if (ArgTypes < MTV.ArgTypes) return true;
00970     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
00971   }
00972 };
00973 }
00974 
00975 // Define the actual map itself now...
00976 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
00977 
00978 FunctionValType FunctionValType::get(const FunctionType *FT) {
00979   // Build up a FunctionValType
00980   std::vector<const Type *> ParamTypes;
00981   ParamTypes.reserve(FT->getNumParams());
00982   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
00983     ParamTypes.push_back(FT->getParamType(i));
00984   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
00985 }
00986 
00987 
00988 // FunctionType::get - The factory function for the FunctionType class...
00989 FunctionType *FunctionType::get(const Type *ReturnType,
00990                                 const std::vector<const Type*> &Params,
00991                                 bool isVarArg) {
00992   FunctionValType VT(ReturnType, Params, isVarArg);
00993   FunctionType *MT = FunctionTypes.get(VT);
00994   if (MT) return MT;
00995 
00996   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
00997 
00998 #ifdef DEBUG_MERGE_TYPES
00999   std::cerr << "Derived new type: " << MT << "\n";
01000 #endif
01001   return MT;
01002 }
01003 
01004 //===----------------------------------------------------------------------===//
01005 // Array Type Factory...
01006 //
01007 namespace llvm {
01008 class ArrayValType {
01009   const Type *ValTy;
01010   uint64_t Size;
01011 public:
01012   ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
01013 
01014   static ArrayValType get(const ArrayType *AT) {
01015     return ArrayValType(AT->getElementType(), AT->getNumElements());
01016   }
01017 
01018   static unsigned hashTypeStructure(const ArrayType *AT) {
01019     return (unsigned)AT->getNumElements();
01020   }
01021 
01022   // Subclass should override this... to update self as usual
01023   void doRefinement(const DerivedType *OldType, const Type *NewType) {
01024     assert(ValTy == OldType);
01025     ValTy = NewType;
01026   }
01027 
01028   inline bool operator<(const ArrayValType &MTV) const {
01029     if (Size < MTV.Size) return true;
01030     return Size == MTV.Size && ValTy < MTV.ValTy;
01031   }
01032 };
01033 }
01034 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
01035 
01036 
01037 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
01038   assert(ElementType && "Can't get array of null types!");
01039 
01040   ArrayValType AVT(ElementType, NumElements);
01041   ArrayType *AT = ArrayTypes.get(AVT);
01042   if (AT) return AT;           // Found a match, return it!
01043 
01044   // Value not found.  Derive a new type!
01045   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
01046 
01047 #ifdef DEBUG_MERGE_TYPES
01048   std::cerr << "Derived new type: " << *AT << "\n";
01049 #endif
01050   return AT;
01051 }
01052 
01053 
01054 //===----------------------------------------------------------------------===//
01055 // Packed Type Factory...
01056 //
01057 namespace llvm {
01058 class PackedValType {
01059   const Type *ValTy;
01060   unsigned Size;
01061 public:
01062   PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
01063 
01064   static PackedValType get(const PackedType *PT) {
01065     return PackedValType(PT->getElementType(), PT->getNumElements());
01066   }
01067 
01068   static unsigned hashTypeStructure(const PackedType *PT) {
01069     return PT->getNumElements();
01070   }
01071 
01072   // Subclass should override this... to update self as usual
01073   void doRefinement(const DerivedType *OldType, const Type *NewType) {
01074     assert(ValTy == OldType);
01075     ValTy = NewType;
01076   }
01077 
01078   inline bool operator<(const PackedValType &MTV) const {
01079     if (Size < MTV.Size) return true;
01080     return Size == MTV.Size && ValTy < MTV.ValTy;
01081   }
01082 };
01083 }
01084 static TypeMap<PackedValType, PackedType> PackedTypes;
01085 
01086 
01087 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
01088   assert(ElementType && "Can't get packed of null types!");
01089   assert(isPowerOf2_32(NumElements) && "Vector length should be a power of 2!");
01090 
01091   PackedValType PVT(ElementType, NumElements);
01092   PackedType *PT = PackedTypes.get(PVT);
01093   if (PT) return PT;           // Found a match, return it!
01094 
01095   // Value not found.  Derive a new type!
01096   PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
01097 
01098 #ifdef DEBUG_MERGE_TYPES
01099   std::cerr << "Derived new type: " << *PT << "\n";
01100 #endif
01101   return PT;
01102 }
01103 
01104 //===----------------------------------------------------------------------===//
01105 // Struct Type Factory...
01106 //
01107 
01108 namespace llvm {
01109 // StructValType - Define a class to hold the key that goes into the TypeMap
01110 //
01111 class StructValType {
01112   std::vector<const Type*> ElTypes;
01113 public:
01114   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
01115 
01116   static StructValType get(const StructType *ST) {
01117     std::vector<const Type *> ElTypes;
01118     ElTypes.reserve(ST->getNumElements());
01119     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
01120       ElTypes.push_back(ST->getElementType(i));
01121 
01122     return StructValType(ElTypes);
01123   }
01124 
01125   static unsigned hashTypeStructure(const StructType *ST) {
01126     return ST->getNumElements();
01127   }
01128 
01129   // Subclass should override this... to update self as usual
01130   void doRefinement(const DerivedType *OldType, const Type *NewType) {
01131     for (unsigned i = 0; i < ElTypes.size(); ++i)
01132       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
01133   }
01134 
01135   inline bool operator<(const StructValType &STV) const {
01136     return ElTypes < STV.ElTypes;
01137   }
01138 };
01139 }
01140 
01141 static TypeMap<StructValType, StructType> StructTypes;
01142 
01143 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
01144   StructValType STV(ETypes);
01145   StructType *ST = StructTypes.get(STV);
01146   if (ST) return ST;
01147 
01148   // Value not found.  Derive a new type!
01149   StructTypes.add(STV, ST = new StructType(ETypes));
01150 
01151 #ifdef DEBUG_MERGE_TYPES
01152   std::cerr << "Derived new type: " << *ST << "\n";
01153 #endif
01154   return ST;
01155 }
01156 
01157 
01158 
01159 //===----------------------------------------------------------------------===//
01160 // Pointer Type Factory...
01161 //
01162 
01163 // PointerValType - Define a class to hold the key that goes into the TypeMap
01164 //
01165 namespace llvm {
01166 class PointerValType {
01167   const Type *ValTy;
01168 public:
01169   PointerValType(const Type *val) : ValTy(val) {}
01170 
01171   static PointerValType get(const PointerType *PT) {
01172     return PointerValType(PT->getElementType());
01173   }
01174 
01175   static unsigned hashTypeStructure(const PointerType *PT) {
01176     return getSubElementHash(PT);
01177   }
01178 
01179   // Subclass should override this... to update self as usual
01180   void doRefinement(const DerivedType *OldType, const Type *NewType) {
01181     assert(ValTy == OldType);
01182     ValTy = NewType;
01183   }
01184 
01185   bool operator<(const PointerValType &MTV) const {
01186     return ValTy < MTV.ValTy;
01187   }
01188 };
01189 }
01190 
01191 static TypeMap<PointerValType, PointerType> PointerTypes;
01192 
01193 PointerType *PointerType::get(const Type *ValueType) {
01194   assert(ValueType && "Can't get a pointer to <null> type!");
01195   // FIXME: The sparc backend makes void pointers, which is horribly broken.
01196   // "Fix" it, then reenable this assertion.
01197   //assert(ValueType != Type::VoidTy &&
01198   //       "Pointer to void is not valid, use sbyte* instead!");
01199   PointerValType PVT(ValueType);
01200 
01201   PointerType *PT = PointerTypes.get(PVT);
01202   if (PT) return PT;
01203 
01204   // Value not found.  Derive a new type!
01205   PointerTypes.add(PVT, PT = new PointerType(ValueType));
01206 
01207 #ifdef DEBUG_MERGE_TYPES
01208   std::cerr << "Derived new type: " << *PT << "\n";
01209 #endif
01210   return PT;
01211 }
01212 
01213 //===----------------------------------------------------------------------===//
01214 //                     Derived Type Refinement Functions
01215 //===----------------------------------------------------------------------===//
01216 
01217 // removeAbstractTypeUser - Notify an abstract type that a user of the class
01218 // no longer has a handle to the type.  This function is called primarily by
01219 // the PATypeHandle class.  When there are no users of the abstract type, it
01220 // is annihilated, because there is no way to get a reference to it ever again.
01221 //
01222 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
01223   // Search from back to front because we will notify users from back to
01224   // front.  Also, it is likely that there will be a stack like behavior to
01225   // users that register and unregister users.
01226   //
01227   unsigned i;
01228   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
01229     assert(i != 0 && "AbstractTypeUser not in user list!");
01230 
01231   --i;  // Convert to be in range 0 <= i < size()
01232   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
01233 
01234   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
01235 
01236 #ifdef DEBUG_MERGE_TYPES
01237   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
01238             << *this << "][" << i << "] User = " << U << "\n";
01239 #endif
01240 
01241   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
01242 #ifdef DEBUG_MERGE_TYPES
01243     std::cerr << "DELETEing unused abstract type: <" << *this
01244               << ">[" << (void*)this << "]" << "\n";
01245 #endif
01246     delete this;                  // No users of this abstract type!
01247   }
01248 }
01249 
01250 
01251 // refineAbstractTypeTo - This function is used to when it is discovered that
01252 // the 'this' abstract type is actually equivalent to the NewType specified.
01253 // This causes all users of 'this' to switch to reference the more concrete type
01254 // NewType and for 'this' to be deleted.
01255 //
01256 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
01257   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
01258   assert(this != NewType && "Can't refine to myself!");
01259   assert(ForwardType == 0 && "This type has already been refined!");
01260 
01261   // The descriptions may be out of date.  Conservatively clear them all!
01262   AbstractTypeDescriptions.clear();
01263 
01264 #ifdef DEBUG_MERGE_TYPES
01265   std::cerr << "REFINING abstract type [" << (void*)this << " "
01266             << *this << "] to [" << (void*)NewType << " "
01267             << *NewType << "]!\n";
01268 #endif
01269 
01270   // Make sure to put the type to be refined to into a holder so that if IT gets
01271   // refined, that we will not continue using a dead reference...
01272   //
01273   PATypeHolder NewTy(NewType);
01274 
01275   // Any PATypeHolders referring to this type will now automatically forward to
01276   // the type we are resolved to.
01277   ForwardType = NewType;
01278   if (NewType->isAbstract())
01279     cast<DerivedType>(NewType)->addRef();
01280 
01281   // Add a self use of the current type so that we don't delete ourself until
01282   // after the function exits.
01283   //
01284   PATypeHolder CurrentTy(this);
01285 
01286   // To make the situation simpler, we ask the subclass to remove this type from
01287   // the type map, and to replace any type uses with uses of non-abstract types.
01288   // This dramatically limits the amount of recursive type trouble we can find
01289   // ourselves in.
01290   dropAllTypeUses();
01291 
01292   // Iterate over all of the uses of this type, invoking callback.  Each user
01293   // should remove itself from our use list automatically.  We have to check to
01294   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
01295   // will not cause users to drop off of the use list.  If we resolve to ourself
01296   // we succeed!
01297   //
01298   while (!AbstractTypeUsers.empty() && NewTy != this) {
01299     AbstractTypeUser *User = AbstractTypeUsers.back();
01300 
01301     unsigned OldSize = AbstractTypeUsers.size();
01302 #ifdef DEBUG_MERGE_TYPES
01303     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
01304               << "] of abstract type [" << (void*)this << " "
01305               << *this << "] to [" << (void*)NewTy.get() << " "
01306               << *NewTy << "]!\n";
01307 #endif
01308     User->refineAbstractType(this, NewTy);
01309 
01310     assert(AbstractTypeUsers.size() != OldSize &&
01311            "AbsTyUser did not remove self from user list!");
01312   }
01313 
01314   // If we were successful removing all users from the type, 'this' will be
01315   // deleted when the last PATypeHolder is destroyed or updated from this type.
01316   // This may occur on exit of this function, as the CurrentTy object is
01317   // destroyed.
01318 }
01319 
01320 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
01321 // the current type has transitioned from being abstract to being concrete.
01322 //
01323 void DerivedType::notifyUsesThatTypeBecameConcrete() {
01324 #ifdef DEBUG_MERGE_TYPES
01325   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
01326 #endif
01327 
01328   unsigned OldSize = AbstractTypeUsers.size();
01329   while (!AbstractTypeUsers.empty()) {
01330     AbstractTypeUser *ATU = AbstractTypeUsers.back();
01331     ATU->typeBecameConcrete(this);
01332 
01333     assert(AbstractTypeUsers.size() < OldSize-- &&
01334            "AbstractTypeUser did not remove itself from the use list!");
01335   }
01336 }
01337 
01338 // refineAbstractType - Called when a contained type is found to be more
01339 // concrete - this could potentially change us from an abstract type to a
01340 // concrete type.
01341 //
01342 void FunctionType::refineAbstractType(const DerivedType *OldType,
01343                                       const Type *NewType) {
01344   FunctionTypes.RefineAbstractType(this, OldType, NewType);
01345 }
01346 
01347 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
01348   FunctionTypes.TypeBecameConcrete(this, AbsTy);
01349 }
01350 
01351 
01352 // refineAbstractType - Called when a contained type is found to be more
01353 // concrete - this could potentially change us from an abstract type to a
01354 // concrete type.
01355 //
01356 void ArrayType::refineAbstractType(const DerivedType *OldType,
01357                                    const Type *NewType) {
01358   ArrayTypes.RefineAbstractType(this, OldType, NewType);
01359 }
01360 
01361 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
01362   ArrayTypes.TypeBecameConcrete(this, AbsTy);
01363 }
01364 
01365 // refineAbstractType - Called when a contained type is found to be more
01366 // concrete - this could potentially change us from an abstract type to a
01367 // concrete type.
01368 //
01369 void PackedType::refineAbstractType(const DerivedType *OldType,
01370                                    const Type *NewType) {
01371   PackedTypes.RefineAbstractType(this, OldType, NewType);
01372 }
01373 
01374 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
01375   PackedTypes.TypeBecameConcrete(this, AbsTy);
01376 }
01377 
01378 // refineAbstractType - Called when a contained type is found to be more
01379 // concrete - this could potentially change us from an abstract type to a
01380 // concrete type.
01381 //
01382 void StructType::refineAbstractType(const DerivedType *OldType,
01383                                     const Type *NewType) {
01384   StructTypes.RefineAbstractType(this, OldType, NewType);
01385 }
01386 
01387 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
01388   StructTypes.TypeBecameConcrete(this, AbsTy);
01389 }
01390 
01391 // refineAbstractType - Called when a contained type is found to be more
01392 // concrete - this could potentially change us from an abstract type to a
01393 // concrete type.
01394 //
01395 void PointerType::refineAbstractType(const DerivedType *OldType,
01396                                      const Type *NewType) {
01397   PointerTypes.RefineAbstractType(this, OldType, NewType);
01398 }
01399 
01400 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
01401   PointerTypes.TypeBecameConcrete(this, AbsTy);
01402 }
01403 
01404 bool SequentialType::indexValid(const Value *V) const {
01405   const Type *Ty = V->getType();
01406   switch (Ty->getTypeID()) {
01407   case Type::IntTyID:
01408   case Type::UIntTyID:
01409   case Type::LongTyID:
01410   case Type::ULongTyID:
01411     return true;
01412   default:
01413     return false;
01414   }
01415 }
01416 
01417 namespace llvm {
01418 std::ostream &operator<<(std::ostream &OS, const Type *T) {
01419   if (T == 0)
01420     OS << "<null> value!\n";
01421   else
01422     T->print(OS);
01423   return OS;
01424 }
01425 
01426 std::ostream &operator<<(std::ostream &OS, const Type &T) {
01427   T.print(OS);
01428   return OS;
01429 }
01430 }
01431 
01432 /// clearAllTypeMaps - This method frees all internal memory used by the
01433 /// type subsystem, which can be used in environments where this memory is
01434 /// otherwise reported as a leak.
01435 void Type::clearAllTypeMaps() {
01436   std::vector<Type *> DerivedTypes;
01437 
01438   FunctionTypes.clear(DerivedTypes);
01439   PointerTypes.clear(DerivedTypes);
01440   StructTypes.clear(DerivedTypes);
01441   ArrayTypes.clear(DerivedTypes);
01442   PackedTypes.clear(DerivedTypes);
01443 
01444   for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
01445       E = DerivedTypes.end(); I != E; ++I)
01446     (*I)->ContainedTys.clear();
01447   for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
01448       E = DerivedTypes.end(); I != E; ++I)
01449     delete *I;
01450   DerivedTypes.clear();
01451 }
01452 
01453 // vim: sw=2