1 //===-- Type.cpp - Implement the Type class ----------------------*- C++ -*--=//
3 // This file implements the Type class for the VMCore library.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/DerivedTypes.h"
8 #include "llvm/SymbolTable.h"
9 #include "llvm/Constants.h"
10 #include "Support/StringExtras.h"
11 #include "Support/STLExtras.h"
14 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
15 // created and later destroyed, all in an effort to make sure that there is only
16 // a single cannonical version of a type.
18 //#define DEBUG_MERGE_TYPES 1
21 //===----------------------------------------------------------------------===//
22 // Type Class Implementation
23 //===----------------------------------------------------------------------===//
25 static unsigned CurUID = 0;
26 static std::vector<const Type *> UIDMappings;
28 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
29 // for types as they are needed. Because resolution of types must invalidate
30 // all of the abstract type descriptions, we keep them in a seperate map to make
32 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
33 static std::map<const Type*, std::string> AbstractTypeDescriptions;
35 void PATypeHolder::dump() const {
36 std::cerr << "PATypeHolder(" << (void*)this << ")\n";
40 Type::Type(const std::string &name, PrimitiveID id)
41 : Value(Type::TypeTy, Value::TypeVal) {
42 ConcreteTypeDescriptions[this] = name;
44 Abstract = Recursive = false;
45 UID = CurUID++; // Assign types UID's as they are created
46 UIDMappings.push_back(this);
49 void Type::setName(const std::string &Name, SymbolTable *ST) {
50 assert(ST && "Type::setName - Must provide symbol table argument!");
52 if (Name.size()) ST->insert(Name, this);
56 const Type *Type::getUniqueIDType(unsigned UID) {
57 assert(UID < UIDMappings.size() &&
58 "Type::getPrimitiveType: UID out of range!");
59 return UIDMappings[UID];
62 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
64 case VoidTyID : return VoidTy;
65 case BoolTyID : return BoolTy;
66 case UByteTyID : return UByteTy;
67 case SByteTyID : return SByteTy;
68 case UShortTyID: return UShortTy;
69 case ShortTyID : return ShortTy;
70 case UIntTyID : return UIntTy;
71 case IntTyID : return IntTy;
72 case ULongTyID : return ULongTy;
73 case LongTyID : return LongTy;
74 case FloatTyID : return FloatTy;
75 case DoubleTyID: return DoubleTy;
76 case TypeTyID : return TypeTy;
77 case LabelTyID : return LabelTy;
83 // isLosslesslyConvertibleTo - Return true if this type can be converted to
84 // 'Ty' without any reinterpretation of bits. For example, uint to int.
86 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
87 if (this == Ty) return true;
88 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
89 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
91 if (getPrimitiveID() == Ty->getPrimitiveID())
92 return true; // Handles identity cast, and cast of differing pointer types
94 // Now we know that they are two differing primitive or pointer types
95 switch (getPrimitiveID()) {
96 case Type::UByteTyID: return Ty == Type::SByteTy;
97 case Type::SByteTyID: return Ty == Type::UByteTy;
98 case Type::UShortTyID: return Ty == Type::ShortTy;
99 case Type::ShortTyID: return Ty == Type::UShortTy;
100 case Type::UIntTyID: return Ty == Type::IntTy;
101 case Type::IntTyID: return Ty == Type::UIntTy;
102 case Type::ULongTyID:
104 case Type::PointerTyID:
105 return Ty == Type::ULongTy || Ty == Type::LongTy || isa<PointerType>(Ty);
107 return false; // Other types have no identity values
111 // getPrimitiveSize - Return the basic size of this type if it is a primative
112 // type. These are fixed by LLVM and are not target dependent. This will
113 // return zero if the type does not have a size or is not a primitive type.
115 unsigned Type::getPrimitiveSize() const {
116 switch (getPrimitiveID()) {
117 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
118 #include "llvm/Type.def"
124 // getTypeDescription - This is a recursive function that walks a type hierarchy
125 // calculating the description for a type.
127 static std::string getTypeDescription(const Type *Ty,
128 std::vector<const Type *> &TypeStack) {
129 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
130 std::map<const Type*, std::string>::iterator I =
131 AbstractTypeDescriptions.lower_bound(Ty);
132 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
134 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
135 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
139 if (!Ty->isAbstract() && !Ty->isRecursive()) { // Base case for the recursion
140 std::map<const Type*, std::string>::iterator I =
141 ConcreteTypeDescriptions.find(Ty);
142 if (I != ConcreteTypeDescriptions.end()) return I->second;
145 // Check to see if the Type is already on the stack...
146 unsigned Slot = 0, CurSize = TypeStack.size();
147 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
149 // This is another base case for the recursion. In this case, we know
150 // that we have looped back to a type that we have previously visited.
151 // Generate the appropriate upreference to handle this.
154 return "\\" + utostr(CurSize-Slot); // Here's the upreference
156 // Recursive case: derived types...
158 TypeStack.push_back(Ty); // Add us to the stack..
160 switch (Ty->getPrimitiveID()) {
161 case Type::FunctionTyID: {
162 const FunctionType *FTy = cast<FunctionType>(Ty);
163 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
164 for (FunctionType::ParamTypes::const_iterator
165 I = FTy->getParamTypes().begin(),
166 E = FTy->getParamTypes().end(); I != E; ++I) {
167 if (I != FTy->getParamTypes().begin())
169 Result += getTypeDescription(*I, TypeStack);
171 if (FTy->isVarArg()) {
172 if (!FTy->getParamTypes().empty()) Result += ", ";
178 case Type::StructTyID: {
179 const StructType *STy = cast<StructType>(Ty);
181 for (StructType::ElementTypes::const_iterator
182 I = STy->getElementTypes().begin(),
183 E = STy->getElementTypes().end(); I != E; ++I) {
184 if (I != STy->getElementTypes().begin())
186 Result += getTypeDescription(*I, TypeStack);
191 case Type::PointerTyID: {
192 const PointerType *PTy = cast<PointerType>(Ty);
193 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
196 case Type::ArrayTyID: {
197 const ArrayType *ATy = cast<ArrayType>(Ty);
198 unsigned NumElements = ATy->getNumElements();
200 Result += utostr(NumElements) + " x ";
201 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
205 assert(0 && "Unhandled type in getTypeDescription!");
209 TypeStack.pop_back(); // Remove self from stack...
211 // In order to reduce the amount of repeated computation, we cache the computd
213 if (Ty->isAbstract())
214 AbstractTypeDescriptions[Ty] = Result;
216 ConcreteTypeDescriptions[Ty] = Result;
223 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
225 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
226 if (I != Map.end()) return I->second;
228 std::vector<const Type *> TypeStack;
229 getTypeDescription(Ty, TypeStack);
230 assert(Map.count(Ty) && "Type didn't get inserted!!");
235 const std::string &Type::getDescription() const {
237 return getOrCreateDesc(AbstractTypeDescriptions, this);
239 return getOrCreateDesc(ConcreteTypeDescriptions, this);
243 bool StructType::indexValid(const Value *V) const {
244 if (!isa<Constant>(V)) return false;
245 if (V->getType() != Type::UByteTy) return false;
246 unsigned Idx = cast<ConstantUInt>(V)->getValue();
247 return Idx < ETypes.size();
250 // getTypeAtIndex - Given an index value into the type, return the type of the
251 // element. For a structure type, this must be a constant value...
253 const Type *StructType::getTypeAtIndex(const Value *V) const {
254 assert(isa<Constant>(V) && "Structure index must be a constant!!");
255 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
256 unsigned Idx = cast<ConstantUInt>(V)->getValue();
257 assert(Idx < ETypes.size() && "Structure index out of range!");
258 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
264 //===----------------------------------------------------------------------===//
265 // Auxilliary classes
266 //===----------------------------------------------------------------------===//
268 // These classes are used to implement specialized behavior for each different
271 struct SignedIntType : public Type {
272 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
274 // isSigned - Return whether a numeric type is signed.
275 virtual bool isSigned() const { return 1; }
277 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
278 // virtual function invocation.
280 virtual bool isInteger() const { return 1; }
283 struct UnsignedIntType : public Type {
284 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
286 // isUnsigned - Return whether a numeric type is signed.
287 virtual bool isUnsigned() const { return 1; }
289 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
290 // virtual function invocation.
292 virtual bool isInteger() const { return 1; }
295 struct OtherType : public Type {
296 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
299 static struct TypeType : public Type {
300 TypeType() : Type("type", TypeTyID) {}
301 } TheTypeTy; // Implement the type that is global.
304 //===----------------------------------------------------------------------===//
305 // Static 'Type' data
306 //===----------------------------------------------------------------------===//
308 static OtherType TheVoidTy ("void" , Type::VoidTyID);
309 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
310 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
311 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
312 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
313 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
314 static SignedIntType TheIntTy ("int" , Type::IntTyID);
315 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
316 static SignedIntType TheLongTy ("long" , Type::LongTyID);
317 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
318 static OtherType TheFloatTy ("float" , Type::FloatTyID);
319 static OtherType TheDoubleTy("double", Type::DoubleTyID);
320 static OtherType TheLabelTy ("label" , Type::LabelTyID);
322 Type *Type::VoidTy = &TheVoidTy;
323 Type *Type::BoolTy = &TheBoolTy;
324 Type *Type::SByteTy = &TheSByteTy;
325 Type *Type::UByteTy = &TheUByteTy;
326 Type *Type::ShortTy = &TheShortTy;
327 Type *Type::UShortTy = &TheUShortTy;
328 Type *Type::IntTy = &TheIntTy;
329 Type *Type::UIntTy = &TheUIntTy;
330 Type *Type::LongTy = &TheLongTy;
331 Type *Type::ULongTy = &TheULongTy;
332 Type *Type::FloatTy = &TheFloatTy;
333 Type *Type::DoubleTy = &TheDoubleTy;
334 Type *Type::TypeTy = &TheTypeTy;
335 Type *Type::LabelTy = &TheLabelTy;
338 //===----------------------------------------------------------------------===//
339 // Derived Type Constructors
340 //===----------------------------------------------------------------------===//
342 FunctionType::FunctionType(const Type *Result,
343 const std::vector<const Type*> &Params,
344 bool IsVarArgs) : DerivedType(FunctionTyID),
345 ResultType(PATypeHandle(Result, this)),
346 isVarArgs(IsVarArgs) {
347 ParamTys.reserve(Params.size());
348 for (unsigned i = 0; i < Params.size(); ++i)
349 ParamTys.push_back(PATypeHandle(Params[i], this));
351 setDerivedTypeProperties();
354 StructType::StructType(const std::vector<const Type*> &Types)
355 : CompositeType(StructTyID) {
356 ETypes.reserve(Types.size());
357 for (unsigned i = 0; i < Types.size(); ++i) {
358 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
359 ETypes.push_back(PATypeHandle(Types[i], this));
361 setDerivedTypeProperties();
364 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
365 : SequentialType(ArrayTyID, ElType) {
367 setDerivedTypeProperties();
370 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
371 setDerivedTypeProperties();
374 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
377 #ifdef DEBUG_MERGE_TYPES
378 std::cerr << "Derived new type: " << getDescription() << "\n";
385 //===----------------------------------------------------------------------===//
386 // Derived Type setDerivedTypeProperties Function
387 //===----------------------------------------------------------------------===//
389 // getTypeProps - This is a recursive function that walks a type hierarchy
390 // calculating the description for a type and whether or not it is abstract or
391 // recursive. Worst case it will have to do a lot of traversing if you have
392 // some whacko opaque types, but in most cases, it will do some simple stuff
393 // when it hits non-abstract types that aren't recursive.
395 static void getTypeProps(const Type *Ty, std::vector<const Type *> &TypeStack,
396 bool &isAbstract, bool &isRecursive) {
397 if (!Ty->isAbstract() && !Ty->isRecursive()) // Base case for the recursion
398 return; // Primitive = leaf type
400 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
401 isAbstract = true; // This whole type is abstract!
402 return; // Opaque = leaf type
405 // Check to see if the Type is already on the stack...
406 for (unsigned Slot = 0; Slot != TypeStack.size(); ++Slot)
407 if (TypeStack[Slot] == Ty) { // Scan for type
408 isRecursive = true; // We know we are recursive
412 // Recursive case: derived type...
413 TypeStack.push_back(Ty); // Add us to the stack..
415 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
417 getTypeProps(*I, TypeStack, isAbstract, isRecursive);
418 if (isAbstract && isRecursive) break;
421 TypeStack.pop_back(); // Remove self from stack...
425 // setDerivedTypeProperties - This function is used to calculate the
426 // isAbstract, isRecursive, and the Description settings for a type. The
427 // getTypeProps function does all the dirty work.
429 void DerivedType::setDerivedTypeProperties() {
430 std::vector<const Type *> TypeStack;
431 bool isAbstract = false, isRecursive = false;
435 getTypeProps(this, TypeStack, isAbstract, isRecursive);
436 setAbstract(isAbstract);
437 setRecursive(isRecursive);
441 //===----------------------------------------------------------------------===//
442 // Type Structural Equality Testing
443 //===----------------------------------------------------------------------===//
445 // TypesEqual - Two types are considered structurally equal if they have the
446 // same "shape": Every level and element of the types have identical primitive
447 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
448 // be pointer equals to be equivalent though. This uses an optimistic algorithm
449 // that assumes that two graphs are the same until proven otherwise.
451 static bool TypesEqual(const Type *Ty, const Type *Ty2,
452 std::map<const Type *, const Type *> &EqTypes) {
453 if (Ty == Ty2) return true;
454 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
455 if (Ty->isPrimitiveType()) return true;
456 if (isa<OpaqueType>(Ty))
457 return false; // Two nonequal opaque types are never equal
459 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
460 if (It != EqTypes.end())
461 return It->second == Ty2; // Looping back on a type, check for equality
463 // Otherwise, add the mapping to the table to make sure we don't get
464 // recursion on the types...
465 EqTypes.insert(std::make_pair(Ty, Ty2));
467 // Iterate over the types and make sure the the contents are equivalent...
468 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
469 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
470 for (; I != IE && I2 != IE2; ++I, ++I2)
471 if (!TypesEqual(*I, *I2, EqTypes)) return false;
473 // Two really annoying special cases that breaks an otherwise nice simple
474 // algorithm is the fact that arraytypes have sizes that differentiates types,
475 // and that method types can be varargs or not. Consider this now.
476 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
477 if (ATy->getNumElements() != cast<ArrayType>(Ty2)->getNumElements())
479 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
480 if (FTy->isVarArg() != cast<FunctionType>(Ty2)->isVarArg())
484 return I == IE && I2 == IE2; // Types equal if both iterators are done
487 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
488 std::map<const Type *, const Type *> EqTypes;
489 return TypesEqual(Ty, Ty2, EqTypes);
494 //===----------------------------------------------------------------------===//
495 // Derived Type Factory Functions
496 //===----------------------------------------------------------------------===//
498 // TypeMap - Make sure that only one instance of a particular type may be
499 // created on any given run of the compiler... note that this involves updating
500 // our map if an abstract type gets refined somehow...
502 template<class ValType, class TypeClass>
503 class TypeMap : public AbstractTypeUser {
504 typedef std::map<ValType, PATypeHandle> MapTy;
507 ~TypeMap() { print("ON EXIT"); }
509 inline TypeClass *get(const ValType &V) {
510 typename std::map<ValType, PATypeHandle>::iterator I
512 // TODO: FIXME: When Types are not CONST.
513 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
516 inline void add(const ValType &V, TypeClass *T) {
517 Map.insert(std::make_pair(V, PATypeHandle(T, this)));
521 // containsEquivalent - Return true if the typemap contains a type that is
522 // structurally equivalent to the specified type.
524 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
525 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
526 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
527 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
531 // refineAbstractType - This is called when one of the contained abstract
532 // types gets refined... this simply removes the abstract type from our table.
533 // We expect that whoever refined the type will add it back to the table,
536 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
537 #ifdef DEBUG_MERGE_TYPES
538 std::cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
539 << OldTy->getDescription() << " replacement == " << (void*)NewTy
540 << ", " << NewTy->getDescription() << "\n";
542 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
543 if (I->second == OldTy) {
544 // Check to see if the type just became concrete. If so, remove self
546 I->second.removeUserFromConcrete();
547 I->second = cast<TypeClass>(NewTy);
551 void remove(const ValType &OldVal) {
552 typename MapTy::iterator I = Map.find(OldVal);
553 assert(I != Map.end() && "TypeMap::remove, element not found!");
557 void print(const char *Arg) const {
558 #ifdef DEBUG_MERGE_TYPES
559 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
561 for (MapTy::const_iterator I = Map.begin(), E = Map.end(); I != E; ++I)
562 std::cerr << " " << (++i) << ". " << I->second << " "
563 << I->second->getDescription() << "\n";
567 void dump() const { print("dump output"); }
571 // ValTypeBase - This is the base class that is used by the various
572 // instantiations of TypeMap. This class is an AbstractType user that notifies
573 // the underlying TypeMap when it gets modified.
575 template<class ValType, class TypeClass>
576 class ValTypeBase : public AbstractTypeUser {
577 TypeMap<ValType, TypeClass> &MyTable;
579 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
581 // Subclass should override this... to update self as usual
582 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
584 // typeBecameConcrete - This callback occurs when a contained type refines
585 // to itself, but becomes concrete in the process. Our subclass should remove
586 // itself from the ATU list of the specified type.
588 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
590 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
591 assert(OldTy == NewTy || OldTy->isAbstract());
593 if (!OldTy->isAbstract())
594 typeBecameConcrete(OldTy);
596 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
597 ValType Tmp(*(ValType*)this); // Copy this.
598 PATypeHandle OldType(Table.get(*(ValType*)this), this);
599 Table.remove(*(ValType*)this); // Destroy's this!
601 // Refine temporary to new state...
603 Tmp.doRefinement(OldTy, NewTy);
605 // FIXME: when types are not const!
606 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
610 std::cerr << "ValTypeBase instance!\n";
616 //===----------------------------------------------------------------------===//
617 // Function Type Factory and Value Class...
620 // FunctionValType - Define a class to hold the key that goes into the TypeMap
622 class FunctionValType : public ValTypeBase<FunctionValType, FunctionType> {
624 std::vector<PATypeHandle> ArgTypes;
627 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
628 bool IVA, TypeMap<FunctionValType, FunctionType> &Tab)
629 : ValTypeBase<FunctionValType, FunctionType>(Tab), RetTy(ret, this),
631 for (unsigned i = 0; i < args.size(); ++i)
632 ArgTypes.push_back(PATypeHandle(args[i], this));
635 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
636 // this FunctionValType owns them, not the old one!
638 FunctionValType(const FunctionValType &MVT)
639 : ValTypeBase<FunctionValType, FunctionType>(MVT), RetTy(MVT.RetTy, this),
640 isVarArg(MVT.isVarArg) {
641 ArgTypes.reserve(MVT.ArgTypes.size());
642 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
643 ArgTypes.push_back(PATypeHandle(MVT.ArgTypes[i], this));
646 // Subclass should override this... to update self as usual
647 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
648 if (RetTy == OldType) RetTy = NewType;
649 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
650 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
653 virtual void typeBecameConcrete(const DerivedType *Ty) {
654 if (RetTy == Ty) RetTy.removeUserFromConcrete();
656 for (unsigned i = 0; i < ArgTypes.size(); ++i)
657 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
660 inline bool operator<(const FunctionValType &MTV) const {
661 if (RetTy.get() < MTV.RetTy.get()) return true;
662 if (RetTy.get() > MTV.RetTy.get()) return false;
664 if (ArgTypes < MTV.ArgTypes) return true;
665 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
669 // Define the actual map itself now...
670 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
672 // FunctionType::get - The factory function for the FunctionType class...
673 FunctionType *FunctionType::get(const Type *ReturnType,
674 const std::vector<const Type*> &Params,
676 FunctionValType VT(ReturnType, Params, isVarArg, FunctionTypes);
677 FunctionType *MT = FunctionTypes.get(VT);
680 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
682 #ifdef DEBUG_MERGE_TYPES
683 std::cerr << "Derived new type: " << MT << "\n";
688 //===----------------------------------------------------------------------===//
689 // Array Type Factory...
691 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
695 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
696 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
698 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
699 // ArrayValType owns it, not the old one!
701 ArrayValType(const ArrayValType &AVT)
702 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
705 // Subclass should override this... to update self as usual
706 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
707 assert(ValTy == OldType);
711 virtual void typeBecameConcrete(const DerivedType *Ty) {
712 assert(ValTy == Ty &&
713 "Contained type became concrete but we're not using it!");
714 ValTy.removeUserFromConcrete();
717 inline bool operator<(const ArrayValType &MTV) const {
718 if (Size < MTV.Size) return true;
719 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
723 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
725 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
726 assert(ElementType && "Can't get array of null types!");
728 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
729 ArrayType *AT = ArrayTypes.get(AVT);
730 if (AT) return AT; // Found a match, return it!
732 // Value not found. Derive a new type!
733 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
735 #ifdef DEBUG_MERGE_TYPES
736 std::cerr << "Derived new type: " << AT->getDescription() << "\n";
741 //===----------------------------------------------------------------------===//
742 // Struct Type Factory...
745 // StructValType - Define a class to hold the key that goes into the TypeMap
747 class StructValType : public ValTypeBase<StructValType, StructType> {
748 std::vector<PATypeHandle> ElTypes;
750 StructValType(const std::vector<const Type*> &args,
751 TypeMap<StructValType, StructType> &Tab)
752 : ValTypeBase<StructValType, StructType>(Tab) {
753 ElTypes.reserve(args.size());
754 for (unsigned i = 0, e = args.size(); i != e; ++i)
755 ElTypes.push_back(PATypeHandle(args[i], this));
758 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
759 // this StructValType owns them, not the old one!
761 StructValType(const StructValType &SVT)
762 : ValTypeBase<StructValType, StructType>(SVT){
763 ElTypes.reserve(SVT.ElTypes.size());
764 for (unsigned i = 0, e = SVT.ElTypes.size(); i != e; ++i)
765 ElTypes.push_back(PATypeHandle(SVT.ElTypes[i], this));
768 // Subclass should override this... to update self as usual
769 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
770 for (unsigned i = 0; i < ElTypes.size(); ++i)
771 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
774 virtual void typeBecameConcrete(const DerivedType *Ty) {
775 for (unsigned i = 0, e = ElTypes.size(); i != e; ++i)
776 if (ElTypes[i] == Ty)
777 ElTypes[i].removeUserFromConcrete();
780 inline bool operator<(const StructValType &STV) const {
781 return ElTypes < STV.ElTypes;
785 static TypeMap<StructValType, StructType> StructTypes;
787 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
788 StructValType STV(ETypes, StructTypes);
789 StructType *ST = StructTypes.get(STV);
792 // Value not found. Derive a new type!
793 StructTypes.add(STV, ST = new StructType(ETypes));
795 #ifdef DEBUG_MERGE_TYPES
796 std::cerr << "Derived new type: " << ST->getDescription() << "\n";
801 //===----------------------------------------------------------------------===//
802 // Pointer Type Factory...
805 // PointerValType - Define a class to hold the key that goes into the TypeMap
807 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
810 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
811 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
813 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
814 // PointerValType owns it, not the old one!
816 PointerValType(const PointerValType &PVT)
817 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
819 // Subclass should override this... to update self as usual
820 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
821 assert(ValTy == OldType);
825 virtual void typeBecameConcrete(const DerivedType *Ty) {
826 assert(ValTy == Ty &&
827 "Contained type became concrete but we're not using it!");
828 ValTy.removeUserFromConcrete();
831 inline bool operator<(const PointerValType &MTV) const {
832 return ValTy.get() < MTV.ValTy.get();
836 static TypeMap<PointerValType, PointerType> PointerTypes;
838 PointerType *PointerType::get(const Type *ValueType) {
839 assert(ValueType && "Can't get a pointer to <null> type!");
840 PointerValType PVT(ValueType, PointerTypes);
842 PointerType *PT = PointerTypes.get(PVT);
845 // Value not found. Derive a new type!
846 PointerTypes.add(PVT, PT = new PointerType(ValueType));
848 #ifdef DEBUG_MERGE_TYPES
849 std::cerr << "Derived new type: " << PT->getDescription() << "\n";
854 void debug_type_tables() {
855 FunctionTypes.dump();
862 //===----------------------------------------------------------------------===//
863 // Derived Type Refinement Functions
864 //===----------------------------------------------------------------------===//
866 // addAbstractTypeUser - Notify an abstract type that there is a new user of
867 // it. This function is called primarily by the PATypeHandle class.
869 void DerivedType::addAbstractTypeUser(AbstractTypeUser *U) const {
870 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
872 #if DEBUG_MERGE_TYPES
873 std::cerr << " addAbstractTypeUser[" << (void*)this << ", "
874 << getDescription() << "][" << AbstractTypeUsers.size()
875 << "] User = " << U << "\n";
877 AbstractTypeUsers.push_back(U);
881 // removeAbstractTypeUser - Notify an abstract type that a user of the class
882 // no longer has a handle to the type. This function is called primarily by
883 // the PATypeHandle class. When there are no users of the abstract type, it
884 // is anihilated, because there is no way to get a reference to it ever again.
886 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
887 // Search from back to front because we will notify users from back to
888 // front. Also, it is likely that there will be a stack like behavior to
889 // users that register and unregister users.
892 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
893 assert(i != 0 && "AbstractTypeUser not in user list!");
895 --i; // Convert to be in range 0 <= i < size()
896 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
898 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
900 #ifdef DEBUG_MERGE_TYPES
901 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
902 << getDescription() << "][" << i << "] User = " << U << "\n";
905 if (AbstractTypeUsers.empty() && isAbstract()) {
906 #ifdef DEBUG_MERGE_TYPES
907 std::cerr << "DELETEing unused abstract type: <" << getDescription()
908 << ">[" << (void*)this << "]" << "\n";
910 delete this; // No users of this abstract type!
915 // refineAbstractTypeTo - This function is used to when it is discovered that
916 // the 'this' abstract type is actually equivalent to the NewType specified.
917 // This causes all users of 'this' to switch to reference the more concrete
918 // type NewType and for 'this' to be deleted.
920 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
921 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
922 assert(this != NewType && "Can't refine to myself!");
924 // The descriptions may be out of date. Conservatively clear them all!
925 AbstractTypeDescriptions.clear();
927 #ifdef DEBUG_MERGE_TYPES
928 std::cerr << "REFINING abstract type [" << (void*)this << " "
929 << getDescription() << "] to [" << (void*)NewType << " "
930 << NewType->getDescription() << "]!\n";
934 // Make sure to put the type to be refined to into a holder so that if IT gets
935 // refined, that we will not continue using a dead reference...
937 PATypeHolder NewTy(NewType);
939 // Add a self use of the current type so that we don't delete ourself until
940 // after this while loop. We are careful to never invoke refine on ourself,
941 // so this extra reference shouldn't be a problem. Note that we must only
942 // remove a single reference at the end, but we must tolerate multiple self
943 // references because we could be refineAbstractTypeTo'ing recursively on the
946 addAbstractTypeUser(this);
948 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
949 unsigned NumSelfUses = 0;
951 // Iterate over all of the uses of this type, invoking callback. Each user
952 // should remove itself from our use list automatically. We have to check to
953 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
954 // will not cause users to drop off of the use list. If we resolve to ourself
957 while (AbstractTypeUsers.size() > NumSelfUses && NewTy != this) {
958 AbstractTypeUser *User = AbstractTypeUsers.back();
961 // Move self use to the start of the list. Increment NSU.
962 std::swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
964 unsigned OldSize = AbstractTypeUsers.size();
965 #ifdef DEBUG_MERGE_TYPES
966 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
967 << "] of abstract type [" << (void*)this << " "
968 << getDescription() << "] to [" << (void*)NewTy.get() << " "
969 << NewTy->getDescription() << "]!\n";
971 User->refineAbstractType(this, NewTy);
973 #ifdef DEBUG_MERGE_TYPES
974 if (AbstractTypeUsers.size() == OldSize) {
975 User->refineAbstractType(this, NewTy);
976 if (AbstractTypeUsers.back() != User)
977 std::cerr << "User changed!\n";
978 std::cerr << "Top of user list is:\n";
979 AbstractTypeUsers.back()->dump();
981 std::cerr <<"\nOld User=\n";
985 assert(AbstractTypeUsers.size() != OldSize &&
986 "AbsTyUser did not remove self from user list!");
990 // Remove a single self use, even though there may be several here. This will
991 // probably 'delete this', so no instance variables may be used after this
994 assert((NewTy == this || AbstractTypeUsers.back() == this) &&
995 "Only self uses should be left!");
996 removeAbstractTypeUser(this);
999 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
1000 // has been refined a bit. The pointer is still valid and still should be
1001 // used, but the subtypes have changed.
1003 void DerivedType::typeIsRefined() {
1004 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
1005 if (isRefining == 1) return; // Kill recursion here...
1008 #ifdef DEBUG_MERGE_TYPES
1009 std::cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription()
1013 // In this loop we have to be very careful not to get into infinite loops and
1014 // other problem cases. Specifically, we loop through all of the abstract
1015 // type users in the user list, notifying them that the type has been refined.
1016 // At their choice, they may or may not choose to remove themselves from the
1017 // list of users. Regardless of whether they do or not, we have to be sure
1018 // that we only notify each user exactly once. Because the refineAbstractType
1019 // method can cause an arbitrary permutation to the user list, we cannot loop
1020 // through it in any particular order and be guaranteed that we will be
1021 // successful at this aim. Because of this, we keep track of all the users we
1022 // have visited and only visit users we have not seen. Because this user list
1023 // should be small, we use a vector instead of a full featured set to keep
1024 // track of what users we have notified so far.
1026 std::vector<AbstractTypeUser*> Refined;
1029 for (i = AbstractTypeUsers.size(); i != 0; --i)
1030 if (find(Refined.begin(), Refined.end(), AbstractTypeUsers[i-1]) ==
1032 break; // Found an unrefined user?
1034 if (i == 0) break; // Noone to refine left, break out of here!
1036 AbstractTypeUser *ATU = AbstractTypeUsers[--i];
1037 Refined.push_back(ATU); // Keep track of which users we have refined!
1039 #ifdef DEBUG_MERGE_TYPES
1040 std::cerr << " typeIsREFINED user " << i << "[" << ATU
1041 << "] of abstract type [" << (void*)this << " "
1042 << getDescription() << "]\n";
1044 ATU->refineAbstractType(this, this);
1050 if (!(isAbstract() || AbstractTypeUsers.empty()))
1051 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
1052 if (AbstractTypeUsers[i] != this) {
1054 std::cerr << "FOUND FAILURE\nUser: ";
1055 AbstractTypeUsers[i]->dump();
1056 std::cerr << "\nCatch:\n";
1057 AbstractTypeUsers[i]->refineAbstractType(this, this);
1058 assert(0 && "Type became concrete,"
1059 " but it still has abstract type users hanging around!");
1068 // refineAbstractType - Called when a contained type is found to be more
1069 // concrete - this could potentially change us from an abstract type to a
1072 void FunctionType::refineAbstractType(const DerivedType *OldType,
1073 const Type *NewType) {
1074 #ifdef DEBUG_MERGE_TYPES
1075 std::cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
1076 << OldType->getDescription() << "], " << (void*)NewType << " ["
1077 << NewType->getDescription() << "])\n";
1079 // Find the type element we are refining...
1080 if (ResultType == OldType) {
1081 ResultType.removeUserFromConcrete();
1082 ResultType = NewType;
1084 for (unsigned i = 0, e = ParamTys.size(); i != e; ++i)
1085 if (ParamTys[i] == OldType) {
1086 ParamTys[i].removeUserFromConcrete();
1087 ParamTys[i] = NewType;
1090 const FunctionType *MT = FunctionTypes.containsEquivalent(this);
1091 if (MT && MT != this) {
1092 refineAbstractTypeTo(MT); // Different type altogether...
1094 setDerivedTypeProperties(); // Update the name and isAbstract
1095 typeIsRefined(); // Same type, different contents...
1100 // refineAbstractType - Called when a contained type is found to be more
1101 // concrete - this could potentially change us from an abstract type to a
1104 void ArrayType::refineAbstractType(const DerivedType *OldType,
1105 const Type *NewType) {
1106 #ifdef DEBUG_MERGE_TYPES
1107 std::cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
1108 << OldType->getDescription() << "], " << (void*)NewType << " ["
1109 << NewType->getDescription() << "])\n";
1112 assert(getElementType() == OldType);
1113 ElementType.removeUserFromConcrete();
1114 ElementType = NewType;
1116 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
1117 if (AT && AT != this) {
1118 refineAbstractTypeTo(AT); // Different type altogether...
1120 setDerivedTypeProperties(); // Update the name and isAbstract
1121 typeIsRefined(); // Same type, different contents...
1126 // refineAbstractType - Called when a contained type is found to be more
1127 // concrete - this could potentially change us from an abstract type to a
1130 void StructType::refineAbstractType(const DerivedType *OldType,
1131 const Type *NewType) {
1132 #ifdef DEBUG_MERGE_TYPES
1133 std::cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1134 << OldType->getDescription() << "], " << (void*)NewType << " ["
1135 << NewType->getDescription() << "])\n";
1137 for (int i = ETypes.size()-1; i >= 0; --i)
1138 if (ETypes[i] == OldType) {
1139 ETypes[i].removeUserFromConcrete();
1141 // Update old type to new type in the array...
1142 ETypes[i] = NewType;
1145 const StructType *ST = StructTypes.containsEquivalent(this);
1146 if (ST && ST != this) {
1147 refineAbstractTypeTo(ST); // Different type altogether...
1149 setDerivedTypeProperties(); // Update the name and isAbstract
1150 typeIsRefined(); // Same type, different contents...
1154 // refineAbstractType - Called when a contained type is found to be more
1155 // concrete - this could potentially change us from an abstract type to a
1158 void PointerType::refineAbstractType(const DerivedType *OldType,
1159 const Type *NewType) {
1160 #ifdef DEBUG_MERGE_TYPES
1161 std::cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1162 << OldType->getDescription() << "], " << (void*)NewType << " ["
1163 << NewType->getDescription() << "])\n";
1166 assert(ElementType == OldType);
1167 ElementType.removeUserFromConcrete();
1168 ElementType = NewType;
1170 const PointerType *PT = PointerTypes.containsEquivalent(this);
1171 if (PT && PT != this) {
1172 refineAbstractTypeTo(PT); // Different type altogether...
1174 setDerivedTypeProperties(); // Update the name and isAbstract
1175 typeIsRefined(); // Same type, different contents...