[llvm-branch-commits] [llvm-branch] r133420 - in /llvm/branches/type-system-rewrite: docs/ include/llvm-c/ include/llvm-c/Transforms/ include/llvm/ include/llvm/ADT/ include/llvm/Bitcode/ include/llvm/Support/ include/llvm/Transforms/ lib/AsmParser/ lib/Bitcode/Writer/ lib/CodeGen/ lib/ExecutionEngine/Interpreter/ lib/Target/ lib/Target/CBackend/ lib/Target/CppBackend/ lib/Transforms/IPO/ lib/Transforms/Utils/ lib/VMCore/

Chris Lattner sabre at nondot.org
Sun Jun 19 23:45:54 PDT 2011


Author: lattner
Date: Mon Jun 20 01:45:54 2011
New Revision: 133420

URL: http://llvm.org/viewvc/llvm-project?rev=133420&view=rev
Log:
Initial stab at the type system rewrite.  This is far enough along that llvm-as links,
but it still needs substantial work on the linker and bitcode reader.  There are also
two known issues (one in the bc writer's value enumerator, one in the .ll parser) and
no testing at all has been done.  It's getting close though, and progress is good:
 55 files changed, 1291 insertions(+), 3858 deletions(-)
 

Modified:
    llvm/branches/type-system-rewrite/docs/LangRef.html
    llvm/branches/type-system-rewrite/docs/ProgrammersManual.html
    llvm/branches/type-system-rewrite/include/llvm-c/Core.h
    llvm/branches/type-system-rewrite/include/llvm-c/Transforms/IPO.h
    llvm/branches/type-system-rewrite/include/llvm/ADT/StringMap.h
    llvm/branches/type-system-rewrite/include/llvm/AbstractTypeUser.h
    llvm/branches/type-system-rewrite/include/llvm/Bitcode/LLVMBitCodes.h
    llvm/branches/type-system-rewrite/include/llvm/DefaultPasses.h
    llvm/branches/type-system-rewrite/include/llvm/DerivedTypes.h
    llvm/branches/type-system-rewrite/include/llvm/Function.h
    llvm/branches/type-system-rewrite/include/llvm/GlobalValue.h
    llvm/branches/type-system-rewrite/include/llvm/Instructions.h
    llvm/branches/type-system-rewrite/include/llvm/LinkAllPasses.h
    llvm/branches/type-system-rewrite/include/llvm/Module.h
    llvm/branches/type-system-rewrite/include/llvm/Support/PassManagerBuilder.h
    llvm/branches/type-system-rewrite/include/llvm/Transforms/IPO.h
    llvm/branches/type-system-rewrite/include/llvm/Type.h
    llvm/branches/type-system-rewrite/include/llvm/TypeSymbolTable.h
    llvm/branches/type-system-rewrite/include/llvm/Value.h
    llvm/branches/type-system-rewrite/lib/AsmParser/LLLexer.h
    llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.cpp
    llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.h
    llvm/branches/type-system-rewrite/lib/Bitcode/Writer/BitcodeWriter.cpp
    llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.cpp
    llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.h
    llvm/branches/type-system-rewrite/lib/CodeGen/ShadowStackGC.cpp
    llvm/branches/type-system-rewrite/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp
    llvm/branches/type-system-rewrite/lib/Target/CBackend/CBackend.cpp
    llvm/branches/type-system-rewrite/lib/Target/CppBackend/CPPBackend.cpp
    llvm/branches/type-system-rewrite/lib/Target/TargetData.cpp
    llvm/branches/type-system-rewrite/lib/Transforms/IPO/CMakeLists.txt
    llvm/branches/type-system-rewrite/lib/Transforms/IPO/DeadTypeElimination.cpp
    llvm/branches/type-system-rewrite/lib/Transforms/IPO/IPO.cpp
    llvm/branches/type-system-rewrite/lib/Transforms/IPO/MergeFunctions.cpp
    llvm/branches/type-system-rewrite/lib/Transforms/IPO/StripSymbols.cpp
    llvm/branches/type-system-rewrite/lib/Transforms/Utils/CloneModule.cpp
    llvm/branches/type-system-rewrite/lib/Transforms/Utils/LowerInvoke.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/AsmWriter.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/CMakeLists.txt
    llvm/branches/type-system-rewrite/lib/VMCore/ConstantFold.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/Constants.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/ConstantsContext.h
    llvm/branches/type-system-rewrite/lib/VMCore/Core.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/Function.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/InlineAsm.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/Instructions.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.h
    llvm/branches/type-system-rewrite/lib/VMCore/Metadata.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/Module.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/Type.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/TypeSymbolTable.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/TypesContext.h
    llvm/branches/type-system-rewrite/lib/VMCore/Value.cpp
    llvm/branches/type-system-rewrite/lib/VMCore/Verifier.cpp

Modified: llvm/branches/type-system-rewrite/docs/LangRef.html
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/docs/LangRef.html?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/docs/LangRef.html (original)
+++ llvm/branches/type-system-rewrite/docs/LangRef.html Mon Jun 20 01:45:54 2011
@@ -83,7 +83,6 @@
           <li><a href="#t_opaque">Opaque Type</a></li>
         </ol>
       </li>
-      <li><a href="#t_uprefs">Type Up-references</a></li>
     </ol>
   </li>
   <li><a href="#constants">Constants</a>
@@ -2028,55 +2027,6 @@
 
 </div>
 
-<!-- ======================================================================= -->
-<h3>
-  <a name="t_uprefs">Type Up-references</a>
-</h3>
-
-<div>
-
-<h5>Overview:</h5>
-<p>An "up reference" allows you to refer to a lexically enclosing type without
-   requiring it to have a name. For instance, a structure declaration may
-   contain a pointer to any of the types it is lexically a member of.  Example
-   of up references (with their equivalent as named type declarations)
-   include:</p>
-
-<pre>
-   { \2 * }                %x = type { %x* }
-   { \2 }*                 %y = type { %y }*
-   \1*                     %z = type %z*
-</pre>
-
-<p>An up reference is needed by the asmprinter for printing out cyclic types
-   when there is no declared name for a type in the cycle.  Because the
-   asmprinter does not want to print out an infinite type string, it needs a
-   syntax to handle recursive types that have no names (all names are optional
-   in llvm IR).</p>
-
-<h5>Syntax:</h5>
-<pre>
-   \<level>
-</pre>
-
-<p>The level is the count of the lexical type that is being referred to.</p>
-
-<h5>Examples:</h5>
-<table class="layout">
-  <tr class="layout">
-    <td class="left"><tt>\1*</tt></td>
-    <td class="left">Self-referential pointer.</td>
-  </tr>
-  <tr class="layout">
-    <td class="left"><tt>{ { \3*, i8 }, i32 }</tt></td>
-    <td class="left">Recursive structure where the upref refers to the out-most
-                     structure.</td>
-  </tr>
-</table>
-
-</div>
-
-</div>
 
 <!-- *********************************************************************** -->
 <h2><a name="constants">Constants</a></h2>

Modified: llvm/branches/type-system-rewrite/docs/ProgrammersManual.html
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/docs/ProgrammersManual.html?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/docs/ProgrammersManual.html (original)
+++ llvm/branches/type-system-rewrite/docs/ProgrammersManual.html Mon Jun 20 01:45:54 2011
@@ -168,7 +168,7 @@
     <li><a href="#AbstractTypeUser">The AbstractTypeUser Class</a></li>
   </ul></li>
 
-  <li><a href="#SymbolTable">The <tt>ValueSymbolTable</tt> and <tt>TypeSymbolTable</tt> classes</a></li>
+  <li><a href="#SymbolTable">The <tt>ValueSymbolTable</tt> class</a></li>
   <li><a href="#UserLayout">The <tt>User</tt> and owned <tt>Use</tt> classes' memory layout</a></li>
   </ul></li>
 
@@ -2810,8 +2810,7 @@
 
 <!-- ======================================================================= -->
 <h3>
-  <a name="SymbolTable">The <tt>ValueSymbolTable</tt> and
-   <tt>TypeSymbolTable</tt> classes</a>
+  <a name="SymbolTable">The <tt>ValueSymbolTable</tt> class</a>
 </h3>
 
 <div>
@@ -2820,9 +2819,7 @@
 href="#Function"><tt>Function</tt></a> and <a href="#Module">
 <tt>Module</tt></a> classes use for naming value definitions. The symbol table
 can provide a name for any <a href="#Value"><tt>Value</tt></a>. 
-The <tt><a href="http://llvm.org/doxygen/classllvm_1_1TypeSymbolTable.html">
-TypeSymbolTable</a></tt> class is used by the <tt>Module</tt> class to store
-names for types.</p>
+</p>
 
 <p>Note that the <tt>SymbolTable</tt> class should not be directly accessed 
 by most clients.  It should only be used when iteration over the symbol table 
@@ -2832,13 +2829,12 @@
 an empty name) do not exist in the symbol table.
 </p>
 
-<p>These symbol tables support iteration over the values/types in the symbol
+<p>Symbol tables support iteration over the values in the symbol
 table with <tt>begin/end/iterator</tt> and supports querying to see if a
 specific name is in the symbol table (with <tt>lookup</tt>).  The
 <tt>ValueSymbolTable</tt> class exposes no public mutator methods, instead,
 simply call <tt>setName</tt> on a value, which will autoinsert it into the
-appropriate symbol table.  For types, use the Module::addTypeName method to
-insert entries into the symbol table.</p>
+appropriate symbol table.</p>
 
 </div>
 

Modified: llvm/branches/type-system-rewrite/include/llvm-c/Core.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm-c/Core.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm-c/Core.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm-c/Core.h Mon Jun 20 01:45:54 2011
@@ -68,13 +68,6 @@
  */
 typedef struct LLVMOpaqueType *LLVMTypeRef;
 
-/**
- * When building recursive types using LLVMRefineType, LLVMTypeRef values may
- * become invalid; use LLVMTypeHandleRef to resolve this problem. See the
- * llvm::AbstractTypeHolder class.
- */
-typedef struct LLVMOpaqueTypeHandle *LLVMTypeHandleRef;
-
 typedef struct LLVMOpaqueValue *LLVMValueRef;
 typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef;
 typedef struct LLVMOpaqueBuilder *LLVMBuilderRef;
@@ -206,7 +199,6 @@
   LLVMStructTypeKind,      /**< Structures */
   LLVMArrayTypeKind,       /**< Arrays */
   LLVMPointerTypeKind,     /**< Pointers */
-  LLVMOpaqueTypeKind,      /**< Opaque: type with unknown structure */
   LLVMVectorTypeKind,      /**< SIMD 'packed' format, or other vector type */
   LLVMMetadataTypeKind,    /**< Metadata */
   LLVMX86_MMXTypeKind      /**< X86 MMX */
@@ -320,12 +312,6 @@
 const char *LLVMGetTarget(LLVMModuleRef M);
 void LLVMSetTarget(LLVMModuleRef M, const char *Triple);
 
-/** See Module::addTypeName. */
-LLVMBool LLVMAddTypeName(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty);
-void LLVMDeleteTypeName(LLVMModuleRef M, const char *Name);
-LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name);
-const char *LLVMGetTypeName(LLVMModuleRef M, LLVMTypeRef Ty);
-
 /** See Module::dump. */
 void LLVMDumpModule(LLVMModuleRef M);
 
@@ -418,7 +404,6 @@
 /* Operations on other types */
 LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C);
 LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C);
-LLVMTypeRef LLVMOpaqueTypeInContext(LLVMContextRef C);
 LLVMTypeRef LLVMX86MMXTypeInContext(LLVMContextRef C);
 
 LLVMTypeRef LLVMVoidType(void);
@@ -426,13 +411,6 @@
 LLVMTypeRef LLVMOpaqueType(void);
 LLVMTypeRef LLVMX86MMXType(void);
 
-/* Operations on type handles */
-LLVMTypeHandleRef LLVMCreateTypeHandle(LLVMTypeRef PotentiallyAbstractTy);
-void LLVMRefineType(LLVMTypeRef AbstractTy, LLVMTypeRef ConcreteTy);
-LLVMTypeRef LLVMResolveTypeHandle(LLVMTypeHandleRef TypeHandle);
-void LLVMDisposeTypeHandle(LLVMTypeHandleRef TypeHandle);
-
-
 /*===-- Values ------------------------------------------------------------===*/
 
 /* The bulk of LLVM's object model consists of values, which comprise a very
@@ -1117,7 +1095,6 @@
   DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module,             LLVMModuleRef        )
   DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock,         LLVMBasicBlockRef    )
   DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>,        LLVMBuilderRef       )
-  DEFINE_SIMPLE_CONVERSION_FUNCTIONS(PATypeHolder,       LLVMTypeHandleRef    )
   DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MemoryBuffer,       LLVMMemoryBufferRef  )
   DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext,        LLVMContextRef       )
   DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Use,                LLVMUseRef           )

Modified: llvm/branches/type-system-rewrite/include/llvm-c/Transforms/IPO.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm-c/Transforms/IPO.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm-c/Transforms/IPO.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm-c/Transforms/IPO.h Mon Jun 20 01:45:54 2011
@@ -30,9 +30,6 @@
 /** See llvm::createDeadArgEliminationPass function. */
 void LLVMAddDeadArgEliminationPass(LLVMPassManagerRef PM);
 
-/** See llvm::createDeadTypeEliminationPass function. */
-void LLVMAddDeadTypeEliminationPass(LLVMPassManagerRef PM);
-
 /** See llvm::createFunctionAttrsPass function. */
 void LLVMAddFunctionAttrsPass(LLVMPassManagerRef PM);
 

Modified: llvm/branches/type-system-rewrite/include/llvm/ADT/StringMap.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/ADT/StringMap.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/ADT/StringMap.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/ADT/StringMap.h Mon Jun 20 01:45:54 2011
@@ -307,7 +307,7 @@
     return ValueTy();
   }
 
-  ValueTy& operator[](StringRef Key) {
+  ValueTy &operator[](StringRef Key) {
     return GetOrCreateValue(Key).getValue();
   }
 

Modified: llvm/branches/type-system-rewrite/include/llvm/AbstractTypeUser.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/AbstractTypeUser.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/AbstractTypeUser.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/AbstractTypeUser.h Mon Jun 20 01:45:54 2011
@@ -11,6 +11,11 @@
 //
 //===----------------------------------------------------------------------===//
 
+
+#error REMOVE ME!
+
+
+
 #ifndef LLVM_ABSTRACT_TYPE_USER_H
 #define LLVM_ABSTRACT_TYPE_USER_H
 

Modified: llvm/branches/type-system-rewrite/include/llvm/Bitcode/LLVMBitCodes.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Bitcode/LLVMBitCodes.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Bitcode/LLVMBitCodes.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Bitcode/LLVMBitCodes.h Mon Jun 20 01:45:54 2011
@@ -29,13 +29,23 @@
 
     // Module sub-block id's.
     PARAMATTR_BLOCK_ID,
-    TYPE_BLOCK_ID,
+    
+    /// TYPE_BLOCK_ID_OLD - This is the type descriptor block in LLVM 2.9 and
+    /// earlier, replaced with TYPE_BLOCK_ID2.  FIXME: Remove in LLVM 3.1.
+    TYPE_BLOCK_ID_OLD,
+    
     CONSTANTS_BLOCK_ID,
     FUNCTION_BLOCK_ID,
-    TYPE_SYMTAB_BLOCK_ID,
+    
+    /// TYPE_SYMTAB_BLOCK_ID_OLD - This type descriptor is from LLVM 2.9 and
+    /// earlier bitcode files.  FIXME: Remove in LLVM 3.1
+    TYPE_SYMTAB_BLOCK_ID_OLD,
+    
     VALUE_SYMTAB_BLOCK_ID,
     METADATA_BLOCK_ID,
-    METADATA_ATTACHMENT_ID
+    METADATA_ATTACHMENT_ID,
+    
+    TYPE_BLOCK_ID_NEW
   };
 
 
@@ -72,31 +82,38 @@
 
   /// TYPE blocks have codes for each type primitive they use.
   enum TypeCodes {
-    TYPE_CODE_NUMENTRY =  1,   // NUMENTRY: [numentries]
+    TYPE_CODE_NUMENTRY =  1,    // NUMENTRY: [numentries]
 
     // Type Codes
-    TYPE_CODE_VOID     =  2,   // VOID
-    TYPE_CODE_FLOAT    =  3,   // FLOAT
-    TYPE_CODE_DOUBLE   =  4,   // DOUBLE
-    TYPE_CODE_LABEL    =  5,   // LABEL
-    TYPE_CODE_OPAQUE   =  6,   // OPAQUE
-    TYPE_CODE_INTEGER  =  7,   // INTEGER: [width]
-    TYPE_CODE_POINTER  =  8,   // POINTER: [pointee type]
-    TYPE_CODE_FUNCTION =  9,   // FUNCTION: [vararg, retty, paramty x N]
-    TYPE_CODE_STRUCT   = 10,   // STRUCT: [ispacked, eltty x N]
-    TYPE_CODE_ARRAY    = 11,   // ARRAY: [numelts, eltty]
-    TYPE_CODE_VECTOR   = 12,   // VECTOR: [numelts, eltty]
+    TYPE_CODE_VOID     =  2,    // VOID
+    TYPE_CODE_FLOAT    =  3,    // FLOAT
+    TYPE_CODE_DOUBLE   =  4,    // DOUBLE
+    TYPE_CODE_LABEL    =  5,    // LABEL
+    TYPE_CODE_OPAQUE   =  6,    // OPAQUE
+    TYPE_CODE_INTEGER  =  7,    // INTEGER: [width]
+    TYPE_CODE_POINTER  =  8,    // POINTER: [pointee type]
+    TYPE_CODE_FUNCTION =  9,    // FUNCTION: [vararg, retty, paramty x N]
+    
+    // FIXME: This is the encoding used for structs in LLVM 2.9 and earlier.
+    // REMOVE this in LLVM 3.1
+    TYPE_CODE_STRUCT_OLD = 10,  // STRUCT: [ispacked, eltty x N]
+    TYPE_CODE_ARRAY    = 11,    // ARRAY: [numelts, eltty]
+    TYPE_CODE_VECTOR   = 12,    // VECTOR: [numelts, eltty]
 
     // These are not with the other floating point types because they're
     // a late addition, and putting them in the right place breaks
     // binary compatibility.
-    TYPE_CODE_X86_FP80 = 13,   // X86 LONG DOUBLE
-    TYPE_CODE_FP128    = 14,   // LONG DOUBLE (112 bit mantissa)
-    TYPE_CODE_PPC_FP128= 15,   // PPC LONG DOUBLE (2 doubles)
-
-    TYPE_CODE_METADATA = 16,   // METADATA
-
-    TYPE_CODE_X86_MMX = 17     // X86 MMX
+    TYPE_CODE_X86_FP80 = 13,    // X86 LONG DOUBLE
+    TYPE_CODE_FP128    = 14,    // LONG DOUBLE (112 bit mantissa)
+    TYPE_CODE_PPC_FP128= 15,    // PPC LONG DOUBLE (2 doubles)
+
+    TYPE_CODE_METADATA = 16,    // METADATA
+
+    TYPE_CODE_X86_MMX = 17,     // X86 MMX
+    
+    TYPE_CODE_STRUCT_ANON = 18, // STRUCT_ANON: [ispacked, eltty x N]
+    TYPE_CODE_STRUCT_NAME = 19, // STRUCT_NAME: [strchr x N]
+    TYPE_CODE_STRUCT_NAMED = 20 // STRUCT_NAMED: [ispacked, eltty x N]
   };
 
   // The type symbol table only has one code (TST_ENTRY_CODE).

Modified: llvm/branches/type-system-rewrite/include/llvm/DefaultPasses.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/DefaultPasses.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/DefaultPasses.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/DefaultPasses.h Mon Jun 20 01:45:54 2011
@@ -29,7 +29,6 @@
 extern unsigned char CorrelatedValuePropagationID;
 extern unsigned char DeadArgEliminationID;
 extern unsigned char DeadStoreEliminationID;
-extern unsigned char DeadTypeEliminationID;
 extern unsigned char EarlyCSEID;
 extern unsigned char FunctionAttrsID;
 extern unsigned char FunctionInliningID;

Modified: llvm/branches/type-system-rewrite/include/llvm/DerivedTypes.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/DerivedTypes.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/DerivedTypes.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/DerivedTypes.h Mon Jun 20 01:45:54 2011
@@ -24,51 +24,16 @@
 namespace llvm {
 
 class Value;
-template<class ValType, class TypeClass> class TypeMap;
-class FunctionValType;
-class ArrayValType;
-class StructValType;
-class PointerValType;
-class VectorValType;
-class IntegerValType;
 class APInt;
 class LLVMContext;
 template<typename T> class ArrayRef;
+class StringRef;
 
 class DerivedType : public Type {
-  friend class Type;
-
 protected:
   explicit DerivedType(LLVMContext &C, TypeID id) : Type(C, id) {}
-
-  /// notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type
-  /// that the current type has transitioned from being abstract to being
-  /// concrete.
-  ///
-  void notifyUsesThatTypeBecameConcrete();
-
-  /// dropAllTypeUses - When this (abstract) type is resolved to be equal to
-  /// another (more concrete) type, we must eliminate all references to other
-  /// types, to avoid some circular reference problems.
-  ///
-  void dropAllTypeUses();
-
 public:
 
-  //===--------------------------------------------------------------------===//
-  // Abstract Type handling methods - These types have special lifetimes, which
-  // are managed by (add|remove)AbstractTypeUser. See comments in
-  // AbstractTypeUser.h for more information.
-
-  /// refineAbstractTypeTo - This function is used to when it is discovered that
-  /// the 'this' abstract type is actually equivalent to the NewType specified.
-  /// This causes all users of 'this' to switch to reference the more concrete
-  /// type NewType and for 'this' to be deleted.
-  ///
-  void refineAbstractTypeTo(const Type *NewType);
-
-  void dump() const { Type::dump(); }
-
   // Methods for support type inquiry through isa, cast, and dyn_cast.
   static inline bool classof(const DerivedType *) { return true; }
   static inline bool classof(const Type *T) {
@@ -88,7 +53,6 @@
       DerivedType(C, IntegerTyID) {
     setSubclassData(NumBits);
   }
-  friend class TypeMap<IntegerValType, IntegerType>;
 public:
   /// This enum is just used to hold constants we need for IntegerType.
   enum {
@@ -103,7 +67,7 @@
   /// that instance will be returned. Otherwise a new one will be created. Only
   /// one instance with a given NumBits value is ever created.
   /// @brief Get or create an IntegerType instance.
-  static const IntegerType *get(LLVMContext &C, unsigned NumBits);
+  static IntegerType *get(LLVMContext &C, unsigned NumBits);
 
   /// @brief Get the number of bits in this IntegerType
   unsigned getBitWidth() const { return getSubclassData(); }
@@ -143,7 +107,6 @@
 /// FunctionType - Class to represent function types
 ///
 class FunctionType : public DerivedType {
-  friend class TypeMap<FunctionValType, FunctionType>;
   FunctionType(const FunctionType &);                   // Do not implement
   const FunctionType &operator=(const FunctionType &);  // Do not implement
   FunctionType(const Type *Result, ArrayRef<const Type*> Params,
@@ -169,24 +132,20 @@
   static bool isValidArgumentType(const Type *ArgTy);
 
   bool isVarArg() const { return getSubclassData(); }
-  const Type *getReturnType() const { return ContainedTys[0]; }
+  Type *getReturnType() const { return ContainedTys[0]; }
 
   typedef Type::subtype_iterator param_iterator;
   param_iterator param_begin() const { return ContainedTys + 1; }
   param_iterator param_end() const { return &ContainedTys[NumContainedTys]; }
 
   // Parameter type accessors.
-  const Type *getParamType(unsigned i) const { return ContainedTys[i+1]; }
+  Type *getParamType(unsigned i) const { return ContainedTys[i+1]; }
 
   /// getNumParams - Return the number of fixed parameters this function type
   /// requires.  This does not consider varargs.
   ///
   unsigned getNumParams() const { return NumContainedTys - 1; }
 
-  // Implement the AbstractTypeUser interface.
-  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
-  virtual void typeBecameConcrete(const DerivedType *AbsTy);
-
   // Methods for support type inquiry through isa, cast, and dyn_cast.
   static inline bool classof(const FunctionType *) { return true; }
   static inline bool classof(const Type *T) {
@@ -205,8 +164,8 @@
   /// getTypeAtIndex - Given an index value into the type, return the type of
   /// the element.
   ///
-  const Type *getTypeAtIndex(const Value *V) const;
-  const Type *getTypeAtIndex(unsigned Idx) const;
+  Type *getTypeAtIndex(const Value *V) const;
+  Type *getTypeAtIndex(unsigned Idx) const;
   bool indexValid(const Value *V) const;
   bool indexValid(unsigned Idx) const;
 
@@ -222,18 +181,48 @@
 
 
 /// StructType - Class to represent struct types, both normal and packed.
+/// Besides being optionally packed, structs can be either "anonymous" or may
+/// have an identity.  Anonymous structs are uniqued by structural equivalence,
+/// but types are each unique when created, and optionally have a name.
 ///
 class StructType : public CompositeType {
-  friend class TypeMap<StructValType, StructType>;
   StructType(const StructType &);                   // Do not implement
   const StructType &operator=(const StructType &);  // Do not implement
-  StructType(LLVMContext &C, ArrayRef<const Type*> Types, bool isPacked);
+  StructType(LLVMContext &C)
+    : CompositeType(C, StructTyID), SymbolTableEntry(0) {}
+  enum {
+    // This is the contents of the SubClassData field.
+    SCDB_HasBody = 1,
+    SCDB_Packed = 2,
+    SCDB_IsAnonymous = 4
+  };
+  
+  /// SymbolTableEntry - For a named struct that actually has a name, this is a
+  /// pointer to the symbol table entry (maintained by LLVMContext) for the
+  /// struct.  This is null if the type is an anonymous struct or if it is
+  /// 
+  void *SymbolTableEntry;
 public:
+  /// StructType::createNamed - This creates a named struct with no body
+  /// specified.  If the name is empty, it creates an unnamed struct, which has
+  /// a unique identity but no actual name.
+  static StructType *createNamed(LLVMContext &Context, StringRef Name);
+  
+  static StructType *createNamed(StringRef Name, ArrayRef<Type*> Elements,
+                                 bool isPacked = false);
+  static StructType *createNamed(LLVMContext &Context, StringRef Name,
+                                 ArrayRef<Type*> Elements,
+                                 bool isPacked = false);
+
   /// StructType::get - This static method is the primary way to create a
   /// StructType.
   ///
+  /// FIXME: Remove the 'const Type*' version of this when types are pervasively
+  /// de-constified.
   static StructType *get(LLVMContext &Context, ArrayRef<const Type*> Elements,
                          bool isPacked = false);
+  static StructType *get(LLVMContext &Context, ArrayRef<Type*> Elements,
+                         bool isPacked = false);
 
   /// StructType::get - Create an empty structure type.
   ///
@@ -245,11 +234,36 @@
   /// element type.
   static StructType *get(const Type *elt1, ...) END_WITH_NULL;
 
+  bool isPacked() const { return (getSubclassData() & SCDB_Packed) != 0; }
+  
+  /// isAnonymous - Return true if this type is uniqued by structural
+  /// equivalence, false if it has an identity.
+  bool isAnonymous() const {return (getSubclassData() & SCDB_IsAnonymous) != 0;}
+  
+  /// isOpaque - Return true if this is a type with an identity that has no body
+  /// specified yet.  These prints as 'opaque' in .ll files.
+  bool isOpaque() const { return (getSubclassData() & SCDB_HasBody) == 0; }
+  
+  /// hasName - Return true if this is a named struct that has a non-empty name.
+  bool hasName() const { return SymbolTableEntry != 0; }
+  
+  /// getName - Return the name for this struct type if it has an identity.
+  /// This may return an empty string for an unnamed struct type.  Do not call
+  /// this on an anonymous type.
+  StringRef getName() const;
+  
+  /// setName - Change the name of this type to the specified name, or to a name
+  /// with a suffix if there is a collision.  Do not call this on an anonymous
+  /// type.
+  void setName(StringRef Name);
+
+  /// setBody - Specify a body for an opaque type.
+  void setBody(ArrayRef<Type*> Elements, bool isPacked = false);
+  
   /// isValidElementType - Return true if the specified type is valid as a
   /// element type.
   static bool isValidElementType(const Type *ElemTy);
-
-  bool isPacked() const { return getSubclassData() != 0 ? true : false; }
+  
 
   // Iterator access to the elements.
   typedef Type::subtype_iterator element_iterator;
@@ -258,22 +272,15 @@
 
   /// isLayoutIdentical - Return true if this is layout identical to the
   /// specified struct.
-  bool isLayoutIdentical(const StructType *Other) const {
-    return this == Other;
-  }
-  
+  bool isLayoutIdentical(const StructType *Other) const;  
   
   // Random access to the elements
   unsigned getNumElements() const { return NumContainedTys; }
-  const Type *getElementType(unsigned N) const {
+  Type *getElementType(unsigned N) const {
     assert(N < NumContainedTys && "Element number out of range!");
     return ContainedTys[N];
   }
 
-  // Implement the AbstractTypeUser interface.
-  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
-  virtual void typeBecameConcrete(const DerivedType *AbsTy);
-
   // Methods for support type inquiry through isa, cast, and dyn_cast.
   static inline bool classof(const StructType *) { return true; }
   static inline bool classof(const Type *T) {
@@ -290,21 +297,19 @@
 /// components out in memory identically.
 ///
 class SequentialType : public CompositeType {
-  PATypeHandle ContainedType;       ///< Storage for the single contained type.
+  Type *ContainedType;               ///< Storage for the single contained type.
   SequentialType(const SequentialType &);                  // Do not implement!
   const SequentialType &operator=(const SequentialType &); // Do not implement!
 
-  // avoiding warning: 'this' : used in base member initializer list
-  SequentialType *this_() { return this; }
 protected:
-  SequentialType(TypeID TID, const Type *ElType)
-    : CompositeType(ElType->getContext(), TID), ContainedType(ElType, this_()) {
+  SequentialType(TypeID TID, Type *ElType)
+    : CompositeType(ElType->getContext(), TID), ContainedType(ElType) {
     ContainedTys = &ContainedType;
     NumContainedTys = 1;
   }
 
 public:
-  const Type *getElementType() const { return ContainedTys[0]; }
+  Type *getElementType() const { return ContainedTys[0]; }
 
   // Methods for support type inquiry through isa, cast, and dyn_cast.
   static inline bool classof(const SequentialType *) { return true; }
@@ -319,12 +324,11 @@
 /// ArrayType - Class to represent array types.
 ///
 class ArrayType : public SequentialType {
-  friend class TypeMap<ArrayValType, ArrayType>;
   uint64_t NumElements;
 
   ArrayType(const ArrayType &);                   // Do not implement
   const ArrayType &operator=(const ArrayType &);  // Do not implement
-  ArrayType(const Type *ElType, uint64_t NumEl);
+  ArrayType(Type *ElType, uint64_t NumEl);
 public:
   /// ArrayType::get - This static method is the primary way to construct an
   /// ArrayType
@@ -337,10 +341,6 @@
 
   uint64_t getNumElements() const { return NumElements; }
 
-  // Implement the AbstractTypeUser interface.
-  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
-  virtual void typeBecameConcrete(const DerivedType *AbsTy);
-
   // Methods for support type inquiry through isa, cast, and dyn_cast.
   static inline bool classof(const ArrayType *) { return true; }
   static inline bool classof(const Type *T) {
@@ -351,12 +351,11 @@
 /// VectorType - Class to represent vector types.
 ///
 class VectorType : public SequentialType {
-  friend class TypeMap<VectorValType, VectorType>;
   unsigned NumElements;
 
   VectorType(const VectorType &);                   // Do not implement
   const VectorType &operator=(const VectorType &);  // Do not implement
-  VectorType(const Type *ElType, unsigned NumEl);
+  VectorType(Type *ElType, unsigned NumEl);
 public:
   /// VectorType::get - This static method is the primary way to construct an
   /// VectorType.
@@ -369,7 +368,7 @@
   ///
   static VectorType *getInteger(const VectorType *VTy) {
     unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
-    const Type *EltTy = IntegerType::get(VTy->getContext(), EltBits);
+    Type *EltTy = IntegerType::get(VTy->getContext(), EltBits);
     return VectorType::get(EltTy, VTy->getNumElements());
   }
 
@@ -379,7 +378,7 @@
   ///
   static VectorType *getExtendedElementVectorType(const VectorType *VTy) {
     unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
-    const Type *EltTy = IntegerType::get(VTy->getContext(), EltBits * 2);
+    Type *EltTy = IntegerType::get(VTy->getContext(), EltBits * 2);
     return VectorType::get(EltTy, VTy->getNumElements());
   }
 
@@ -391,7 +390,7 @@
     unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
     assert((EltBits & 1) == 0 &&
            "Cannot truncate vector element with odd bit-width");
-    const Type *EltTy = IntegerType::get(VTy->getContext(), EltBits / 2);
+    Type *EltTy = IntegerType::get(VTy->getContext(), EltBits / 2);
     return VectorType::get(EltTy, VTy->getNumElements());
   }
 
@@ -407,10 +406,6 @@
     return NumElements * getElementType()->getPrimitiveSizeInBits();
   }
 
-  // Implement the AbstractTypeUser interface.
-  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
-  virtual void typeBecameConcrete(const DerivedType *AbsTy);
-
   // Methods for support type inquiry through isa, cast, and dyn_cast.
   static inline bool classof(const VectorType *) { return true; }
   static inline bool classof(const Type *T) {
@@ -422,11 +417,9 @@
 /// PointerType - Class to represent pointers.
 ///
 class PointerType : public SequentialType {
-  friend class TypeMap<PointerValType, PointerType>;
-
   PointerType(const PointerType &);                   // Do not implement
   const PointerType &operator=(const PointerType &);  // Do not implement
-  explicit PointerType(const Type *ElType, unsigned AddrSpace);
+  explicit PointerType(Type *ElType, unsigned AddrSpace);
 public:
   /// PointerType::get - This constructs a pointer to an object of the specified
   /// type in a numbered address space.
@@ -445,10 +438,6 @@
   /// @brief Return the address space of the Pointer type.
   inline unsigned getAddressSpace() const { return getSubclassData(); }
 
-  // Implement the AbstractTypeUser interface.
-  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
-  virtual void typeBecameConcrete(const DerivedType *AbsTy);
-
   // Implement support type inquiry through isa, cast, and dyn_cast.
   static inline bool classof(const PointerType *) { return true; }
   static inline bool classof(const Type *T) {
@@ -456,26 +445,6 @@
   }
 };
 
-
-/// OpaqueType - Class to represent opaque types.
-///
-class OpaqueType : public DerivedType {
-  friend class LLVMContextImpl;
-  OpaqueType(const OpaqueType &);                   // DO NOT IMPLEMENT
-  const OpaqueType &operator=(const OpaqueType &);  // DO NOT IMPLEMENT
-  OpaqueType(LLVMContext &C);
-public:
-  /// OpaqueType::get - Static factory method for the OpaqueType class.
-  ///
-  static OpaqueType *get(LLVMContext &C);
-
-  // Implement support for type inquiry through isa, cast, and dyn_cast.
-  static inline bool classof(const OpaqueType *) { return true; }
-  static inline bool classof(const Type *T) {
-    return T->getTypeID() == OpaqueTyID;
-  }
-};
-
 } // End llvm namespace
 
 #endif

Modified: llvm/branches/type-system-rewrite/include/llvm/Function.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Function.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Function.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Function.h Mon Jun 20 01:45:54 2011
@@ -128,8 +128,8 @@
 
   ~Function();
 
-  const Type *getReturnType() const;           // Return the type of the ret val
-  const FunctionType *getFunctionType() const; // Return the FunctionType for me
+  Type *getReturnType() const;           // Return the type of the ret val
+  FunctionType *getFunctionType() const; // Return the FunctionType for me
 
   /// getContext - Return a pointer to the LLVMContext associated with this 
   /// function, or NULL if this function is not bound to a context yet.

Modified: llvm/branches/type-system-rewrite/include/llvm/GlobalValue.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/GlobalValue.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/GlobalValue.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/GlobalValue.h Mon Jun 20 01:45:54 2011
@@ -106,8 +106,8 @@
   bool use_empty_except_constants();
 
   /// getType - Global values are always pointers.
-  inline const PointerType *getType() const {
-    return reinterpret_cast<const PointerType*>(User::getType());
+  inline PointerType *getType() const {
+    return reinterpret_cast<PointerType*>(User::getType());
   }
 
   static LinkageTypes getLinkOnceLinkage(bool ODR) {

Modified: llvm/branches/type-system-rewrite/include/llvm/Instructions.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Instructions.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Instructions.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Instructions.h Mon Jun 20 01:45:54 2011
@@ -76,7 +76,7 @@
   /// getAllocatedType - Return the type that is being allocated by the
   /// instruction.
   ///
-  const Type *getAllocatedType() const;
+  Type *getAllocatedType() const;
 
   /// getAlignment - Return the alignment of the memory that is being allocated
   /// by the instruction.
@@ -271,10 +271,10 @@
 //                             GetElementPtrInst Class
 //===----------------------------------------------------------------------===//
 
-// checkType - Simple wrapper function to give a better assertion failure
+// checkGEPType - Simple wrapper function to give a better assertion failure
 // message on bad indexes for a gep instruction.
 //
-static inline const Type *checkType(const Type *Ty) {
+static inline const Type *checkGEPType(const Type *Ty) {
   assert(Ty && "Invalid GetElementPtrInst indices for type!");
   return Ty;
 }
@@ -315,13 +315,13 @@
   /// pointer type.
   ///
   template<typename RandomAccessIterator>
-  static const Type *getIndexedType(const Type *Ptr,
-                                    RandomAccessIterator IdxBegin,
-                                    RandomAccessIterator IdxEnd,
-                                    // This argument ensures that we
-                                    // have an iterator we can do
-                                    // arithmetic on in constant time
-                                    std::random_access_iterator_tag) {
+  static Type *getIndexedType(const Type *Ptr,
+                              RandomAccessIterator IdxBegin,
+                              RandomAccessIterator IdxEnd,
+                              // This argument ensures that we
+                              // have an iterator we can do
+                              // arithmetic on in constant time
+                              std::random_access_iterator_tag) {
     unsigned NumIdx = static_cast<unsigned>(std::distance(IdxBegin, IdxEnd));
 
     if (NumIdx > 0)
@@ -446,24 +446,22 @@
   /// pointer type.
   ///
   template<typename RandomAccessIterator>
-  static const Type *getIndexedType(const Type *Ptr,
-                                    RandomAccessIterator IdxBegin,
-                                    RandomAccessIterator IdxEnd) {
+  static Type *getIndexedType(const Type *Ptr, RandomAccessIterator IdxBegin,
+                              RandomAccessIterator IdxEnd) {
     return getIndexedType(Ptr, IdxBegin, IdxEnd,
                           typename std::iterator_traits<RandomAccessIterator>::
                           iterator_category());
   }
 
-  static const Type *getIndexedType(const Type *Ptr,
-                                    Value* const *Idx, unsigned NumIdx);
-
-  static const Type *getIndexedType(const Type *Ptr,
-                                    Constant* const *Idx, unsigned NumIdx);
-
-  static const Type *getIndexedType(const Type *Ptr,
-                                    uint64_t const *Idx, unsigned NumIdx);
-
-  static const Type *getIndexedType(const Type *Ptr, Value *Idx);
+  // FIXME: Use ArrayRef
+  static Type *getIndexedType(const Type *Ptr,
+                              Value* const *Idx, unsigned NumIdx);
+  static Type *getIndexedType(const Type *Ptr,
+                              Constant* const *Idx, unsigned NumIdx);
+
+  static Type *getIndexedType(const Type *Ptr,
+                              uint64_t const *Idx, unsigned NumIdx);
+  static Type *getIndexedType(const Type *Ptr, Value *Idx);
 
   inline op_iterator       idx_begin()       { return op_begin()+1; }
   inline const_op_iterator idx_begin() const { return op_begin()+1; }
@@ -538,7 +536,7 @@
                                      unsigned Values,
                                      const Twine &NameStr,
                                      Instruction *InsertBefore)
-  : Instruction(PointerType::get(checkType(
+  : Instruction(PointerType::get(checkGEPType(
                                    getIndexedType(Ptr->getType(),
                                                   IdxBegin, IdxEnd)),
                                  cast<PointerType>(Ptr->getType())
@@ -557,7 +555,7 @@
                                      unsigned Values,
                                      const Twine &NameStr,
                                      BasicBlock *InsertAtEnd)
-  : Instruction(PointerType::get(checkType(
+  : Instruction(PointerType::get(checkGEPType(
                                    getIndexedType(Ptr->getType(),
                                                   IdxBegin, IdxEnd)),
                                  cast<PointerType>(Ptr->getType())
@@ -1459,17 +1457,18 @@
   ///
   /// Null is returned if the indices are invalid for the specified type.
   ///
-  static const Type *getIndexedType(const Type *Agg,
-                                    const unsigned *Idx, unsigned NumIdx);
+  /// FIXME: Use ArrayRef
+  static Type *getIndexedType(const Type *Agg,
+                              const unsigned *Idx, unsigned NumIdx);
 
   template<typename RandomAccessIterator>
-  static const Type *getIndexedType(const Type *Ptr,
-                                    RandomAccessIterator IdxBegin,
-                                    RandomAccessIterator IdxEnd,
-                                    // This argument ensures that we
-                                    // have an iterator we can do
-                                    // arithmetic on in constant time
-                                    std::random_access_iterator_tag) {
+  static Type *getIndexedType(const Type *Ptr,
+                              RandomAccessIterator IdxBegin,
+                              RandomAccessIterator IdxEnd,
+                              // This argument ensures that we
+                              // have an iterator we can do
+                              // arithmetic on in constant time
+                              std::random_access_iterator_tag) {
     unsigned NumIdx = static_cast<unsigned>(std::distance(IdxBegin, IdxEnd));
 
     if (NumIdx > 0)
@@ -1542,15 +1541,16 @@
   ///
   /// Null is returned if the indices are invalid for the specified type.
   ///
+  /// FIXME: Remove the templates and just use ArrayRef.
   template<typename RandomAccessIterator>
-  static const Type *getIndexedType(const Type *Ptr,
-                                    RandomAccessIterator IdxBegin,
-                                    RandomAccessIterator IdxEnd) {
+  static Type *getIndexedType(const Type *Ptr,
+                              RandomAccessIterator IdxBegin,
+                              RandomAccessIterator IdxEnd) {
     return getIndexedType(Ptr, IdxBegin, IdxEnd,
                           typename std::iterator_traits<RandomAccessIterator>::
                           iterator_category());
   }
-  static const Type *getIndexedType(const Type *Ptr, unsigned Idx);
+  static Type *getIndexedType(const Type *Ptr, unsigned Idx);
 
   typedef const unsigned* idx_iterator;
   inline idx_iterator idx_begin() const { return Indices.begin(); }
@@ -1590,8 +1590,8 @@
                                    RandomAccessIterator IdxEnd,
                                    const Twine &NameStr,
                                    Instruction *InsertBefore)
-  : UnaryInstruction(checkType(getIndexedType(Agg->getType(),
-                                              IdxBegin, IdxEnd)),
+  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(),
+                                                 IdxBegin, IdxEnd)),
                      ExtractValue, Agg, InsertBefore) {
   init(IdxBegin, IdxEnd, NameStr,
        typename std::iterator_traits<RandomAccessIterator>
@@ -1603,8 +1603,8 @@
                                    RandomAccessIterator IdxEnd,
                                    const Twine &NameStr,
                                    BasicBlock *InsertAtEnd)
-  : UnaryInstruction(checkType(getIndexedType(Agg->getType(),
-                                              IdxBegin, IdxEnd)),
+  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(),
+                                                 IdxBegin, IdxEnd)),
                      ExtractValue, Agg, InsertAtEnd) {
   init(IdxBegin, IdxEnd, NameStr,
        typename std::iterator_traits<RandomAccessIterator>

Modified: llvm/branches/type-system-rewrite/include/llvm/LinkAllPasses.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/LinkAllPasses.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/LinkAllPasses.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/LinkAllPasses.h Mon Jun 20 01:45:54 2011
@@ -62,7 +62,6 @@
       (void) llvm::createDeadCodeEliminationPass();
       (void) llvm::createDeadInstEliminationPass();
       (void) llvm::createDeadStoreEliminationPass();
-      (void) llvm::createDeadTypeEliminationPass();
       (void) llvm::createDomOnlyPrinterPass();
       (void) llvm::createDomPrinterPass();
       (void) llvm::createDomOnlyViewerPass();

Modified: llvm/branches/type-system-rewrite/include/llvm/Module.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Module.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Module.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Module.h Mon Jun 20 01:45:54 2011
@@ -28,6 +28,10 @@
 class FunctionType;
 class GVMaterializer;
 class LLVMContext;
+class StructType;
+template<typename T> struct DenseMapInfo;
+template<typename KeyT, typename ValueT, 
+         typename KeyInfoT, typename ValueInfoT> class DenseMap;
 
 template<> struct ilist_traits<Function>
   : public SymbolTableListTraits<Function, Module> {
@@ -145,7 +149,6 @@
   NamedMDListType NamedMDList;    ///< The named metadata in the module
   std::string GlobalScopeAsm;     ///< Inline Asm at global scope.
   ValueSymbolTable *ValSymTab;    ///< Symbol table for values
-  TypeSymbolTable *TypeSymTab;    ///< Symbol table for types
   OwningPtr<GVMaterializer> Materializer;  ///< Used to materialize GlobalValues
   std::string ModuleID;           ///< Human readable identifier for the module
   std::string TargetTriple;       ///< Platform target triple Module compiled on
@@ -244,6 +247,18 @@
   /// custom metadata IDs registered in this LLVMContext.
   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
 
+  
+  typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*>,
+                   DenseMapInfo<unsigned> > NumeredTypesMapTy;
+
+  /// findUsedStructTypes - Walk the entire module and find all of the
+  /// struct types that are in use, returning them in a vector.
+  void findUsedStructTypes(std::vector<StructType*> &StructTypes) const;
+  
+  /// getTypeByName - Return the type with the specified name, or null if there
+  /// is none by that name.
+  const Type *getTypeByName(StringRef Name) const;
+
 /// @}
 /// @name Function Accessors
 /// @{
@@ -340,23 +355,6 @@
   void eraseNamedMetadata(NamedMDNode *NMD);
 
 /// @}
-/// @name Type Accessors
-/// @{
-
-  /// addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
-  /// there is already an entry for this name, true is returned and the symbol
-  /// table is not modified.
-  bool addTypeName(StringRef Name, const Type *Ty);
-
-  /// getTypeName - If there is at least one entry in the symbol table for the
-  /// specified type, return it.
-  std::string getTypeName(const Type *Ty) const;
-
-  /// getTypeByName - Return the type with the specified name in this module, or
-  /// null if there is none by that name.
-  const Type *getTypeByName(StringRef Name) const;
-
-/// @}
 /// @name Materialization
 /// @{
 
@@ -429,10 +427,6 @@
   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
   /// Get the Module's symbol table of global variable and function identifiers.
   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
-  /// Get the symbol table of types
-  const TypeSymbolTable  &getTypeSymbolTable() const  { return *TypeSymTab; }
-  /// Get the Module's symbol table of types
-  TypeSymbolTable        &getTypeSymbolTable()        { return *TypeSymTab; }
 
 /// @}
 /// @name Global Variable Iteration
@@ -535,6 +529,7 @@
 
   /// Dump the module to stderr (for debugging).
   void dump() const;
+  
   /// This function causes all the subinstructions to "let go" of all references
   /// that they are maintaining.  This allows one to 'delete' a whole class at
   /// a time, even though there may be circular references... first all

Modified: llvm/branches/type-system-rewrite/include/llvm/Support/PassManagerBuilder.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Support/PassManagerBuilder.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Support/PassManagerBuilder.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Support/PassManagerBuilder.h Mon Jun 20 01:45:54 2011
@@ -230,8 +230,8 @@
     MPM.add(createInstructionCombiningPass());  // Clean up after everything.
     
     if (!DisableUnitAtATime) {
+      // FIXME: We shouldn't bother with this anymore.
       MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
-      MPM.add(createDeadTypeEliminationPass()); // Eliminate dead types
       
       // GlobalOpt already deletes dead functions and globals, at -O3 try a
       // late pass of GlobalDCE.  It is capable of deleting dead cycles.

Modified: llvm/branches/type-system-rewrite/include/llvm/Transforms/IPO.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Transforms/IPO.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Transforms/IPO.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Transforms/IPO.h Mon Jun 20 01:45:54 2011
@@ -74,13 +74,6 @@
 
 
 //===----------------------------------------------------------------------===//
-/// createDeadTypeEliminationPass - Return a new pass that eliminates symbol
-/// table entries for types that are never used.
-///
-ModulePass *createDeadTypeEliminationPass();
-
-
-//===----------------------------------------------------------------------===//
 /// createGlobalDCEPass - This transform is designed to eliminate unreachable
 /// internal globals (functions or global variables)
 ///

Modified: llvm/branches/type-system-rewrite/include/llvm/Type.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Type.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Type.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Type.h Mon Jun 20 01:45:54 2011
@@ -15,19 +15,17 @@
 #ifndef LLVM_TYPE_H
 #define LLVM_TYPE_H
 
-#include "llvm/AbstractTypeUser.h"
 #include "llvm/Support/Casting.h"
-#include <vector>
 
 namespace llvm {
 
 class DerivedType;
 class PointerType;
 class IntegerType;
-class TypeMapBase;
 class raw_ostream;
 class Module;
 class LLVMContext;
+class LLVMContextImpl;
 template<class GraphType> struct GraphTraits;
 
 /// The instances of the Type class are immutable: once they are created,
@@ -35,29 +33,10 @@
 /// type is ever created.  Thus seeing if two types are equal is a matter of
 /// doing a trivial pointer comparison. To enforce that no two equal instances
 /// are created, Type instances can only be created via static factory methods 
-/// in class Type and in derived classes.
+/// in class Type and in derived classes.  Once allocated, Types are never
+/// free'd.
 /// 
-/// Once allocated, Types are never free'd, unless they are an abstract type
-/// that is resolved to a more concrete type.
-/// 
-/// Types themself don't have a name, and can be named either by:
-/// - using SymbolTable instance, typically from some Module,
-/// - using convenience methods in the Module class (which uses module's 
-///    SymbolTable too).
-///
-/// Opaque types are simple derived types with no state.  There may be many
-/// different Opaque type objects floating around, but two are only considered
-/// identical if they are pointer equals of each other.  This allows us to have
-/// two opaque types that end up resolving to different concrete types later.
-///
-/// Opaque types are also kinda weird and scary and different because they have
-/// to keep a list of uses of the type.  When, through linking, parsing, or
-/// bitcode reading, they become resolved, they need to find and update all
-/// users of the unknown type, causing them to reference a new, more concrete
-/// type.  Opaque types are deleted when their use list dwindles to zero users.
-///
-/// @brief Root of type hierarchy
-class Type : public AbstractTypeUser {
+class Type {
 public:
   //===--------------------------------------------------------------------===//
   /// Definitions of all of the base types for the Type system.  Based on this
@@ -85,8 +64,7 @@
     StructTyID,      ///< 11: Structures
     ArrayTyID,       ///< 12: Arrays
     PointerTyID,     ///< 13: Pointers
-    OpaqueTyID,      ///< 14: Opaque: type with unknown structure
-    VectorTyID,      ///< 15: SIMD 'packed' format, or other vector type
+    VectorTyID,      ///< 14: SIMD 'packed' format, or other vector type
 
     NumTypeIDs,                         // Must remain as last defined ID
     LastPrimitiveTyID = X86_MMXTyID,
@@ -94,86 +72,42 @@
   };
 
 private:
-  TypeID   ID : 8;    // The current base type of this type.
-  bool     Abstract : 1;  // True if type contains an OpaqueType
-  unsigned SubclassData : 23; //Space for subclasses to store data
-
-  /// RefCount - This counts the number of PATypeHolders that are pointing to
-  /// this type.  When this number falls to zero, if the type is abstract and
-  /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
-  /// derived types.
-  ///
-  mutable unsigned RefCount;
-
   /// Context - This refers to the LLVMContext in which this type was uniqued.
   LLVMContext &Context;
-  friend class LLVMContextImpl;
 
-  const Type *getForwardedTypeInternal() const;
-
-  // When the last reference to a forwarded type is removed, it is destroyed.
-  void destroy() const;
+  TypeID   ID : 8;            // The current base type of this type.
+  unsigned SubclassData : 24; // Space for subclasses to store data
 
 protected:
-  explicit Type(LLVMContext &C, TypeID id) :
-                             ID(id), Abstract(false), SubclassData(0),
-                             RefCount(0), Context(C),
-                             ForwardType(0), NumContainedTys(0),
-                             ContainedTys(0) {}
-  virtual ~Type() {
-    assert(AbstractTypeUsers.empty() && "Abstract types remain");
-  }
-
-  /// Types can become nonabstract later, if they are refined.
-  ///
-  inline void setAbstract(bool Val) { Abstract = Val; }
-
-  unsigned getRefCount() const { return RefCount; }
+  friend class LLVMContextImpl;
+  explicit Type(LLVMContext &C, TypeID tid)
+    : Context(C), ID(tid), SubclassData(0),
+      NumContainedTys(0), ContainedTys(0) {}
+  ~Type() {}
 
   unsigned getSubclassData() const { return SubclassData; }
-  void setSubclassData(unsigned val) { SubclassData = val; }
-
-  /// ForwardType - This field is used to implement the union find scheme for
-  /// abstract types.  When types are refined to other types, this field is set
-  /// to the more refined type.  Only abstract types can be forwarded.
-  mutable const Type *ForwardType;
-
-
-  /// AbstractTypeUsers - Implement a list of the users that need to be notified
-  /// if I am a type, and I get resolved into a more concrete type.
-  ///
-  mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
+  void setSubclassData(unsigned val) {
+    SubclassData = val;
+    // Ensure we don't have any accidental truncation.
+    assert(SubclassData == val && "Subclass data too large for field");
+  }
 
-  /// NumContainedTys - Keeps track of how many PATypeHandle instances there
-  /// are at the end of this type instance for the list of contained types. It
-  /// is the subclasses responsibility to set this up. Set to 0 if there are no
-  /// contained types in this type.
+  /// NumContainedTys - Keeps track of how many Type*'s there are in the
+  /// ContainedTys list.
   unsigned NumContainedTys;
 
-  /// ContainedTys - A pointer to the array of Types (PATypeHandle) contained 
-  /// by this Type.  For example, this includes the arguments of a function 
-  /// type, the elements of a structure, the pointee of a pointer, the element
-  /// type of an array, etc.  This pointer may be 0 for types that don't 
-  /// contain other types (Integer, Double, Float).  In general, the subclass 
-  /// should arrange for space for the PATypeHandles to be included in the 
-  /// allocation of the type object and set this pointer to the address of the 
-  /// first element. This allows the Type class to manipulate the ContainedTys 
-  /// without understanding the subclass's placement for this array.  keeping 
-  /// it here also allows the subtype_* members to be implemented MUCH more 
-  /// efficiently, and dynamically very few types do not contain any elements.
-  PATypeHandle *ContainedTys;
+  /// ContainedTys - A pointer to the array of Types contained by this Type.
+  /// For example, this includes the arguments of a function type, the elements
+  /// of a structure, the pointee of a pointer, the element type of an array,
+  /// etc.  This pointer may be 0 for types that don't contain other types
+  /// (Integer, Double, Float).
+  Type * const *ContainedTys;
 
 public:
   void print(raw_ostream &O) const;
-
-  /// @brief Debugging support: print to stderr
   void dump() const;
 
-  /// @brief Debugging support: print to stderr (use type names from context
-  /// module).
-  void dump(const Module *Context) const;
-
-  /// getContext - Fetch the LLVMContext in which this type was uniqued.
+  /// getContext - Return the LLVMContext in which this type was uniqued.
   LLVMContext &getContext() const { return Context; }
 
   //===--------------------------------------------------------------------===//
@@ -205,8 +139,10 @@
 
   /// isFloatingPointTy - Return true if this is one of the five floating point
   /// types
-  bool isFloatingPointTy() const { return ID == FloatTyID || ID == DoubleTyID ||
-      ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
+  bool isFloatingPointTy() const {
+    return ID == FloatTyID || ID == DoubleTyID ||
+      ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID;
+  }
 
   /// isX86_MMXTy - Return true if this is X86 MMX.
   bool isX86_MMXTy() const { return ID == X86_MMXTyID; }
@@ -249,19 +185,10 @@
   ///
   bool isPointerTy() const { return ID == PointerTyID; }
 
-  /// isOpaqueTy - True if this is an instance of OpaqueType.
-  ///
-  bool isOpaqueTy() const { return ID == OpaqueTyID; }
-
   /// isVectorTy - True if this is an instance of VectorType.
   ///
   bool isVectorTy() const { return ID == VectorTyID; }
 
-  /// isAbstract - True if the type is either an Opaque type, or is a derived
-  /// type that includes an opaque type somewhere in it.
-  ///
-  inline bool isAbstract() const { return Abstract; }
-
   /// canLosslesslyBitCastTo - Return true if this type could be converted 
   /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts 
   /// are valid for types of the same size only where no re-interpretation of 
@@ -276,24 +203,22 @@
   /// Here are some useful little methods to query what type derived types are
   /// Note that all other types can just compare to see if this == Type::xxxTy;
   ///
-  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
-  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
+  bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
+  bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
 
   /// isFirstClassType - Return true if the type is "first class", meaning it
   /// is a valid type for a Value.
   ///
-  inline bool isFirstClassType() const {
-    // There are more first-class kinds than non-first-class kinds, so a
-    // negative test is simpler than a positive one.
-    return ID != FunctionTyID && ID != VoidTyID && ID != OpaqueTyID;
+  bool isFirstClassType() const {
+    return ID != FunctionTyID && ID != VoidTyID;
   }
 
   /// isSingleValueType - Return true if the type is a valid type for a
-  /// virtual register in codegen.  This includes all first-class types
-  /// except struct and array types.
+  /// register in codegen.  This includes all first-class types except struct
+  /// and array types.
   ///
-  inline bool isSingleValueType() const {
-    return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
+  bool isSingleValueType() const {
+    return (ID != VoidTyID && isPrimitiveType()) ||
             ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
   }
 
@@ -302,7 +227,7 @@
   /// extractvalue instruction. This includes struct and array types, but
   /// does not include vector types.
   ///
-  inline bool isAggregateType() const {
+  bool isAggregateType() const {
     return ID == StructTyID || ID == ArrayTyID;
   }
 
@@ -319,9 +244,8 @@
     // it doesn't have a size.
     if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID)
       return false;
-    // If it is something that can have a size and it's concrete, it definitely
-    // has a size, otherwise we have to try harder to decide.
-    return !isAbstract() || isSizedDerivedType();
+    // Otherwise we have to try harder to decide.
+    return isSizedDerivedType();
   }
 
   /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
@@ -346,23 +270,14 @@
   /// have a stable mantissa (e.g. ppc long double), this method returns -1.
   int getFPMantissaWidth() const;
 
-  /// getForwardedType - Return the type that this type has been resolved to if
-  /// it has been resolved to anything.  This is used to implement the
-  /// union-find algorithm for type resolution, and shouldn't be used by general
-  /// purpose clients.
-  const Type *getForwardedType() const {
-    if (!ForwardType) return 0;
-    return getForwardedTypeInternal();
-  }
-
   /// getScalarType - If this is a vector type, return the element type,
-  /// otherwise return this.
+  /// otherwise return 'this'.
   const Type *getScalarType() const;
 
   //===--------------------------------------------------------------------===//
-  // Type Iteration support
+  // Type Iteration support.
   //
-  typedef PATypeHandle *subtype_iterator;
+  typedef Type * const *subtype_iterator;
   subtype_iterator subtype_begin() const { return ContainedTys; }
   subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
 
@@ -370,9 +285,9 @@
   /// (defined a the end of the file).  For derived types, this returns the
   /// types 'contained' in the derived type.
   ///
-  const Type *getContainedType(unsigned i) const {
+  Type *getContainedType(unsigned i) const {
     assert(i < NumContainedTys && "Index out of range!");
-    return ContainedTys[i].get();
+    return ContainedTys[i];
   }
 
   /// getNumContainedTypes - Return the number of types in the derived type.
@@ -385,140 +300,77 @@
   //
 
   /// getPrimitiveType - Return a type based on an identifier.
-  static const Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
+  static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
 
   //===--------------------------------------------------------------------===//
-  // These are the builtin types that are always available...
+  // These are the builtin types that are always available.
   //
-  static const Type *getVoidTy(LLVMContext &C);
-  static const Type *getLabelTy(LLVMContext &C);
-  static const Type *getFloatTy(LLVMContext &C);
-  static const Type *getDoubleTy(LLVMContext &C);
-  static const Type *getMetadataTy(LLVMContext &C);
-  static const Type *getX86_FP80Ty(LLVMContext &C);
-  static const Type *getFP128Ty(LLVMContext &C);
-  static const Type *getPPC_FP128Ty(LLVMContext &C);
-  static const Type *getX86_MMXTy(LLVMContext &C);
-  static const IntegerType *getIntNTy(LLVMContext &C, unsigned N);
-  static const IntegerType *getInt1Ty(LLVMContext &C);
-  static const IntegerType *getInt8Ty(LLVMContext &C);
-  static const IntegerType *getInt16Ty(LLVMContext &C);
-  static const IntegerType *getInt32Ty(LLVMContext &C);
-  static const IntegerType *getInt64Ty(LLVMContext &C);
+  static Type *getVoidTy(LLVMContext &C);
+  static Type *getLabelTy(LLVMContext &C);
+  static Type *getFloatTy(LLVMContext &C);
+  static Type *getDoubleTy(LLVMContext &C);
+  static Type *getMetadataTy(LLVMContext &C);
+  static Type *getX86_FP80Ty(LLVMContext &C);
+  static Type *getFP128Ty(LLVMContext &C);
+  static Type *getPPC_FP128Ty(LLVMContext &C);
+  static Type *getX86_MMXTy(LLVMContext &C);
+  static IntegerType *getIntNTy(LLVMContext &C, unsigned N);
+  static IntegerType *getInt1Ty(LLVMContext &C);
+  static IntegerType *getInt8Ty(LLVMContext &C);
+  static IntegerType *getInt16Ty(LLVMContext &C);
+  static IntegerType *getInt32Ty(LLVMContext &C);
+  static IntegerType *getInt64Ty(LLVMContext &C);
 
   //===--------------------------------------------------------------------===//
   // Convenience methods for getting pointer types with one of the above builtin
   // types as pointee.
   //
-  static const PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getIntNPtrTy(LLVMContext &C, unsigned N,
-                                         unsigned AS = 0);
-  static const PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
-  static const PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0);
+  static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
+  static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
 
   /// Methods for support type inquiry through isa, cast, and dyn_cast:
   static inline bool classof(const Type *) { return true; }
 
-  void addRef() const {
-    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
-    ++RefCount;
-  }
-
-  void dropRef() const {
-    assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
-    assert(RefCount && "No objects are currently referencing this object!");
-
-    // If this is the last PATypeHolder using this object, and there are no
-    // PATypeHandles using it, the type is dead, delete it now.
-    if (--RefCount == 0 && AbstractTypeUsers.empty())
-      this->destroy();
-  }
-  
-  /// addAbstractTypeUser - Notify an abstract type that there is a new user of
-  /// it.  This function is called primarily by the PATypeHandle class.
-  ///
-  void addAbstractTypeUser(AbstractTypeUser *U) const;
-  
-  /// removeAbstractTypeUser - Notify an abstract type that a user of the class
-  /// no longer has a handle to the type.  This function is called primarily by
-  /// the PATypeHandle class.  When there are no users of the abstract type, it
-  /// is annihilated, because there is no way to get a reference to it ever
-  /// again.
-  ///
-  void removeAbstractTypeUser(AbstractTypeUser *U) const;
-
   /// getPointerTo - Return a pointer to the current type.  This is equivalent
   /// to PointerType::get(Foo, AddrSpace).
-  const PointerType *getPointerTo(unsigned AddrSpace = 0) const;
+  PointerType *getPointerTo(unsigned AddrSpace = 0) const;
 
 private:
   /// isSizedDerivedType - Derived types like structures and arrays are sized
   /// iff all of the members of the type are sized as well.  Since asking for
   /// their size is relatively uncommon, move this operation out of line.
   bool isSizedDerivedType() const;
-
-  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
-  virtual void typeBecameConcrete(const DerivedType *AbsTy);
-
-protected:
-  // PromoteAbstractToConcrete - This is an internal method used to calculate
-  // change "Abstract" from true to false when types are refined.
-  void PromoteAbstractToConcrete();
-  friend class TypeMapBase;
 };
 
-//===----------------------------------------------------------------------===//
-// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
-// These are defined here because they MUST be inlined, yet are dependent on
-// the definition of the Type class.
-//
-inline void PATypeHandle::addUser() {
-  assert(Ty && "Type Handle has a null type!");
-  if (Ty->isAbstract())
-    Ty->addAbstractTypeUser(User);
-}
-inline void PATypeHandle::removeUser() {
-  if (Ty->isAbstract())
-    Ty->removeAbstractTypeUser(User);
-}
-
-// Define inline methods for PATypeHolder.
-
-/// get - This implements the forwarding part of the union-find algorithm for
-/// abstract types.  Before every access to the Type*, we check to see if the
-/// type we are pointing to is forwarding to a new type.  If so, we drop our
-/// reference to the type.
-///
-inline Type *PATypeHolder::get() const {
-  if (Ty == 0) return 0;
-  const Type *NewTy = Ty->getForwardedType();
-  if (!NewTy) return const_cast<Type*>(Ty);
-  return *const_cast<PATypeHolder*>(this) = NewTy;
-}
-
-inline void PATypeHolder::addRef() {
-  if (Ty && Ty->isAbstract())
-    Ty->addRef();
-}
-
-inline void PATypeHolder::dropRef() {
-  if (Ty && Ty->isAbstract())
-    Ty->dropRef();
+// Printing of types.
+static inline raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
+  T.print(OS);
+  return OS;
 }
 
+// allow isa<PointerType>(x) to work without DerivedTypes.h included.
+template <> struct isa_impl<PointerType, Type> {
+  static inline bool doit(const Type &Ty) {
+    return Ty.getTypeID() == Type::PointerTyID;
+  }
+};
 
+  
 //===----------------------------------------------------------------------===//
 // Provide specializations of GraphTraits to be able to treat a type as a
 // graph of sub types.
 
+
 template <> struct GraphTraits<Type*> {
   typedef Type NodeType;
   typedef Type::subtype_iterator ChildIteratorType;
@@ -545,14 +397,6 @@
   }
 };
 
-template <> struct isa_impl<PointerType, Type> {
-  static inline bool doit(const Type &Ty) {
-    return Ty.getTypeID() == Type::PointerTyID;
-  }
-};
-
-raw_ostream &operator<<(raw_ostream &OS, const Type &T);
-
 } // End llvm namespace
 
 #endif

Modified: llvm/branches/type-system-rewrite/include/llvm/TypeSymbolTable.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/TypeSymbolTable.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/TypeSymbolTable.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/TypeSymbolTable.h Mon Jun 20 01:45:54 2011
@@ -1,152 +1,3 @@
-//===-- llvm/TypeSymbolTable.h - Implement a Type Symtab --------*- C++ -*-===//
-//
-//                     The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This file implements the name/type symbol table for LLVM.
-//
-//===----------------------------------------------------------------------===//
 
-#ifndef LLVM_TYPE_SYMBOL_TABLE_H
-#define LLVM_TYPE_SYMBOL_TABLE_H
 
-#include "llvm/Type.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/Support/DataTypes.h"
-#include <map>
-
-namespace llvm {
-
-/// This class provides a symbol table of name/type pairs with operations to
-/// support constructing, searching and iterating over the symbol table. The
-/// class derives from AbstractTypeUser so that the contents of the symbol
-/// table can be updated when abstract types become concrete.
-class TypeSymbolTable : public AbstractTypeUser {
-
-/// @name Types
-/// @{
-public:
-
-  /// @brief A mapping of names to types.
-  typedef std::map<const std::string, const Type*> TypeMap;
-
-  /// @brief An iterator over the TypeMap.
-  typedef TypeMap::iterator iterator;
-
-  /// @brief A const_iterator over the TypeMap.
-  typedef TypeMap::const_iterator const_iterator;
-
-/// @}
-/// @name Constructors
-/// @{
-public:
-
-  TypeSymbolTable():LastUnique(0) {}
-  ~TypeSymbolTable();
-
-/// @}
-/// @name Accessors
-/// @{
-public:
-
-  /// Generates a unique name for a type based on the \p BaseName by
-  /// incrementing an integer and appending it to the name, if necessary
-  /// @returns the unique name
-  /// @brief Get a unique name for a type
-  std::string getUniqueName(StringRef BaseName) const;
-
-  /// This method finds the type with the given \p name in the type map
-  /// and returns it.
-  /// @returns null if the name is not found, otherwise the Type
-  /// associated with the \p name.
-  /// @brief Lookup a type by name.
-  Type *lookup(StringRef name) const;
-
-  /// Lookup the type associated with name.
-  /// @returns end() if the name is not found, or an iterator at the entry for
-  /// Type.
-  iterator find(StringRef Name) {
-    return tmap.find(Name);
-  }
-
-  /// Lookup the type associated with name.
-  /// @returns end() if the name is not found, or an iterator at the entry for
-  /// Type.
-  const_iterator find(StringRef Name) const {
-    return tmap.find(Name);
-  }
-
-  /// @returns true iff the symbol table is empty.
-  /// @brief Determine if the symbol table is empty
-  inline bool empty() const { return tmap.empty(); }
-
-  /// @returns the size of the symbol table
-  /// @brief The number of name/type pairs is returned.
-  inline unsigned size() const { return unsigned(tmap.size()); }
-
-  /// This function can be used from the debugger to display the
-  /// content of the symbol table while debugging.
-  /// @brief Print out symbol table on stderr
-  void dump() const;
-
-/// @}
-/// @name Iteration
-/// @{
-public:
-  /// Get an iterator to the start of the symbol table
-  inline iterator begin() { return tmap.begin(); }
-
-  /// @brief Get a const_iterator to the start of the symbol table
-  inline const_iterator begin() const { return tmap.begin(); }
-
-  /// Get an iterator to the end of the symbol table.
-  inline iterator end() { return tmap.end(); }
-
-  /// Get a const_iterator to the end of the symbol table.
-  inline const_iterator end() const { return tmap.end(); }
-
-/// @}
-/// @name Mutators
-/// @{
-public:
-
-  /// Inserts a type into the symbol table with the specified name. There can be
-  /// a many-to-one mapping between names and types. This method allows a type
-  /// with an existing entry in the symbol table to get a new name.
-  /// @brief Insert a type under a new name.
-  void insert(StringRef Name, const Type *Typ);
-
-  /// Remove a type at the specified position in the symbol table.
-  /// @returns the removed Type.
-  /// @returns the Type that was erased from the symbol table.
-  Type* remove(iterator TI);
-
-/// @}
-/// @name AbstractTypeUser Methods
-/// @{
-private:
-  /// This function is called when one of the types in the type plane
-  /// is refined.
-  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
-
-  /// This function marks a type as being concrete (defined).
-  virtual void typeBecameConcrete(const DerivedType *AbsTy);
-
-/// @}
-/// @name Internal Data
-/// @{
-private:
-  TypeMap tmap; ///< This is the mapping of names to types.
-  mutable uint32_t LastUnique; ///< Counter for tracking unique names
-
-/// @}
-
-};
-
-} // End llvm namespace
-
-#endif
+#error REMOVE ME.

Modified: llvm/branches/type-system-rewrite/include/llvm/Value.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/include/llvm/Value.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/include/llvm/Value.h (original)
+++ llvm/branches/type-system-rewrite/include/llvm/Value.h Mon Jun 20 01:45:54 2011
@@ -14,7 +14,6 @@
 #ifndef LLVM_VALUE_H
 #define LLVM_VALUE_H
 
-#include "llvm/AbstractTypeUser.h"
 #include "llvm/Use.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
@@ -32,7 +31,6 @@
 class GlobalAlias;
 class InlineAsm;
 class ValueSymbolTable;
-class TypeSymbolTable;
 template<typename ValueTy> class StringMapEntry;
 template <typename ValueTy = Value>
 class AssertingVH;
@@ -43,6 +41,7 @@
 class LLVMContext;
 class Twine;
 class MDNode;
+class Type;
 
 //===----------------------------------------------------------------------===//
 //                                 Value Class
@@ -77,12 +76,11 @@
   /// This field is initialized to zero by the ctor.
   unsigned short SubclassData;
 
-  PATypeHolder VTy;
+  Type *VTy;
   Use *UseList;
 
   friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
   friend class ValueHandleBase;
-  friend class AbstractTypeUser;
   ValueName *Name;
 
   void operator=(const Value &);     // Do not implement
@@ -107,13 +105,13 @@
 
   /// All values are typed, get the type of this value.
   ///
-  inline const Type *getType() const { return VTy; }
+  Type *getType() const { return VTy; }
 
   /// All values hold a context through their type.
   LLVMContext &getContext() const;
 
   // All values can potentially be named...
-  inline bool hasName() const { return Name != 0; }
+  bool hasName() const { return Name != 0; }
   ValueName *getValueName() const { return Name; }
   
   /// getName() - Return a constant reference to the value's name. This is cheap
@@ -279,10 +277,6 @@
     return true; // Values are always values.
   }
 
-  /// getRawType - This should only be used to implement the vmcore library.
-  ///
-  const Type *getRawType() const { return VTy.getRawType(); }
-
   /// stripPointerCasts - This method strips off any unneeded pointer
   /// casts from the specified value, returning the original uncasted value.
   /// Note that the returned value has pointer type if the specified value does.

Modified: llvm/branches/type-system-rewrite/lib/AsmParser/LLLexer.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/AsmParser/LLLexer.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/AsmParser/LLLexer.h (original)
+++ llvm/branches/type-system-rewrite/lib/AsmParser/LLLexer.h Mon Jun 20 01:45:54 2011
@@ -38,7 +38,7 @@
     lltok::Kind CurKind;
     std::string StrVal;
     unsigned UIntVal;
-    const Type *TyVal;
+    Type *TyVal;
     APFloat APFloatVal;
     APSInt  APSIntVal;
 
@@ -56,7 +56,7 @@
     LocTy getLoc() const { return SMLoc::getFromPointer(TokStart); }
     lltok::Kind getKind() const { return CurKind; }
     const std::string &getStrVal() const { return StrVal; }
-    const Type *getTyVal() const { return TyVal; }
+    Type *getTyVal() const { return TyVal; }
     unsigned getUIntVal() const { return UIntVal; }
     const APSInt &getAPSIntVal() const { return APSIntVal; }
     const APFloat &getAPFloatVal() const { return APFloatVal; }

Modified: llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.cpp Mon Jun 20 01:45:54 2011
@@ -89,15 +89,16 @@
     ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
   }
   
-  
-  if (!ForwardRefTypes.empty())
-    return Error(ForwardRefTypes.begin()->second.second,
-                 "use of undefined type named '" +
-                 ForwardRefTypes.begin()->first + "'");
-  if (!ForwardRefTypeIDs.empty())
-    return Error(ForwardRefTypeIDs.begin()->second.second,
-                 "use of undefined type '%" +
-                 Twine(ForwardRefTypeIDs.begin()->first) + "'");
+  for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
+    if (NumberedTypes[i].second.isValid())
+      return Error(NumberedTypes[i].second,
+                   "use of undefined type '%" + Twine(i) + "'");
+
+  for (StringMap<std::pair<StructType*, LocTy> >::iterator I =
+       NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
+    if (I->second.second.isValid())
+      return Error(I->second.second,
+                   "use of undefined type named '" + I->getKey() + "'");
 
   if (!ForwardRefVals.empty())
     return Error(ForwardRefVals.begin()->second.second,
@@ -290,39 +291,35 @@
 }
 
 /// ParseUnnamedType:
-///   ::= LocalVarID '=' 'type' type
+///   ::= LocalVarID '=' 'type' StructType
 bool LLParser::ParseUnnamedType() {
   LocTy TypeLoc = Lex.getLoc();
   unsigned TypeID = NumberedTypes.size();
-  if (Lex.getUIntVal() != TypeID)
-    return Error(Lex.getLoc(), "type expected to be numbered '%" +
-                 Twine(TypeID) + "'");
   Lex.Lex(); // eat LocalVarID;
 
   if (ParseToken(lltok::equal, "expected '=' after name") ||
       ParseToken(lltok::kw_type, "expected 'type' after '='"))
     return true;
 
-  PATypeHolder Ty(Type::getVoidTy(Context));
-  if (ParseType(Ty)) return true;
-
-  // See if this type was previously referenced.
-  std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
-    FI = ForwardRefTypeIDs.find(TypeID);
-  if (FI != ForwardRefTypeIDs.end()) {
-    if (FI->second.first.get() == Ty)
-      return Error(TypeLoc, "self referential type is invalid");
-
-    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
-    Ty = FI->second.first.get();
-    ForwardRefTypeIDs.erase(FI);
-  }
-
-  NumberedTypes.push_back(Ty);
-
-  return false;
+  if (TypeID >= NumberedTypes.size())
+    NumberedTypes.resize(TypeID+1);
+  
+  // If the type was already defined, diagnose the redefinition.
+  if (NumberedTypes[TypeID].first && 
+      !NumberedTypes[TypeID].second.isValid())
+    return Error(TypeLoc, "redefinition of type %" + Twine(TypeID));
+  
+  // If this type number has never been uttered, create it.
+  if (NumberedTypes[TypeID].first == 0)
+    NumberedTypes[TypeID].first = StructType::createNamed(Context, "");
+  
+  // This type is being defined, so clear the location to indicate this.
+  NumberedTypes[TypeID].second = SMLoc();
+  
+  return ParseStructDefinition(NumberedTypes[TypeID].first);
 }
 
+
 /// toplevelentity
 ///   ::= LocalVar '=' 'type' type
 bool LLParser::ParseNamedType() {
@@ -330,37 +327,26 @@
   LocTy NameLoc = Lex.getLoc();
   Lex.Lex();  // eat LocalVar.
 
-  PATypeHolder Ty(Type::getVoidTy(Context));
-
   if (ParseToken(lltok::equal, "expected '=' after name") ||
-      ParseToken(lltok::kw_type, "expected 'type' after name") ||
-      ParseType(Ty))
+      ParseToken(lltok::kw_type, "expected 'type' after name"))
     return true;
-
-  // Set the type name, checking for conflicts as we do so.
-  bool AlreadyExists = M->addTypeName(Name, Ty);
-  if (!AlreadyExists) return false;
-
-  // See if this type is a forward reference.  We need to eagerly resolve
-  // types to allow recursive type redefinitions below.
-  std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
-  FI = ForwardRefTypes.find(Name);
-  if (FI != ForwardRefTypes.end()) {
-    if (FI->second.first.get() == Ty)
-      return Error(NameLoc, "self referential type is invalid");
-
-    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
-    Ty = FI->second.first.get();
-    ForwardRefTypes.erase(FI);
-    return false;
-  }
-
-  // Inserting a name that is already defined, get the existing name.
-  assert(M->getTypeByName(Name) && "Conflict but no matching type?!");
-
-  // Otherwise, this is an attempt to redefine a type, report the error.
-  return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
-               getTypeString(Ty) + "'");
+  
+  std::pair<StructType*, LocTy> &Entry = NamedTypes[Name];
+  
+  // If the type was already defined, diagnose the redefinition.
+  if (Entry.first && !Entry.second.isValid())
+    return Error(NameLoc, "redefinition of type %" + Name);
+  
+  // If this type number has never been uttered, create it.  Note that this can
+  // end up with a different name than we request if there is another type of
+  // this name in the context.
+  if (Entry.first == 0)
+    Entry.first = StructType::createNamed(Context, Name);
+  
+  // This type is being defined, so clear the location to indicate this.
+  Entry.second = SMLoc();
+  
+  return ParseStructDefinition(Entry.first);
 }
 
 
@@ -536,7 +522,7 @@
   unsigned MetadataID = 0;
 
   LocTy TyLoc;
-  PATypeHolder Ty(Type::getVoidTy(Context));
+  Type *Ty = 0;
   SmallVector<Value *, 16> Elts;
   if (ParseUInt32(MetadataID) ||
       ParseToken(lltok::equal, "expected '=' here") ||
@@ -668,7 +654,7 @@
   LocTy UnnamedAddrLoc;
   LocTy TyLoc;
 
-  PATypeHolder Ty(Type::getVoidTy(Context));
+  Type *Ty = 0;
   if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
       ParseOptionalAddrSpace(AddrSpace) ||
       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
@@ -792,18 +778,11 @@
 
   // Otherwise, create a new forward reference for this value and remember it.
   GlobalValue *FwdVal;
-  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
-    // Function types can return opaque but functions can't.
-    if (FT->getReturnType()->isOpaqueTy()) {
-      Error(Loc, "function may not return opaque type");
-      return 0;
-    }
-
+  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
-  } else {
+  else
     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
                                 GlobalValue::ExternalWeakLinkage, 0, Name);
-  }
 
   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
   return FwdVal;
@@ -837,17 +816,11 @@
 
   // Otherwise, create a new forward reference for this value and remember it.
   GlobalValue *FwdVal;
-  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
-    // Function types can return opaque but functions can't.
-    if (FT->getReturnType()->isOpaqueTy()) {
-      Error(Loc, "function may not return opaque type");
-      return 0;
-    }
+  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
-  } else {
+  else
     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
                                 GlobalValue::ExternalWeakLinkage, 0, "");
-  }
 
   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
   return FwdVal;
@@ -1228,165 +1201,68 @@
 // Type Parsing.
 //===----------------------------------------------------------------------===//
 
-/// ParseType - Parse and resolve a full type.
-bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
-  LocTy TypeLoc = Lex.getLoc();
-  if (ParseTypeRec(Result)) return true;
-
-  // Verify no unresolved uprefs.
-  if (!UpRefs.empty())
-    return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
-
-  if (!AllowVoid && Result.get()->isVoidTy())
-    return Error(TypeLoc, "void type only allowed for function results");
-
-  return false;
-}
-
-/// HandleUpRefs - Every time we finish a new layer of types, this function is
-/// called.  It loops through the UpRefs vector, which is a list of the
-/// currently active types.  For each type, if the up-reference is contained in
-/// the newly completed type, we decrement the level count.  When the level
-/// count reaches zero, the up-referenced type is the type that is passed in:
-/// thus we can complete the cycle.
-///
-PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
-  // If Ty isn't abstract, or if there are no up-references in it, then there is
-  // nothing to resolve here.
-  if (!ty->isAbstract() || UpRefs.empty()) return ty;
-
-  PATypeHolder Ty(ty);
-#if 0
-  dbgs() << "Type '" << *Ty
-         << "' newly formed.  Resolving upreferences.\n"
-         << UpRefs.size() << " upreferences active!\n";
-#endif
-
-  // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
-  // to zero), we resolve them all together before we resolve them to Ty.  At
-  // the end of the loop, if there is anything to resolve to Ty, it will be in
-  // this variable.
-  OpaqueType *TypeToResolve = 0;
-
-  for (unsigned i = 0; i != UpRefs.size(); ++i) {
-    // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
-    bool ContainsType =
-      std::find(Ty->subtype_begin(), Ty->subtype_end(),
-                UpRefs[i].LastContainedTy) != Ty->subtype_end();
-
-#if 0
-    dbgs() << "  UR#" << i << " - TypeContains(" << *Ty << ", "
-           << *UpRefs[i].LastContainedTy << ") = "
-           << (ContainsType ? "true" : "false")
-           << " level=" << UpRefs[i].NestingLevel << "\n";
-#endif
-    if (!ContainsType)
-      continue;
-
-    // Decrement level of upreference
-    unsigned Level = --UpRefs[i].NestingLevel;
-    UpRefs[i].LastContainedTy = Ty;
-
-    // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
-    if (Level != 0)
-      continue;
-
-#if 0
-    dbgs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
-#endif
-    if (!TypeToResolve)
-      TypeToResolve = UpRefs[i].UpRefTy;
-    else
-      UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
-    UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
-    --i;                                // Do not skip the next element.
-  }
-
-  if (TypeToResolve)
-    TypeToResolve->refineAbstractTypeTo(Ty);
-
-  return Ty;
-}
-
-
-/// ParseTypeRec - The recursive function used to process the internal
-/// implementation details of types.
-bool LLParser::ParseTypeRec(PATypeHolder &Result) {
+/// ParseType - Parse a type.
+bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
+  SMLoc TypeLoc = Lex.getLoc();
   switch (Lex.getKind()) {
   default:
     return TokError("expected type");
   case lltok::Type:
-    // TypeRec ::= 'float' | 'void' (etc)
+    // Type ::= 'float' | 'void' (etc)
     Result = Lex.getTyVal();
     Lex.Lex();
     break;
-  case lltok::kw_opaque:
-    // TypeRec ::= 'opaque'
-    Result = OpaqueType::get(Context);
-    Lex.Lex();
-    break;
   case lltok::lbrace:
-    // TypeRec ::= '{' ... '}'
-    if (ParseStructType(Result, false))
+    // Type ::= StructType
+    if (ParseAnonStructType(Result, false))
       return true;
     break;
   case lltok::lsquare:
-    // TypeRec ::= '[' ... ']'
+    // Type ::= '[' ... ']'
     Lex.Lex(); // eat the lsquare.
     if (ParseArrayVectorType(Result, false))
       return true;
     break;
   case lltok::less: // Either vector or packed struct.
-    // TypeRec ::= '<' ... '>'
+    // Type ::= '<' ... '>'
     Lex.Lex();
     if (Lex.getKind() == lltok::lbrace) {
-      if (ParseStructType(Result, true) ||
+      if (ParseAnonStructType(Result, true) ||
           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
         return true;
     } else if (ParseArrayVectorType(Result, true))
       return true;
     break;
-  case lltok::LocalVar:
-    // TypeRec ::= %foo
-    if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
-      Result = T;
-    } else {
-      Result = OpaqueType::get(Context);
-      ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
-                                            std::make_pair(Result,
-                                                           Lex.getLoc())));
-      M->addTypeName(Lex.getStrVal(), Result.get());
+  case lltok::LocalVar: {
+    // Type ::= %foo
+    std::pair<StructType*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
+    
+    // If the type hasn't been defined yet, create a forward definition and
+    // remember where that forward def'n was seen (in case it never is defined).
+    if (Entry.first == 0) {
+      Entry.first = StructType::createNamed(Context, Lex.getStrVal());
+      Entry.second = Lex.getLoc();
     }
+    Result = Entry.first;
     Lex.Lex();
     break;
+  }
 
-  case lltok::LocalVarID:
-    // TypeRec ::= %4
-    if (Lex.getUIntVal() < NumberedTypes.size())
-      Result = NumberedTypes[Lex.getUIntVal()];
-    else {
-      std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
-        I = ForwardRefTypeIDs.find(Lex.getUIntVal());
-      if (I != ForwardRefTypeIDs.end())
-        Result = I->second.first;
-      else {
-        Result = OpaqueType::get(Context);
-        ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
-                                                std::make_pair(Result,
-                                                               Lex.getLoc())));
-      }
+  case lltok::LocalVarID: {
+    // Type ::= %4
+    if (Lex.getUIntVal() >= NumberedTypes.size())
+      NumberedTypes.resize(Lex.getUIntVal()+1);
+    std::pair<StructType*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
+    
+    // If the type hasn't been defined yet, create a forward definition and
+    // remember where that forward def'n was seen (in case it never is defined).
+    if (Entry.first == 0) {
+      Entry.first = StructType::createNamed(Context, "");
+      Entry.second = Lex.getLoc();
     }
+    Result = Entry.first;
     Lex.Lex();
     break;
-  case lltok::backslash: {
-    // TypeRec ::= '\' 4
-    Lex.Lex();
-    unsigned Val;
-    if (ParseUInt32(Val)) return true;
-    OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
-    UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
-    Result = OT;
-    break;
   }
   }
 
@@ -1394,34 +1270,37 @@
   while (1) {
     switch (Lex.getKind()) {
     // End of type.
-    default: return false;
+    default:
+      if (!AllowVoid && Result->isVoidTy())
+        return Error(TypeLoc, "void type only allowed for function results");
+      return false;
 
-    // TypeRec ::= TypeRec '*'
+    // Type ::= Type '*'
     case lltok::star:
-      if (Result.get()->isLabelTy())
+      if (Result->isLabelTy())
         return TokError("basic block pointers are invalid");
-      if (Result.get()->isVoidTy())
-        return TokError("pointers to void are invalid; use i8* instead");
-      if (!PointerType::isValidElementType(Result.get()))
+      if (Result->isVoidTy())
+        return TokError("pointers to void are invalid - use i8* instead");
+      if (!PointerType::isValidElementType(Result))
         return TokError("pointer to this type is invalid");
-      Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
+      Result = PointerType::getUnqual(Result);
       Lex.Lex();
       break;
 
-    // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
+    // Type ::= Type 'addrspace' '(' uint32 ')' '*'
     case lltok::kw_addrspace: {
-      if (Result.get()->isLabelTy())
+      if (Result->isLabelTy())
         return TokError("basic block pointers are invalid");
-      if (Result.get()->isVoidTy())
+      if (Result->isVoidTy())
         return TokError("pointers to void are invalid; use i8* instead");
-      if (!PointerType::isValidElementType(Result.get()))
+      if (!PointerType::isValidElementType(Result))
         return TokError("pointer to this type is invalid");
       unsigned AddrSpace;
       if (ParseOptionalAddrSpace(AddrSpace) ||
           ParseToken(lltok::star, "expected '*' in address space"))
         return true;
 
-      Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
+      Result = PointerType::get(Result, AddrSpace);
       break;
     }
 
@@ -1452,7 +1331,7 @@
 
     // Parse the argument.
     LocTy ArgLoc;
-    PATypeHolder ArgTy(Type::getVoidTy(Context));
+    Type *ArgTy = 0;
     unsigned ArgAttrs1 = Attribute::None;
     unsigned ArgAttrs2 = Attribute::None;
     Value *V;
@@ -1472,7 +1351,7 @@
 
 
 /// ParseArgumentList - Parse the argument list for a function type or function
-/// prototype.  If 'inType' is true then we are parsing a FunctionType.
+/// prototype.
 ///   ::= '(' ArgTypeListI ')'
 /// ArgTypeListI
 ///   ::= /*empty*/
@@ -1480,8 +1359,8 @@
 ///   ::= ArgTypeList ',' '...'
 ///   ::= ArgType (',' ArgType)*
 ///
-bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
-                                 bool &isVarArg, bool inType) {
+bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
+                                 bool &isVarArg){
   isVarArg = false;
   assert(Lex.getKind() == lltok::lparen);
   Lex.Lex(); // eat the (.
@@ -1493,14 +1372,11 @@
     Lex.Lex();
   } else {
     LocTy TypeLoc = Lex.getLoc();
-    PATypeHolder ArgTy(Type::getVoidTy(Context));
+    Type *ArgTy = 0;
     unsigned Attrs;
     std::string Name;
 
-    // If we're parsing a type, use ParseTypeRec, because we allow recursive
-    // types (such as a function returning a pointer to itself).  If parsing a
-    // function prototype, we require fully resolved types.
-    if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
+    if (ParseType(ArgTy) ||
         ParseOptionalAttrs(Attrs, 0)) return true;
 
     if (ArgTy->isVoidTy())
@@ -1525,8 +1401,7 @@
 
       // Otherwise must be an argument type.
       TypeLoc = Lex.getLoc();
-      if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
-          ParseOptionalAttrs(Attrs, 0)) return true;
+      if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
 
       if (ArgTy->isVoidTy())
         return Error(TypeLoc, "argument can not have void type");
@@ -1538,7 +1413,7 @@
         Name = "";
       }
 
-      if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
+      if (!ArgTy->isFirstClassType())
         return Error(TypeLoc, "invalid type for function argument");
 
       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
@@ -1550,15 +1425,15 @@
 
 /// ParseFunctionType
 ///  ::= Type ArgumentList OptionalAttrs
-bool LLParser::ParseFunctionType(PATypeHolder &Result) {
+bool LLParser::ParseFunctionType(Type *&Result) {
   assert(Lex.getKind() == lltok::lparen);
 
   if (!FunctionType::isValidReturnType(Result))
     return TokError("invalid function return type");
 
-  std::vector<ArgInfo> ArgList;
+  SmallVector<ArgInfo, 8> ArgList;
   bool isVarArg;
-  if (ParseArgumentList(ArgList, isVarArg, true))
+  if (ParseArgumentList(ArgList, isVarArg))
     return true;
 
   // Reject names on the arguments lists.
@@ -1570,68 +1445,90 @@
                    "argument attributes invalid in function type");
   }
 
-  std::vector<const Type*> ArgListTy;
+  SmallVector<const Type*, 16> ArgListTy;
   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
-    ArgListTy.push_back(ArgList[i].Type);
+    ArgListTy.push_back(ArgList[i].Ty);
+
+  Result = FunctionType::get(Result, ArgListTy, isVarArg);
+  return false;
+}
+
+/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
+/// other structs.
+bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
+  SmallVector<Type*, 8> Elts;
+  if (ParseStructBody(Elts)) return true;
+  
+  Result = StructType::get(Context, Elts, Packed);
+  return false;
+}
 
-  Result = HandleUpRefs(FunctionType::get(Result.get(),
-                                                ArgListTy, isVarArg));
+/// ParseStructDefinition - Parse a struct in a 'type' definition.
+bool LLParser::ParseStructDefinition(StructType *STy) {
+  // The definition must be a (possibly) struct type or the 'opaque' keyword.
+  // If we have opaque, just return without filling in the definition for the
+  // struct.  This counts as a definition as far as the .ll file goes.
+  if (EatIfPresent(lltok::kw_opaque))
+    return false;
+  
+  bool isPacked = false;
+  if (EatIfPresent(lltok::less)) {
+    if (Lex.getKind() != lltok::lbrace)
+      return TokError("expected packed struct type in definition");
+    isPacked = true;
+  }
+  
+  SmallVector<Type*, 8> Body;
+  if (ParseStructBody(Body) ||
+      (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
+    return true;
+  
+  STy->setBody(Body, isPacked);
   return false;
 }
 
+
 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
-///   TypeRec
+///   StructType
 ///     ::= '{' '}'
-///     ::= '{' TypeRec (',' TypeRec)* '}'
+///     ::= '{' Type (',' Type)* '}'
 ///     ::= '<' '{' '}' '>'
-///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
-bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
+///     ::= '<' '{' Type (',' Type)* '}' '>'
+bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
   assert(Lex.getKind() == lltok::lbrace);
   Lex.Lex(); // Consume the '{'
 
-  if (EatIfPresent(lltok::rbrace)) {
-    Result = StructType::get(Context, Packed);
+  // Handle the empty struct.
+  if (EatIfPresent(lltok::rbrace))
     return false;
-  }
 
-  std::vector<PATypeHolder> ParamsList;
   LocTy EltTyLoc = Lex.getLoc();
-  if (ParseTypeRec(Result)) return true;
-  ParamsList.push_back(Result);
+  Type *Ty = 0;
+  if (ParseType(Ty)) return true;
+  Body.push_back(Ty);
 
-  if (Result->isVoidTy())
-    return Error(EltTyLoc, "struct element can not have void type");
-  if (!StructType::isValidElementType(Result))
+  if (!StructType::isValidElementType(Ty))
     return Error(EltTyLoc, "invalid element type for struct");
 
   while (EatIfPresent(lltok::comma)) {
     EltTyLoc = Lex.getLoc();
-    if (ParseTypeRec(Result)) return true;
+    if (ParseType(Ty)) return true;
 
-    if (Result->isVoidTy())
-      return Error(EltTyLoc, "struct element can not have void type");
-    if (!StructType::isValidElementType(Result))
+    if (!StructType::isValidElementType(Ty))
       return Error(EltTyLoc, "invalid element type for struct");
 
-    ParamsList.push_back(Result);
+    Body.push_back(Ty);
   }
 
-  if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
-    return true;
-
-  std::vector<const Type*> ParamsListTy;
-  for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
-    ParamsListTy.push_back(ParamsList[i].get());
-  Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
-  return false;
+  return ParseToken(lltok::rbrace, "expected '}' at end of struct");
 }
 
 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
 /// token has already been consumed.
-///   TypeRec
+///   Type
 ///     ::= '[' APSINTVAL 'x' Types ']'
 ///     ::= '<' APSINTVAL 'x' Types '>'
-bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
+bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
       Lex.getAPSIntVal().getBitWidth() > 64)
     return TokError("expected number in address space");
@@ -1644,11 +1541,8 @@
       return true;
 
   LocTy TypeLoc = Lex.getLoc();
-  PATypeHolder EltTy(Type::getVoidTy(Context));
-  if (ParseTypeRec(EltTy)) return true;
-
-  if (EltTy->isVoidTy())
-    return Error(TypeLoc, "array and vector element type cannot be void");
+  Type *EltTy = 0;
+  if (ParseType(EltTy)) return true;
 
   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
                  "expected end of sequential type"))
@@ -1665,7 +1559,7 @@
   } else {
     if (!ArrayType::isValidElementType(EltTy))
       return Error(TypeLoc, "invalid array element type");
-    Result = HandleUpRefs(ArrayType::get(EltTy, Size));
+    Result = ArrayType::get(EltTy, Size);
   }
   return false;
 }
@@ -1770,7 +1664,7 @@
   }
 
   // Don't make placeholders with invalid type.
-  if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
+  if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
     P.Error(Loc, "invalid use of a non-first-class type");
     return 0;
   }
@@ -1811,7 +1705,7 @@
     return 0;
   }
 
-  if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
+  if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
     P.Error(Loc, "invalid use of a non-first-class type");
     return 0;
   }
@@ -2131,7 +2025,7 @@
   case lltok::kw_inttoptr:
   case lltok::kw_ptrtoint: {
     unsigned Opc = Lex.getUIntVal();
-    PATypeHolder DestTy(Type::getVoidTy(Context));
+    Type *DestTy = 0;
     Constant *SrcVal;
     Lex.Lex();
     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
@@ -2414,9 +2308,9 @@
 }
 
 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
-  PATypeHolder Type(Type::getVoidTy(Context));
-  return ParseType(Type) ||
-         ParseGlobalValue(Type, V);
+  Type *Ty = 0;
+  return ParseType(Ty) ||
+         ParseGlobalValue(Ty, V);
 }
 
 /// ParseGlobalValueVector
@@ -2562,8 +2456,7 @@
     return false;
   case ValID::t_Undef:
     // FIXME: LabelTy should not be a first-class type.
-    if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
-        !Ty->isOpaqueTy())
+    if (!Ty->isFirstClassType() || Ty->isLabelTy())
       return Error(ID.Loc, "invalid type for undef constant");
     V = UndefValue::get(Ty);
     return false;
@@ -2587,17 +2480,17 @@
   }
 }
 
-bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
+bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState *PFS) {
   V = 0;
   ValID ID;
-  return ParseValID(ID, &PFS) ||
-         ConvertValIDToValue(Ty, ID, V, &PFS);
+  return ParseValID(ID, PFS) ||
+         ConvertValIDToValue(Ty, ID, V, PFS);
 }
 
-bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
-  PATypeHolder T(Type::getVoidTy(Context));
-  return ParseType(T) ||
-         ParseValue(T, V, PFS);
+bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
+  Type *Ty = 0;
+  return ParseType(Ty) ||
+         ParseValue(Ty, V, PFS);
 }
 
 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
@@ -2623,7 +2516,7 @@
 
   unsigned Visibility, RetAttrs;
   CallingConv::ID CC;
-  PATypeHolder RetType(Type::getVoidTy(Context));
+  Type *RetType = 0;
   LocTy RetTypeLoc = Lex.getLoc();
   if (ParseOptionalLinkage(Linkage) ||
       ParseOptionalVisibility(Visibility) ||
@@ -2660,8 +2553,7 @@
     return Error(LinkageLoc, "invalid function linkage type");
   }
 
-  if (!FunctionType::isValidReturnType(RetType) ||
-      RetType->isOpaqueTy())
+  if (!FunctionType::isValidReturnType(RetType))
     return Error(RetTypeLoc, "invalid function return type");
 
   LocTy NameLoc = Lex.getLoc();
@@ -2684,7 +2576,7 @@
   if (Lex.getKind() != lltok::lparen)
     return TokError("expected '(' in function argument list");
 
-  std::vector<ArgInfo> ArgList;
+  SmallVector<ArgInfo, 8> ArgList;
   bool isVarArg;
   unsigned FuncAttrs;
   std::string Section;
@@ -2693,7 +2585,7 @@
   bool UnnamedAddr;
   LocTy UnnamedAddrLoc;
 
-  if (ParseArgumentList(ArgList, isVarArg, false) ||
+  if (ParseArgumentList(ArgList, isVarArg) ||
       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
                          &UnnamedAddrLoc) ||
       ParseOptionalAttrs(FuncAttrs, 2) ||
@@ -2719,7 +2611,7 @@
     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
 
   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
-    ParamTypeList.push_back(ArgList[i].Type);
+    ParamTypeList.push_back(ArgList[i].Ty);
     if (ArgList[i].Attrs != Attribute::None)
       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
   }
@@ -3053,7 +2945,7 @@
 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
                        PerFunctionState &PFS) {
-  PATypeHolder Ty(Type::getVoidTy(Context));
+  Type *Ty = 0;
   if (ParseType(Ty, true /*void allowed*/)) return true;
 
   if (Ty->isVoidTy()) {
@@ -3191,7 +3083,7 @@
   LocTy CallLoc = Lex.getLoc();
   unsigned RetAttrs, FnAttrs;
   CallingConv::ID CC;
-  PATypeHolder RetType(Type::getVoidTy(Context));
+  Type *RetType = 0;
   LocTy RetTypeLoc;
   ValID CalleeID;
   SmallVector<ParamInfo, 16> ArgList;
@@ -3369,8 +3261,9 @@
 ///   ::= CastOpc TypeAndValue 'to' Type
 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
                          unsigned Opc) {
-  LocTy Loc;  Value *Op;
-  PATypeHolder DestTy(Type::getVoidTy(Context));
+  LocTy Loc;
+  Value *Op;
+  Type *DestTy = 0;
   if (ParseTypeAndValue(Op, Loc, PFS) ||
       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
       ParseType(DestTy))
@@ -3409,7 +3302,7 @@
 ///   ::= 'va_arg' TypeAndValue ',' Type
 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
   Value *Op;
-  PATypeHolder EltTy(Type::getVoidTy(Context));
+  Type *EltTy = 0;
   LocTy TypeLoc;
   if (ParseTypeAndValue(Op, PFS) ||
       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
@@ -3481,11 +3374,10 @@
 /// ParsePHI
 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
-  PATypeHolder Ty(Type::getVoidTy(Context));
+  Type *Ty = 0;  LocTy TypeLoc;
   Value *Op0, *Op1;
-  LocTy TypeLoc = Lex.getLoc();
 
-  if (ParseType(Ty) ||
+  if (ParseType(Ty, TypeLoc) ||
       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
       ParseValue(Ty, Op0, PFS) ||
       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
@@ -3531,7 +3423,7 @@
                          bool isTail) {
   unsigned RetAttrs, FnAttrs;
   CallingConv::ID CC;
-  PATypeHolder RetType(Type::getVoidTy(Context));
+  Type *RetType = 0;
   LocTy RetTypeLoc;
   ValID CalleeID;
   SmallVector<ParamInfo, 16> ArgList;
@@ -3620,10 +3512,10 @@
 /// ParseAlloc
 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
-  PATypeHolder Ty(Type::getVoidTy(Context));
   Value *Size = 0;
   LocTy SizeLoc;
   unsigned Alignment = 0;
+  Type *Ty = 0;
   if (ParseType(Ty)) return true;
 
   bool AteExtraComma = false;
@@ -3787,12 +3679,7 @@
     }
     
     Value *V = 0;
-    PATypeHolder Ty(Type::getVoidTy(Context));
-    ValID ID;
-    if (ParseType(Ty) || ParseValID(ID, PFS) ||
-        ConvertValIDToValue(Ty, ID, V, PFS))
-      return true;
-    
+    if (ParseTypeAndValue(V, PFS)) return true;
     Elts.push_back(V);
   } while (EatIfPresent(lltok::comma));
 

Modified: llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.h (original)
+++ llvm/branches/type-system-rewrite/lib/AsmParser/LLParser.h Mon Jun 20 01:45:54 2011
@@ -18,6 +18,7 @@
 #include "llvm/Module.h"
 #include "llvm/Type.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/Support/ValueHandle.h"
 #include <map>
 
@@ -32,6 +33,7 @@
   class GlobalValue;
   class MDString;
   class MDNode;
+  class StructType;
 
   /// ValID - Represents a reference of a definition of some sort with no type.
   /// There are several cases where we have to parse the value but where the
@@ -93,33 +95,13 @@
     };
     DenseMap<Instruction*, std::vector<MDRef> > ForwardRefInstMetadata;
 
-    // Type resolution handling data structures.
-    std::map<std::string, std::pair<PATypeHolder, LocTy> > ForwardRefTypes;
-    std::map<unsigned, std::pair<PATypeHolder, LocTy> > ForwardRefTypeIDs;
-    std::vector<PATypeHolder> NumberedTypes;
+    // Type resolution handling data structures.  The location is set when we
+    // have processed a use of the type but not a definition yet.
+    StringMap<std::pair<StructType*, LocTy> > NamedTypes;
+    std::vector<std::pair<StructType*, LocTy> > NumberedTypes;
+    
     std::vector<TrackingVH<MDNode> > NumberedMetadata;
     std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> > ForwardRefMDNodes;
-    struct UpRefRecord {
-      /// Loc - This is the location of the upref.
-      LocTy Loc;
-
-      /// NestingLevel - The number of nesting levels that need to be popped
-      /// before this type is resolved.
-      unsigned NestingLevel;
-
-      /// LastContainedTy - This is the type at the current binding level for
-      /// the type.  Every time we reduce the nesting level, this gets updated.
-      const Type *LastContainedTy;
-
-      /// UpRefTy - This is the actual opaque type that the upreference is
-      /// represented with.
-      OpaqueType *UpRefTy;
-
-      UpRefRecord(LocTy L, unsigned NL, OpaqueType *URTy)
-        : Loc(L), NestingLevel(NL), LastContainedTy((Type*)URTy),
-          UpRefTy(URTy) {}
-    };
-    std::vector<UpRefRecord> UpRefs;
 
     // Global Value reference information.
     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
@@ -137,7 +119,7 @@
       M(m) {}
     bool Run();
 
-    LLVMContext& getContext() { return Context; }
+    LLVMContext &getContext() { return Context; }
 
   private:
 
@@ -222,16 +204,17 @@
     bool ParseMDNodeID(MDNode *&Result, unsigned &SlotNo);
 
     // Type Parsing.
-    bool ParseType(PATypeHolder &Result, bool AllowVoid = false);
-    bool ParseType(PATypeHolder &Result, LocTy &Loc, bool AllowVoid = false) {
+    bool ParseType(Type *&Result, bool AllowVoid = false);
+    bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
       Loc = Lex.getLoc();
       return ParseType(Result, AllowVoid);
     }
-    bool ParseTypeRec(PATypeHolder &H);
-    bool ParseStructType(PATypeHolder &H, bool Packed);
-    bool ParseArrayVectorType(PATypeHolder &H, bool isVector);
-    bool ParseFunctionType(PATypeHolder &Result);
-    PATypeHolder HandleUpRefs(const Type *Ty);
+    bool ParseAnonStructType(Type *&Result, bool Packed);
+    bool ParseStructBody(SmallVectorImpl<Type*> &Body);
+    bool ParseStructDefinition(StructType *STy);
+
+    bool ParseArrayVectorType(Type *&Result, bool isVector);
+    bool ParseFunctionType(Type *&Result);
 
     // Function Semantic Analysis.
     class PerFunctionState {
@@ -278,14 +261,20 @@
     bool ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
                              PerFunctionState *PFS);
 
-    bool ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS);
+    bool ParseValue(const Type *Ty, Value *&V, PerFunctionState *PFS);
+    bool ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
+      return ParseValue(Ty, V, &PFS);
+    }
     bool ParseValue(const Type *Ty, Value *&V, LocTy &Loc,
                     PerFunctionState &PFS) {
       Loc = Lex.getLoc();
-      return ParseValue(Ty, V, PFS);
+      return ParseValue(Ty, V, &PFS);
     }
 
-    bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS);
+    bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
+    bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
+      return ParseTypeAndValue(V, &PFS);
+    }
     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
       Loc = Lex.getLoc();
       return ParseTypeAndValue(V, PFS);
@@ -321,14 +310,13 @@
     // Function Parsing.
     struct ArgInfo {
       LocTy Loc;
-      PATypeHolder Type;
+      Type *Ty;
       unsigned Attrs;
       std::string Name;
-      ArgInfo(LocTy L, PATypeHolder Ty, unsigned Attr, const std::string &N)
-        : Loc(L), Type(Ty), Attrs(Attr), Name(N) {}
+      ArgInfo(LocTy L, Type *ty, unsigned Attr, const std::string &N)
+        : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
     };
-    bool ParseArgumentList(std::vector<ArgInfo> &ArgList,
-                           bool &isVarArg, bool inType);
+    bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
     bool ParseFunctionBody(Function &Fn);
     bool ParseBasicBlock(PerFunctionState &PFS);

Modified: llvm/branches/type-system-rewrite/lib/Bitcode/Writer/BitcodeWriter.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Bitcode/Writer/BitcodeWriter.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Bitcode/Writer/BitcodeWriter.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Bitcode/Writer/BitcodeWriter.cpp Mon Jun 20 01:45:54 2011
@@ -21,7 +21,6 @@
 #include "llvm/Instructions.h"
 #include "llvm/Module.h"
 #include "llvm/Operator.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/ValueSymbolTable.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -29,6 +28,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Program.h"
 #include <cctype>
+#include <map>
 using namespace llvm;
 
 /// These are manifest constants used by the bitcode writer. They do not need to
@@ -101,13 +101,16 @@
   }
 }
 
-static void WriteStringRecord(unsigned Code, const std::string &Str,
+static void WriteStringRecord(unsigned Code, StringRef Str,
                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
   SmallVector<unsigned, 64> Vals;
 
   // Code: [strchar x N]
-  for (unsigned i = 0, e = Str.size(); i != e; ++i)
+  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
+    if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
+      AbbrevToUse = 0;
     Vals.push_back(Str[i]);
+  }
 
   // Emit the finished record.
   Stream.EmitRecord(Code, Vals, AbbrevToUse);
@@ -151,7 +154,7 @@
 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
 
-  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
+  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
   SmallVector<uint64_t, 64> TypeVals;
 
   // Abbrev for TYPE_CODE_POINTER.
@@ -172,15 +175,32 @@
                             Log2_32_Ceil(VE.getTypes().size()+1)));
   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
 
-  // Abbrev for TYPE_CODE_STRUCT.
+  // Abbrev for TYPE_CODE_STRUCT_ANON.
+  Abbv = new BitCodeAbbrev();
+  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
+                            Log2_32_Ceil(VE.getTypes().size()+1)));
+  unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
+
+  // Abbrev for TYPE_CODE_STRUCT_NAME.
+  Abbv = new BitCodeAbbrev();
+  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
+  unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
+
+  // Abbrev for TYPE_CODE_STRUCT_NAMED.
   Abbv = new BitCodeAbbrev();
-  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
+  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
                             Log2_32_Ceil(VE.getTypes().size()+1)));
-  unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
+  unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
 
+  
   // Abbrev for TYPE_CODE_ARRAY.
   Abbv = new BitCodeAbbrev();
   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
@@ -202,16 +222,15 @@
 
     switch (T->getTypeID()) {
     default: llvm_unreachable("Unknown type!");
-    case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
-    case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
-    case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
-    case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
-    case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
+    case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;   break;
+    case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;  break;
+    case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE; break;
+    case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80; break;
+    case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128; break;
     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
-    case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
-    case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
-    case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
-    case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
+    case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;  break;
+    case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA; break;
+    case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX; break;
     case Type::IntegerTyID:
       // INTEGER: [width]
       Code = bitc::TYPE_CODE_INTEGER;
@@ -242,13 +261,24 @@
     case Type::StructTyID: {
       const StructType *ST = cast<StructType>(T);
       // STRUCT: [ispacked, eltty x N]
-      Code = bitc::TYPE_CODE_STRUCT;
       TypeVals.push_back(ST->isPacked());
       // Output all of the element types.
       for (StructType::element_iterator I = ST->element_begin(),
            E = ST->element_end(); I != E; ++I)
         TypeVals.push_back(VE.getTypeID(*I));
-      AbbrevToUse = StructAbbrev;
+      
+      if (ST->isAnonymous()) {
+        Code = bitc::TYPE_CODE_STRUCT_ANON;
+        AbbrevToUse = StructAnonAbbrev;
+      } else {
+        Code = bitc::TYPE_CODE_STRUCT_ANON;
+        AbbrevToUse = StructNamedAbbrev;
+
+        // Emit the name if it is present.
+        if (!ST->getName().empty())
+          WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
+                            StructNameAbbrev, Stream);
+      }
       break;
     }
     case Type::ArrayTyID: {
@@ -1274,46 +1304,6 @@
   Stream.ExitBlock();
 }
 
-/// WriteTypeSymbolTable - Emit a block for the specified type symtab.
-static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
-                                 const ValueEnumerator &VE,
-                                 BitstreamWriter &Stream) {
-  if (TST.empty()) return;
-
-  Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
-
-  // 7-bit fixed width VST_CODE_ENTRY strings.
-  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
-  Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
-                            Log2_32_Ceil(VE.getTypes().size()+1)));
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
-  unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
-
-  SmallVector<unsigned, 64> NameVals;
-
-  for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
-       TI != TE; ++TI) {
-    // TST_ENTRY: [typeid, namechar x N]
-    NameVals.push_back(VE.getTypeID(TI->second));
-
-    const std::string &Str = TI->first;
-    bool is7Bit = true;
-    for (unsigned i = 0, e = Str.size(); i != e; ++i) {
-      NameVals.push_back((unsigned char)Str[i]);
-      if (Str[i] & 128)
-        is7Bit = false;
-    }
-
-    // Emit the finished record.
-    Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
-    NameVals.clear();
-  }
-
-  Stream.ExitBlock();
-}
-
 // Emit blockinfo, which defines the standard abbreviations etc.
 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
   // We only want to emit block info records for blocks that have multiple
@@ -1517,9 +1507,6 @@
   // Emit metadata.
   WriteModuleMetadataStore(M, Stream);
 
-  // Emit the type symbol table information.
-  WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
-
   // Emit names for globals/functions etc.
   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
 

Modified: llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.cpp Mon Jun 20 01:45:54 2011
@@ -17,7 +17,6 @@
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Module.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/ValueSymbolTable.h"
 #include "llvm/Instructions.h"
 #include <algorithm>
@@ -59,9 +58,6 @@
        I != E; ++I)
     EnumerateValue(I->getAliasee());
 
-  // Enumerate types used by the type symbol table.
-  EnumerateTypeSymbolTable(M->getTypeSymbolTable());
-
   // Insert constants and metadata that are named at module level into the slot 
   // pool so that the module symbol table can refer to them...
   EnumerateValueSymbolTable(M->getValueSymbolTable());
@@ -109,78 +105,12 @@
 
   // Optimize constant ordering.
   OptimizeConstants(FirstConstant, Values.size());
-
-  OptimizeTypes();
-
-  // Now that we rearranged the type table, rebuild TypeMap.
-  for (unsigned i = 0, e = Types.size(); i != e; ++i)
-    TypeMap[Types[i]] = i+1;
-}
-
-struct TypeAndDeps {
-  const Type *Ty;
-  unsigned NumDeps;
-};
-
-static int CompareByDeps(const void *a, const void *b) {
-  const TypeAndDeps &ta = *(const TypeAndDeps*) a;
-  const TypeAndDeps &tb = *(const TypeAndDeps*) b;
-  return ta.NumDeps - tb.NumDeps;
 }
 
-static void VisitType(const Type *Ty, SmallPtrSet<const Type*, 16> &Visited,
-                      std::vector<const Type*> &Out) {
-  if (Visited.count(Ty))
-    return;
-
-  Visited.insert(Ty);
-
-  for (Type::subtype_iterator I2 = Ty->subtype_begin(),
-         E2 = Ty->subtype_end(); I2 != E2; ++I2) {
-    const Type *InnerType = I2->get();
-    VisitType(InnerType, Visited, Out);
-  }
-
-  Out.push_back(Ty);
-}
-
-void ValueEnumerator::OptimizeTypes(void) {
-  // If the types form a DAG, this will compute a topological sort and
-  // no forward references will be needed when reading them in.
-  // If there are cycles, this is a simple but reasonable heuristic for
-  // the minimum feedback arc set problem.
-  const unsigned NumTypes = Types.size();
-  std::vector<TypeAndDeps> TypeDeps;
-  TypeDeps.resize(NumTypes);
-
-  for (unsigned I = 0; I < NumTypes; ++I) {
-    const Type *Ty = Types[I];
-    TypeDeps[I].Ty = Ty;
-    TypeDeps[I].NumDeps = 0;
-  }
-
-  for (unsigned I = 0; I < NumTypes; ++I) {
-    const Type *Ty = TypeDeps[I].Ty;
-    for (Type::subtype_iterator I2 = Ty->subtype_begin(),
-           E2 = Ty->subtype_end(); I2 != E2; ++I2) {
-      const Type *InnerType = I2->get();
-      unsigned InnerIndex = TypeMap.lookup(InnerType) - 1;
-      TypeDeps[InnerIndex].NumDeps++;
-    }
-  }
-  array_pod_sort(TypeDeps.begin(), TypeDeps.end(), CompareByDeps);
-
-  SmallPtrSet<const Type*, 16> Visited;
-  Types.clear();
-  Types.reserve(NumTypes);
-  for (unsigned I = 0; I < NumTypes; ++I) {
-    VisitType(TypeDeps[I].Ty, Visited, Types);
-  }
-}
 
 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
-  assert (I != InstructionMap.end() && "Instruction is not mapped!");
+  assert(I != InstructionMap.end() && "Instruction is not mapped!");
   return I->second;
 }
 
@@ -235,14 +165,6 @@
 }
 
 
-/// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
-/// table.
-void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
-  for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
-       TI != TE; ++TI)
-    EnumerateType(TI->second);
-}
-
 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
 /// table into the values table.
 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {

Modified: llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.h (original)
+++ llvm/branches/type-system-rewrite/lib/Bitcode/Writer/ValueEnumerator.h Mon Jun 20 01:45:54 2011
@@ -30,7 +30,6 @@
 class MDNode;
 class NamedMDNode;
 class AttrListPtr;
-class TypeSymbolTable;
 class ValueSymbolTable;
 class MDSymbolTable;
 
@@ -135,7 +134,6 @@
 
 private:
   void OptimizeConstants(unsigned CstStart, unsigned CstEnd);
-  void OptimizeTypes();
     
   void EnumerateMDNodeOperands(const MDNode *N);
   void EnumerateMetadata(const Value *MD);
@@ -146,7 +144,6 @@
   void EnumerateOperandType(const Value *V);
   void EnumerateAttributes(const AttrListPtr &PAL);
   
-  void EnumerateTypeSymbolTable(const TypeSymbolTable &ST);
   void EnumerateValueSymbolTable(const ValueSymbolTable &ST);
   void EnumerateNamedMetadata(const Module *M);
 };

Modified: llvm/branches/type-system-rewrite/lib/CodeGen/ShadowStackGC.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/CodeGen/ShadowStackGC.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/CodeGen/ShadowStackGC.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/CodeGen/ShadowStackGC.cpp Mon Jun 20 01:45:54 2011
@@ -45,7 +45,7 @@
 
     /// StackEntryTy - Abstract type of a link in the shadow stack.
     ///
-    const StructType *StackEntryTy;
+    StructType *StackEntryTy;
 
     /// Roots - GC roots in the current function. Each is a pair of the
     /// intrinsic call and its corresponding alloca.
@@ -215,14 +215,10 @@
                        Metadata.begin(), NumMeta)
   };
 
-  Constant *FrameMap =
-    ConstantStruct::get(StructType::get(DescriptorElts[0]->getType(),
-                                        DescriptorElts[1]->getType(), NULL),
-                        DescriptorElts);
-
-  std::string TypeName("gc_map.");
-  TypeName += utostr(NumMeta);
-  F.getParent()->addTypeName(TypeName, FrameMap->getType());
+  Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
+  StructType *STy = StructType::createNamed("gc_map."+utostr(NumMeta), EltTys);
+  
+  Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
 
   // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
   //        that, short of multithreaded LLVM, it should be safe; all that is
@@ -250,17 +246,12 @@
 
 const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
   // doInitialization creates the generic version of this type.
-  std::vector<const Type*> EltTys;
+  std::vector<Type*> EltTys;
   EltTys.push_back(StackEntryTy);
   for (size_t I = 0; I != Roots.size(); I++)
     EltTys.push_back(Roots[I].second->getAllocatedType());
-  Type *Ty = StructType::get(F.getContext(), EltTys);
-
-  std::string TypeName("gc_stackentry.");
-  TypeName += F.getName();
-  F.getParent()->addTypeName(TypeName, Ty);
-
-  return Ty;
+  
+  return StructType::createNamed("gc_stackentry."+F.getName().str(), EltTys);
 }
 
 /// doInitialization - If this module uses the GC intrinsics, find them now. If
@@ -271,13 +262,12 @@
   //   int32_t NumMeta;  // Number of metadata descriptors. May be < NumRoots.
   //   void *Meta[];     // May be absent for roots without metadata.
   // };
-  std::vector<const Type*> EltTys;
+  std::vector<Type*> EltTys;
   // 32 bits is ok up to a 32GB stack frame. :)
   EltTys.push_back(Type::getInt32Ty(M.getContext()));
   // Specifies length of variable length array. 
   EltTys.push_back(Type::getInt32Ty(M.getContext()));
-  StructType *FrameMapTy = StructType::get(M.getContext(), EltTys);
-  M.addTypeName("gc_map", FrameMapTy);
+  StructType *FrameMapTy = StructType::createNamed("gc_map", EltTys);
   PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
 
   // struct StackEntry {
@@ -285,18 +275,14 @@
   //   FrameMap *Map;          // Pointer to constant FrameMap.
   //   void *Roots[];          // Stack roots (in-place array, so we pretend).
   // };
-  OpaqueType *RecursiveTy = OpaqueType::get(M.getContext());
-
+  
+  StackEntryTy = StructType::createNamed(M.getContext(), "gc_stackentry");
+  
   EltTys.clear();
-  EltTys.push_back(PointerType::getUnqual(RecursiveTy));
+  EltTys.push_back(PointerType::getUnqual(StackEntryTy));
   EltTys.push_back(FrameMapPtrTy);
-  PATypeHolder LinkTyH = StructType::get(M.getContext(), EltTys);
-
-  RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
-  StackEntryTy = cast<StructType>(LinkTyH.get());
+  StackEntryTy->setBody(EltTys);
   const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
-  M.addTypeName("gc_stackentry", LinkTyH.get());  // FIXME: Is this safe from
-                                                  //        a FunctionPass?
 
   // Get the root chain if it already exists.
   Head = M.getGlobalVariable("llvm_gc_root_chain");

Modified: llvm/branches/type-system-rewrite/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp Mon Jun 20 01:45:54 2011
@@ -78,7 +78,6 @@
   case Type::FunctionTyID:return 'M';
   case Type::StructTyID:  return 'T';
   case Type::ArrayTyID:   return 'A';
-  case Type::OpaqueTyID:  return 'O';
   default: return 'U';
   }
 }

Modified: llvm/branches/type-system-rewrite/lib/Target/CBackend/CBackend.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Target/CBackend/CBackend.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Target/CBackend/CBackend.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Target/CBackend/CBackend.cpp Mon Jun 20 01:45:54 2011
@@ -20,7 +20,6 @@
 #include "llvm/Instructions.h"
 #include "llvm/Pass.h"
 #include "llvm/PassManager.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/IntrinsicInst.h"
 #include "llvm/InlineAsm.h"
@@ -69,29 +68,6 @@
       PrivateGlobalPrefix = "";
     }
   };
-  /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
-  /// any unnamed structure types that are used by the program, and merges
-  /// external functions with the same name.
-  ///
-  class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
-  public:
-    static char ID;
-    CBackendNameAllUsedStructsAndMergeFunctions()
-        : ModulePass(ID) {
-          initializeFindUsedTypesPass(*PassRegistry::getPassRegistry());
-        }
-    void getAnalysisUsage(AnalysisUsage &AU) const {
-      AU.addRequired<FindUsedTypes>();
-    }
-
-    virtual const char *getPassName() const {
-      return "C backend type canonicalizer";
-    }
-
-    virtual bool runOnModule(Module &M);
-  };
-
-  char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
 
   /// CWriter - This class is the main chunk of code that converts an LLVM
   /// module to a C translation unit.
@@ -104,7 +80,7 @@
     const MCAsmInfo* TAsm;
     MCContext *TCtx;
     const TargetData* TD;
-    std::map<const Type *, std::string> TypeNames;
+    
     std::map<const ConstantFP *, unsigned> FPConstantMap;
     std::set<Function*> intrinsicPrototypesAlreadyGenerated;
     std::set<const Argument*> ByValParams;
@@ -113,6 +89,10 @@
     DenseMap<const Value*, unsigned> AnonValueNumbers;
     unsigned NextAnonValueNumber;
 
+    /// UnnamedStructIDs - This contains a unique ID for each struct that is
+    /// either anonymous or has no name.
+    DenseMap<const StructType*, unsigned> UnnamedStructIDs;
+    
   public:
     static char ID;
     explicit CWriter(formatted_raw_ostream &o)
@@ -158,9 +138,9 @@
       delete TCtx;
       delete TAsm;
       FPConstantMap.clear();
-      TypeNames.clear();
       ByValParams.clear();
       intrinsicPrototypesAlreadyGenerated.clear();
+      UnnamedStructIDs.clear();
       return false;
     }
 
@@ -177,6 +157,8 @@
                                               const AttrListPtr &PAL,
                                               const PointerType *Ty);
 
+    std::string getStructName(const StructType *ST);
+    
     /// writeOperandDeref - Print the result of dereferencing the specified
     /// operand with '*'.  This is equivalent to printing '*' then using
     /// writeOperand, but avoids excess syntax in some cases.
@@ -206,8 +188,8 @@
 
     void lowerIntrinsics(Function &F);
 
-    void printModuleTypes(const TypeSymbolTable &ST);
-    void printContainedStructs(const Type *Ty, std::set<const Type *> &);
+    void printModuleTypes();
+    void printContainedStructs(const Type *Ty, SmallPtrSet<const Type *, 16> &);
     void printFloatingPointConstants(Function &F);
     void printFloatingPointConstants(const Constant *C);
     void printFunctionSignature(const Function *F, bool Prototype);
@@ -351,6 +333,7 @@
 char CWriter::ID = 0;
 
 
+
 static std::string CBEMangle(const std::string &S) {
   std::string Result;
 
@@ -366,90 +349,14 @@
   return Result;
 }
 
-
-/// This method inserts names for any unnamed structure types that are used by
-/// the program, and removes names from structure types that are not used by the
-/// program.
-///
-bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
-  // Get a set of types that are used by the program...
-  SetVector<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
-
-  // Loop over the module symbol table, removing types from UT that are
-  // already named, and removing names for types that are not used.
-  //
-  TypeSymbolTable &TST = M.getTypeSymbolTable();
-  for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
-       TI != TE; ) {
-    TypeSymbolTable::iterator I = TI++;
-
-    // If this isn't a struct or array type, remove it from our set of types
-    // to name. This simplifies emission later.
-    if (!I->second->isStructTy() && !I->second->isOpaqueTy() &&
-        !I->second->isArrayTy()) {
-      TST.remove(I);
-    } else {
-      // If this is not used, remove it from the symbol table.
-      if (!UT.count(I->second))
-        TST.remove(I);
-      else
-        UT.remove(I->second); // Only keep one name for this type.
-    }
-  }
-
-  // UT now contains types that are not named.  Loop over it, naming
-  // structure types.
-  //
-  bool Changed = false;
-  unsigned RenameCounter = 0;
-  for (SetVector<const Type *>::const_iterator I = UT.begin(), E = UT.end();
-       I != E; ++I)
-    if ((*I)->isStructTy() || (*I)->isArrayTy()) {
-      while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
-        ++RenameCounter;
-      Changed = true;
-    }
-
-
-  // Loop over all external functions and globals.  If we have two with
-  // identical names, merge them.
-  // FIXME: This code should disappear when we don't allow values with the same
-  // names when they have different types!
-  std::map<std::string, GlobalValue*> ExtSymbols;
-  for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
-    Function *GV = I++;
-    if (GV->isDeclaration() && GV->hasName()) {
-      std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
-        = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
-      if (!X.second) {
-        // Found a conflict, replace this global with the previous one.
-        GlobalValue *OldGV = X.first->second;
-        GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
-        GV->eraseFromParent();
-        Changed = true;
-      }
-    }
-  }
-  // Do the same for globals.
-  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
-       I != E;) {
-    GlobalVariable *GV = I++;
-    if (GV->isDeclaration() && GV->hasName()) {
-      std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
-        = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
-      if (!X.second) {
-        // Found a conflict, replace this global with the previous one.
-        GlobalValue *OldGV = X.first->second;
-        GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
-        GV->eraseFromParent();
-        Changed = true;
-      }
-    }
-  }
-
-  return Changed;
+std::string CWriter::getStructName(const StructType *ST) {
+  if (!ST->isAnonymous() && !ST->getName().empty())
+    return CBEMangle("l_"+ST->getName().str());
+  
+  return "l_unnamed_" + utostr(UnnamedStructIDs[ST]);
 }
 
+
 /// printStructReturnPointerFunctionType - This is like printType for a struct
 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
 /// print it as "Struct (*)(...)", for struct return functions.
@@ -463,7 +370,7 @@
   bool PrintedType = false;
 
   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
-  const Type *RetTy = cast<PointerType>(I->get())->getElementType();
+  const Type *RetTy = cast<PointerType>(*I)->getElementType();
   unsigned Idx = 1;
   for (++I, ++Idx; I != E; ++I, ++Idx) {
     if (PrintedType)
@@ -551,12 +458,6 @@
     return Out;
   }
 
-  // Check to see if the type is named.
-  if (!IgnoreName || Ty->isOpaqueTy()) {
-    std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
-    if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
-  }
-
   switch (Ty->getTypeID()) {
   case Type::FunctionTyID: {
     const FunctionType *FTy = cast<FunctionType>(Ty);
@@ -591,6 +492,11 @@
   }
   case Type::StructTyID: {
     const StructType *STy = cast<StructType>(Ty);
+    
+    // Check to see if the type is named.
+    if (!IgnoreName)
+      return Out << getStructName(STy) << ' ' << NameSoFar;
+    
     Out << NameSoFar + " {\n";
     unsigned Idx = 0;
     for (StructType::element_iterator I = STy->element_begin(),
@@ -631,12 +537,6 @@
     return Out << "; }";
   }
 
-  case Type::OpaqueTyID: {
-    std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
-    assert(TypeNames.find(Ty) == TypeNames.end());
-    TypeNames[Ty] = TyName;
-    return Out << TyName << ' ' << NameSoFar;
-  }
   default:
     llvm_unreachable("Unhandled case in getTypeProps!");
   }
@@ -1820,8 +1720,8 @@
         << "/* End Module asm statements */\n";
   }
 
-  // Loop over the symbol table, emitting all named constants...
-  printModuleTypes(M.getTypeSymbolTable());
+  // Loop over the symbol table, emitting all named constants.
+  printModuleTypes();
 
   // Global variable declarations...
   if (!M.global_empty()) {
@@ -2085,11 +1985,10 @@
 }
 
 
-
 /// printSymbolTable - Run through symbol table looking for type names.  If a
 /// type name is found, emit its declaration...
 ///
-void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
+void CWriter::printModuleTypes() {
   Out << "/* Helper union for bitcasts */\n";
   Out << "typedef union {\n";
   Out << "  unsigned int Int32;\n";
@@ -2098,46 +1997,42 @@
   Out << "  double Double;\n";
   Out << "} llvmBitCastUnion;\n";
 
-  // We are only interested in the type plane of the symbol table.
-  TypeSymbolTable::const_iterator I   = TST.begin();
-  TypeSymbolTable::const_iterator End = TST.end();
+  // Get all of the struct types used in the module.
+  std::vector<StructType*> StructTypes;
+  TheModule->findUsedStructTypes(StructTypes);
 
-  // If there are no type names, exit early.
-  if (I == End) return;
+  if (StructTypes.empty()) return;
 
-  // Print out forward declarations for structure types before anything else!
   Out << "/* Structure forward decls */\n";
-  for (; I != End; ++I) {
-    std::string Name = "struct " + CBEMangle("l_"+I->first);
-    Out << Name << ";\n";
-    TypeNames.insert(std::make_pair(I->second, Name));
-  }
 
-  Out << '\n';
+  unsigned NextTypeID = 0;
+  
+  // If any of them are missing names, add a unique ID to UnnamedStructIDs.
+  // Print out forward declarations for structure types.
+  for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
+    StructType *ST = StructTypes[i];
 
-  // Now we can print out typedefs.  Above, we guaranteed that this can only be
-  // for struct or opaque types.
-  Out << "/* Typedefs */\n";
-  for (I = TST.begin(); I != End; ++I) {
-    std::string Name = CBEMangle("l_"+I->first);
-    Out << "typedef ";
-    printType(Out, I->second, false, Name);
-    Out << ";\n";
+    if (ST->isAnonymous() || ST->getName().empty())
+      UnnamedStructIDs[ST] = NextTypeID++;
+
+    std::string Name = getStructName(ST);
+
+    Out << "typedef struct " << Name << ' ' << Name << ";\n";
   }
 
   Out << '\n';
 
-  // Keep track of which structures have been printed so far...
-  std::set<const Type *> StructPrinted;
+  // Keep track of which structures have been printed so far.
+  SmallPtrSet<const Type *, 16> StructPrinted;
 
   // Loop over all structures then push them into the stack so they are
   // printed in the correct order.
   //
   Out << "/* Structure contents */\n";
-  for (I = TST.begin(); I != End; ++I)
-    if (I->second->isStructTy() || I->second->isArrayTy())
+  for (unsigned i = 0, e = StructTypes.size(); i != e; ++i)
+    if (StructTypes[i]->isStructTy())
       // Only print out used types!
-      printContainedStructs(I->second, StructPrinted);
+      printContainedStructs(StructTypes[i], StructPrinted);
 }
 
 // Push the struct onto the stack and recursively push all structs
@@ -2146,7 +2041,7 @@
 // TODO:  Make this work properly with vector types
 //
 void CWriter::printContainedStructs(const Type *Ty,
-                                    std::set<const Type*> &StructPrinted) {
+                                SmallPtrSet<const Type *, 16> &StructPrinted) {
   // Don't walk through pointers.
   if (Ty->isPointerTy() || Ty->isPrimitiveType() || Ty->isIntegerTy())
     return;
@@ -2156,14 +2051,13 @@
        E = Ty->subtype_end(); I != E; ++I)
     printContainedStructs(*I, StructPrinted);
 
-  if (Ty->isStructTy() || Ty->isArrayTy()) {
+  if (const StructType *ST = dyn_cast<StructType>(Ty)) {
     // Check to see if we have already printed this struct.
-    if (StructPrinted.insert(Ty).second) {
-      // Print structure type out.
-      std::string Name = TypeNames[Ty];
-      printType(Out, Ty, false, Name, true);
-      Out << ";\n\n";
-    }
+    if (!StructPrinted.insert(Ty)) return;
+    
+    // Print structure type out.
+    printType(Out, ST, false, getStructName(ST), true);
+    Out << ";\n\n";
   }
 }
 
@@ -3565,7 +3459,6 @@
   PM.add(createGCLoweringPass());
   PM.add(createLowerInvokePass());
   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
-  PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
   PM.add(new CWriter(o));
   PM.add(createGCInfoDeleter());
   return false;

Modified: llvm/branches/type-system-rewrite/lib/Target/CppBackend/CPPBackend.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Target/CppBackend/CPPBackend.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Target/CppBackend/CPPBackend.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Target/CppBackend/CPPBackend.cpp Mon Jun 20 01:45:54 2011
@@ -22,7 +22,6 @@
 #include "llvm/Module.h"
 #include "llvm/Pass.h"
 #include "llvm/PassManager.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -32,7 +31,7 @@
 #include "llvm/Config/config.h"
 #include <algorithm>
 #include <set>
-
+#include <map>
 using namespace llvm;
 
 static cl::opt<std::string>
@@ -188,26 +187,11 @@
   case Type::ArrayTyID:    return "array_";
   case Type::PointerTyID:  return "ptr_";
   case Type::VectorTyID:   return "packed_";
-  case Type::OpaqueTyID:   return "opaque_";
   default:                 return "other_";
   }
   return "unknown_";
 }
 
-// Looks up the type in the symbol table and returns a pointer to its name or
-// a null pointer if it wasn't found. Note that this isn't the same as the
-// Mode::getTypeName function which will return an empty string, not a null
-// pointer if the name is not found.
-static const std::string *
-findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
-  TypeSymbolTable::const_iterator TI = ST.begin();
-  TypeSymbolTable::const_iterator TE = ST.end();
-  for (;TI != TE; ++TI)
-    if (TI->second == Ty)
-      return &(TI->first);
-  return 0;
-}
-
 void CppWriter::error(const std::string& msg) {
   report_fatal_error(msg);
 }
@@ -379,18 +363,20 @@
   case Type::StructTyID:      prefix = "StructTy_"; break;
   case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
   case Type::PointerTyID:     prefix = "PointerTy_"; break;
-  case Type::OpaqueTyID:      prefix = "OpaqueTy_"; break;
   case Type::VectorTyID:      prefix = "VectorTy_"; break;
   default:                    prefix = "OtherTy_"; break; // prevent breakage
   }
 
   // See if the type has a name in the symboltable and build accordingly
-  const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
   std::string name;
-  if (tName)
-    name = std::string(prefix) + *tName;
-  else
-    name = std::string(prefix) + utostr(uniqueNum++);
+  if (const StructType *STy = dyn_cast<StructType>(Ty))
+    if (STy->hasName())
+      name = STy->getName();
+  
+  if (name.empty())
+    name = utostr(uniqueNum++);
+  
+  name = std::string(prefix) + name;
   sanitize(name);
 
   // Save the name
@@ -585,9 +571,18 @@
       Out << ");";
       nl(Out);
     }
-    Out << "StructType* " << typeName << " = StructType::get("
-        << "mod->getContext(), "
-        << typeName << "_fields, /*isPacked=*/"
+    
+    Out << "StructType *" << typeName << " = ";
+    if (ST->isAnonymous()) {
+      Out << "StructType::get(" << "mod->getContext(), ";
+    } else {
+      Out << "StructType::createNamed(mod->getContext(), \"";
+      printEscapedString(ST->getName());
+      Out << "\");";
+      nl(Out);
+      Out << typeName << "->setBody(";
+    }
+    Out << typeName << "_fields, /*isPacked=*/"
         << (ST->isPacked() ? "true" : "false") << ");";
     nl(Out);
     break;
@@ -625,25 +620,10 @@
     nl(Out);
     break;
   }
-  case Type::OpaqueTyID: {
-    Out << "OpaqueType* " << typeName;
-    Out << " = OpaqueType::get(mod->getContext());";
-    nl(Out);
-    break;
-  }
   default:
     error("Invalid TypeID");
   }
 
-  // If the type had a name, make sure we recreate it.
-  const std::string* progTypeName =
-    findTypeName(TheModule->getTypeSymbolTable(),Ty);
-  if (progTypeName) {
-    Out << "mod->addTypeName(\"" << *progTypeName << "\", "
-        << typeName << ");";
-    nl(Out);
-  }
-
   // Pop us off the type stack
   TypeStack.pop_back();
 
@@ -666,7 +646,6 @@
     case Type::StructTyID:   Out << "StructType"; break;
     case Type::VectorTyID:   Out << "VectorType"; break;
     case Type::PointerTyID:  Out << "PointerType"; break;
-    case Type::OpaqueTyID:   Out << "OpaqueType"; break;
     default:                 Out << "NoSuchDerivedType"; break;
     }
     Out << ">(" << I->second << "_fwd.get());";
@@ -691,26 +670,7 @@
 }
 
 void CppWriter::printTypes(const Module* M) {
-  // Walk the symbol table and print out all its types
-  const TypeSymbolTable& symtab = M->getTypeSymbolTable();
-  for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
-       TI != TE; ++TI) {
-
-    // For primitive types and types already defined, just add a name
-    TypeMap::const_iterator TNI = TypeNames.find(TI->second);
-    if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
-        TNI != TypeNames.end()) {
-      Out << "mod->addTypeName(\"";
-      printEscapedString(TI->first);
-      Out << "\", " << getCppName(TI->second) << ");";
-      nl(Out);
-      // For everything else, define the type
-    } else {
-      printType(TI->second);
-    }
-  }
-
-  // Add all of the global variables to the value table...
+  // Add all of the global variables to the value table.
   for (Module::const_global_iterator I = TheModule->global_begin(),
          E = TheModule->global_end(); I != E; ++I) {
     if (I->hasInitializer())
@@ -1954,8 +1914,8 @@
   Out << "}\n";
 }
 
-void CppWriter::printType(const std::string& fname,
-                          const std::string& typeName) {
+void CppWriter::printType(const std::string &fname,
+                          const std::string &typeName) {
   const Type* Ty = TheModule->getTypeByName(typeName);
   if (!Ty) {
     error(std::string("Type '") + typeName + "' not found in input module");

Modified: llvm/branches/type-system-rewrite/lib/Target/TargetData.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Target/TargetData.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Target/TargetData.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Target/TargetData.cpp Mon Jun 20 01:45:54 2011
@@ -313,52 +313,16 @@
 
 namespace {
 
-class StructLayoutMap : public AbstractTypeUser {
+class StructLayoutMap {
   typedef DenseMap<const StructType*, StructLayout*> LayoutInfoTy;
   LayoutInfoTy LayoutInfo;
 
-  void RemoveEntry(LayoutInfoTy::iterator I, bool WasAbstract) {
-    I->second->~StructLayout();
-    free(I->second);
-    if (WasAbstract)
-      I->first->removeAbstractTypeUser(this);
-    LayoutInfo.erase(I);
-  }
-
-
-  /// refineAbstractType - The callback method invoked when an abstract type is
-  /// resolved to another type.  An object must override this method to update
-  /// its internal state to reference NewType instead of OldType.
-  ///
-  virtual void refineAbstractType(const DerivedType *OldTy,
-                                  const Type *) {
-    LayoutInfoTy::iterator I = LayoutInfo.find(cast<const StructType>(OldTy));
-    assert(I != LayoutInfo.end() && "Using type but not in map?");
-    RemoveEntry(I, true);
-  }
-
-  /// typeBecameConcrete - The other case which AbstractTypeUsers must be aware
-  /// of is when a type makes the transition from being abstract (where it has
-  /// clients on its AbstractTypeUsers list) to concrete (where it does not).
-  /// This method notifies ATU's when this occurs for a type.
-  ///
-  virtual void typeBecameConcrete(const DerivedType *AbsTy) {
-    LayoutInfoTy::iterator I = LayoutInfo.find(cast<const StructType>(AbsTy));
-    assert(I != LayoutInfo.end() && "Using type but not in map?");
-    RemoveEntry(I, true);
-  }
-
 public:
   virtual ~StructLayoutMap() {
     // Remove any layouts.
-    for (LayoutInfoTy::iterator
-           I = LayoutInfo.begin(), E = LayoutInfo.end(); I != E; ++I) {
-      const Type *Key = I->first;
+    for (LayoutInfoTy::iterator I = LayoutInfo.begin(), E = LayoutInfo.end();
+         I != E; ++I) {
       StructLayout *Value = I->second;
-
-      if (Key->isAbstract())
-        Key->removeAbstractTypeUser(this);
-
       Value->~StructLayout();
       free(Value);
     }
@@ -367,7 +331,10 @@
   void InvalidateEntry(const StructType *Ty) {
     LayoutInfoTy::iterator I = LayoutInfo.find(Ty);
     if (I == LayoutInfo.end()) return;
-    RemoveEntry(I, Ty->isAbstract());
+    
+    I->second->~StructLayout();
+    free(I->second);
+    LayoutInfo.erase(I);
   }
 
   StructLayout *&operator[](const StructType *STy) {
@@ -404,9 +371,6 @@
 
   new (L) StructLayout(Ty, *this);
 
-  if (Ty->isAbstract())
-    Ty->addAbstractTypeUser(STM);
-
   return L;
 }
 

Modified: llvm/branches/type-system-rewrite/lib/Transforms/IPO/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Transforms/IPO/CMakeLists.txt?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Transforms/IPO/CMakeLists.txt (original)
+++ llvm/branches/type-system-rewrite/lib/Transforms/IPO/CMakeLists.txt Mon Jun 20 01:45:54 2011
@@ -2,7 +2,6 @@
   ArgumentPromotion.cpp
   ConstantMerge.cpp
   DeadArgumentElimination.cpp
-  DeadTypeElimination.cpp
   ExtractGV.cpp
   FunctionAttrs.cpp
   GlobalDCE.cpp

Modified: llvm/branches/type-system-rewrite/lib/Transforms/IPO/DeadTypeElimination.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Transforms/IPO/DeadTypeElimination.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Transforms/IPO/DeadTypeElimination.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Transforms/IPO/DeadTypeElimination.cpp Mon Jun 20 01:45:54 2011
@@ -1,112 +1,5 @@
 //===- DeadTypeElimination.cpp - Eliminate unused types for symbol table --===//
-//
-//                     The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This pass is used to cleanup the output of GCC.  It eliminate names for types
-// that are unused in the entire translation unit, using the FindUsedTypes pass.
-//
-//===----------------------------------------------------------------------===//
 
-#define DEBUG_TYPE "deadtypeelim"
-#include "llvm/Transforms/IPO.h"
-#include "llvm/Analysis/FindUsedTypes.h"
-#include "llvm/Module.h"
-#include "llvm/TypeSymbolTable.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/ADT/Statistic.h"
-using namespace llvm;
-
-STATISTIC(NumKilled, "Number of unused typenames removed from symtab");
-
-namespace {
-  struct DTE : public ModulePass {
-    static char ID; // Pass identification, replacement for typeid
-    DTE() : ModulePass(ID) {
-      initializeDTEPass(*PassRegistry::getPassRegistry());
-    }
-
-    // doPassInitialization - For this pass, it removes global symbol table
-    // entries for primitive types.  These are never used for linking in GCC and
-    // they make the output uglier to look at, so we nuke them.
-    //
-    // Also, initialize instance variables.
-    //
-    bool runOnModule(Module &M);
-
-    // getAnalysisUsage - This function needs FindUsedTypes to do its job...
-    //
-    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
-      AU.addRequired<FindUsedTypes>();
-    }
-  };
-}
-
-char DTE::ID = 0;
-INITIALIZE_PASS_BEGIN(DTE, "deadtypeelim", "Dead Type Elimination",
-                      false, false)
-INITIALIZE_PASS_DEPENDENCY(FindUsedTypes)
-INITIALIZE_PASS_END(DTE, "deadtypeelim", "Dead Type Elimination", false, false)
-
-ModulePass *llvm::createDeadTypeEliminationPass() {
-  return new DTE();
-}
-
-
-// ShouldNukeSymtabEntry - Return true if this module level symbol table entry
-// should be eliminated.
-//
-static inline bool ShouldNukeSymtabEntry(const Type *Ty){
-  // Nuke all names for primitive types!
-  if (Ty->isPrimitiveType() || Ty->isIntegerTy()) 
-    return true;
-
-  // Nuke all pointers to primitive types as well...
-  if (const PointerType *PT = dyn_cast<PointerType>(Ty))
-    if (PT->getElementType()->isPrimitiveType() ||
-        PT->getElementType()->isIntegerTy()) 
-      return true;
-
-  return false;
-}
-
-// run - For this pass, it removes global symbol table entries for primitive
-// types.  These are never used for linking in GCC and they make the output
-// uglier to look at, so we nuke them.  Also eliminate types that are never used
-// in the entire program as indicated by FindUsedTypes.
-//
-bool DTE::runOnModule(Module &M) {
-  bool Changed = false;
-
-  TypeSymbolTable &ST = M.getTypeSymbolTable();
-  const SetVector<const Type*> &T = getAnalysis<FindUsedTypes>().getTypes();
-  std::set<const Type*> UsedTypes(T.begin(), T.end());
-
-  // Check the symbol table for superfluous type entries...
-  //
-  // Grab the 'type' plane of the module symbol...
-  TypeSymbolTable::iterator TI = ST.begin();
-  TypeSymbolTable::iterator TE = ST.end();
-  while ( TI != TE ) {
-    // If this entry should be unconditionally removed, or if we detect that
-    // the type is not used, remove it.
-    const Type *RHS = TI->second;
-    if (ShouldNukeSymtabEntry(RHS) || !UsedTypes.count(RHS)) {
-      ST.remove(TI++);
-      ++NumKilled;
-      Changed = true;
-    } else {
-      ++TI;
-      // We only need to leave one name for each type.
-      UsedTypes.erase(RHS);
-    }
-  }
-
-  return Changed;
-}
-
-// vim: sw=2
+#if 0
+#error remove me.
+#endif

Modified: llvm/branches/type-system-rewrite/lib/Transforms/IPO/IPO.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Transforms/IPO/IPO.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Transforms/IPO/IPO.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Transforms/IPO/IPO.cpp Mon Jun 20 01:45:54 2011
@@ -63,10 +63,6 @@
   unwrap(PM)->add(createDeadArgEliminationPass());
 }
 
-void LLVMAddDeadTypeEliminationPass(LLVMPassManagerRef PM) {
-  unwrap(PM)->add(createDeadTypeEliminationPass());
-}
-
 void LLVMAddFunctionAttrsPass(LLVMPassManagerRef PM) {
   unwrap(PM)->add(createFunctionAttrsPass());
 }

Modified: llvm/branches/type-system-rewrite/lib/Transforms/IPO/MergeFunctions.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Transforms/IPO/MergeFunctions.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Transforms/IPO/MergeFunctions.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Transforms/IPO/MergeFunctions.cpp Mon Jun 20 01:45:54 2011
@@ -218,7 +218,6 @@
     llvm_unreachable("Unknown type!");
     // Fall through in Release mode.
   case Type::IntegerTyID:
-  case Type::OpaqueTyID:
   case Type::VectorTyID:
     // Ty1 == Ty2 would have returned true earlier.
     return false;

Modified: llvm/branches/type-system-rewrite/lib/Transforms/IPO/StripSymbols.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Transforms/IPO/StripSymbols.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Transforms/IPO/StripSymbols.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Transforms/IPO/StripSymbols.cpp Mon Jun 20 01:45:54 2011
@@ -28,8 +28,8 @@
 #include "llvm/Pass.h"
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/ValueSymbolTable.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/Transforms/Utils/Local.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallPtrSet.h"
 using namespace llvm;
 
@@ -174,13 +174,19 @@
   }
 }
 
-// Strip the symbol table of its names.
-static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) {
-  for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) {
-    if (PreserveDbgInfo && StringRef(TI->first).startswith("llvm.dbg"))
-      ++TI;
-    else
-      ST.remove(TI++);
+// Strip any named types of their names.
+static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
+  std::vector<StructType*> StructTypes;
+  M.findUsedStructTypes(StructTypes);
+
+  for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
+    StructType *STy = StructTypes[i];
+    if (STy->isAnonymous() || STy->getName().empty()) continue;
+    
+    if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
+      continue;
+
+    STy->setName("");
   }
 }
 
@@ -221,7 +227,7 @@
   }
   
   // Remove all names from types.
-  StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo);
+  StripTypeNames(M, PreserveDbgInfo);
 
   return true;
 }

Modified: llvm/branches/type-system-rewrite/lib/Transforms/Utils/CloneModule.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Transforms/Utils/CloneModule.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Transforms/Utils/CloneModule.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Transforms/Utils/CloneModule.cpp Mon Jun 20 01:45:54 2011
@@ -15,7 +15,6 @@
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Module.h"
 #include "llvm/DerivedTypes.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/Constant.h"
 #include "llvm/Transforms/Utils/ValueMapper.h"
 using namespace llvm;
@@ -32,20 +31,13 @@
   return CloneModule(M, VMap);
 }
 
-Module *llvm::CloneModule(const Module *M,
-                          ValueToValueMapTy &VMap) {
-  // First off, we need to create the new module...
+Module *llvm::CloneModule(const Module *M, ValueToValueMapTy &VMap) {
+  // First off, we need to create the new module.
   Module *New = new Module(M->getModuleIdentifier(), M->getContext());
   New->setDataLayout(M->getDataLayout());
   New->setTargetTriple(M->getTargetTriple());
   New->setModuleInlineAsm(M->getModuleInlineAsm());
-
-  // Copy all of the type symbol table entries over.
-  const TypeSymbolTable &TST = M->getTypeSymbolTable();
-  for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
-       TI != TE; ++TI)
-    New->addTypeName(TI->first, TI->second);
-  
+   
   // Copy all of the dependent libraries over.
   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
     New->addLibrary(*I);

Modified: llvm/branches/type-system-rewrite/lib/Transforms/Utils/LowerInvoke.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/Transforms/Utils/LowerInvoke.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/Transforms/Utils/LowerInvoke.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/Transforms/Utils/LowerInvoke.cpp Mon Jun 20 01:45:54 2011
@@ -66,7 +66,7 @@
     Constant *AbortFn;
 
     // Used for expensive EH support.
-    const Type *JBLinkTy;
+    StructType *JBLinkTy;
     GlobalVariable *JBListHead;
     Constant *SetJmpFn, *LongJmpFn, *StackSaveFn, *StackRestoreFn;
     bool useExpensiveEHSupport;
@@ -120,24 +120,16 @@
 // doInitialization - Make sure that there is a prototype for abort in the
 // current module.
 bool LowerInvoke::doInitialization(Module &M) {
-  const Type *VoidPtrTy =
-          Type::getInt8PtrTy(M.getContext());
+  const Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
   if (useExpensiveEHSupport) {
     // Insert a type for the linked list of jump buffers.
     unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
     JBSize = JBSize ? JBSize : 200;
-    const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
+    Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
 
-    { // The type is recursive, so use a type holder.
-      std::vector<const Type*> Elements;
-      Elements.push_back(JmpBufTy);
-      OpaqueType *OT = OpaqueType::get(M.getContext());
-      Elements.push_back(PointerType::getUnqual(OT));
-      PATypeHolder JBLType(StructType::get(M.getContext(), Elements));
-      OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
-      JBLinkTy = JBLType.get();
-      M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
-    }
+    JBLinkTy = StructType::createNamed(M.getContext(), "llvm.sjljeh.jmpbufty");
+    Type *Elts[] = { JmpBufTy, PointerType::getUnqual(JBLinkTy) };
+    JBLinkTy->setBody(Elts);
 
     const Type *PtrJBList = PointerType::getUnqual(JBLinkTy);
 

Modified: llvm/branches/type-system-rewrite/lib/VMCore/AsmWriter.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/AsmWriter.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/AsmWriter.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/AsmWriter.cpp Mon Jun 20 01:45:54 2011
@@ -26,8 +26,7 @@
 #include "llvm/Operator.h"
 #include "llvm/Module.h"
 #include "llvm/ValueSymbolTable.h"
-#include "llvm/TypeSymbolTable.h"
-#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/STLExtras.h"
@@ -143,72 +142,57 @@
 /// TypePrinting - Type printing machinery.
 namespace {
 class TypePrinting {
-  DenseMap<const Type *, std::string> TypeNames;
   TypePrinting(const TypePrinting &);   // DO NOT IMPLEMENT
   void operator=(const TypePrinting&);  // DO NOT IMPLEMENT
 public:
-  TypePrinting() {}
-  ~TypePrinting() {}
-  
-  void clear() {
-    TypeNames.clear();
-  }
-  
-  void print(const Type *Ty, raw_ostream &OS, bool IgnoreTopLevelName = false);
+
+  /// NamedTypes - The named types that are used by the current module.
+  std::vector<StructType*> NamedTypes;
   
-  void printAtLeastOneLevel(const Type *Ty, raw_ostream &OS) {
-    print(Ty, OS, true);
-  }
+  /// NumberedTypes - The numbered types, along with their value.
+  DenseMap<StructType*, unsigned> NumberedTypes;
   
-  /// hasTypeName - Return true if the type has a name in TypeNames, false
-  /// otherwise.
-  bool hasTypeName(const Type *Ty) const {
-    return TypeNames.count(Ty);
-  }
 
+  TypePrinting() {}
+  ~TypePrinting() {}
   
-  /// addTypeName - Add a name for the specified type if it doesn't already have
-  /// one.  This name will be printed instead of the structural version of the
-  /// type in order to make the output more concise.
-  void addTypeName(const Type *Ty, const std::string &N) {
-    TypeNames.insert(std::make_pair(Ty, N));
-  }
+  void incorporateTypes(const Module &M);
   
-private:
-  void CalcTypeName(const Type *Ty, SmallVectorImpl<const Type *> &TypeStack,
-                    raw_ostream &OS, bool IgnoreTopLevelName = false);
+  void print(Type *Ty, raw_ostream &OS);
+  
+  void printStructBody(StructType *Ty, raw_ostream &OS);
 };
 } // end anonymous namespace.
 
-/// CalcTypeName - Write the specified type to the specified raw_ostream, making
-/// use of type names or up references to shorten the type name where possible.
-void TypePrinting::CalcTypeName(const Type *Ty,
-                                SmallVectorImpl<const Type *> &TypeStack,
-                                raw_ostream &OS, bool IgnoreTopLevelName) {
-  // Check to see if the type is named.
-  if (!IgnoreTopLevelName) {
-    DenseMap<const Type *, std::string> &TM = TypeNames;
-    DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
-    if (I != TM.end()) {
-      OS << I->second;
-      return;
-    }
-  }
 
-  // Check to see if the Type is already on the stack...
-  unsigned Slot = 0, CurSize = TypeStack.size();
-  while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
-
-  // This is another base case for the recursion.  In this case, we know
-  // that we have looped back to a type that we have previously visited.
-  // Generate the appropriate upreference to handle this.
-  if (Slot < CurSize) {
-    OS << '\\' << unsigned(CurSize-Slot);     // Here's the upreference
-    return;
+void TypePrinting::incorporateTypes(const Module &M) {
+  M.findUsedStructTypes(NamedTypes);
+  
+  // The list of struct types we got back includes all the struct types, split
+  // the unnamed ones out to a numbering and remove the anonymous structs.
+  unsigned NextNumber = 0;
+  
+  std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
+  for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
+    StructType *STy = *I;
+    
+    // Ignore anonymous types.
+    if (STy->isAnonymous())
+      continue;
+    
+    if (STy->getName().empty())
+      NumberedTypes[STy] = NextNumber++;
+    else
+      *NextToUse++ = STy;
   }
+    
+  NamedTypes.erase(NextToUse, NamedTypes.end());
+}
 
-  TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
 
+/// CalcTypeName - Write the specified type to the specified raw_ostream, making
+/// use of type names or up references to shorten the type name where possible.
+void TypePrinting::print(Type *Ty, raw_ostream &OS) {
   switch (Ty->getTypeID()) {
   case Type::VoidTyID:      OS << "void"; break;
   case Type::FloatTyID:     OS << "float"; break;
@@ -221,257 +205,100 @@
   case Type::X86_MMXTyID:   OS << "x86_mmx"; break;
   case Type::IntegerTyID:
     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
-    break;
+    return;
 
   case Type::FunctionTyID: {
-    const FunctionType *FTy = cast<FunctionType>(Ty);
-    CalcTypeName(FTy->getReturnType(), TypeStack, OS);
+    FunctionType *FTy = cast<FunctionType>(Ty);
+    print(FTy->getReturnType(), OS);
     OS << " (";
     for (FunctionType::param_iterator I = FTy->param_begin(),
          E = FTy->param_end(); I != E; ++I) {
       if (I != FTy->param_begin())
         OS << ", ";
-      CalcTypeName(*I, TypeStack, OS);
+      print(*I, OS);
     }
     if (FTy->isVarArg()) {
       if (FTy->getNumParams()) OS << ", ";
       OS << "...";
     }
     OS << ')';
-    break;
+    return;
   }
   case Type::StructTyID: {
-    const StructType *STy = cast<StructType>(Ty);
-    if (STy->isPacked())
-      OS << '<';
-    OS << '{';
-    for (StructType::element_iterator I = STy->element_begin(),
-         E = STy->element_end(); I != E; ++I) {
-      OS << ' ';
-      CalcTypeName(*I, TypeStack, OS);
-      if (llvm::next(I) == STy->element_end())
-        OS << ' ';
-      else
-        OS << ',';
-    }
-    OS << '}';
-    if (STy->isPacked())
-      OS << '>';
-    break;
+    StructType *STy = cast<StructType>(Ty);
+    
+    if (STy->isAnonymous())
+      return printStructBody(STy, OS);
+
+    if (!STy->getName().empty())
+      return PrintLLVMName(OS, STy->getName(), LocalPrefix);
+    
+    DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
+    if (I != NumberedTypes.end())
+      OS << '%' << I->second;
+    else  // Not enumerated, print the hex address.
+      OS << "%\"type 0x" << STy << '\"';
+    return;
   }
   case Type::PointerTyID: {
-    const PointerType *PTy = cast<PointerType>(Ty);
-    CalcTypeName(PTy->getElementType(), TypeStack, OS);
+    PointerType *PTy = cast<PointerType>(Ty);
+    print(PTy->getElementType(), OS);
     if (unsigned AddressSpace = PTy->getAddressSpace())
       OS << " addrspace(" << AddressSpace << ')';
     OS << '*';
-    break;
+    return;
   }
   case Type::ArrayTyID: {
-    const ArrayType *ATy = cast<ArrayType>(Ty);
+    ArrayType *ATy = cast<ArrayType>(Ty);
     OS << '[' << ATy->getNumElements() << " x ";
-    CalcTypeName(ATy->getElementType(), TypeStack, OS);
+    print(ATy->getElementType(), OS);
     OS << ']';
-    break;
+    return;
   }
   case Type::VectorTyID: {
-    const VectorType *PTy = cast<VectorType>(Ty);
+    VectorType *PTy = cast<VectorType>(Ty);
     OS << "<" << PTy->getNumElements() << " x ";
-    CalcTypeName(PTy->getElementType(), TypeStack, OS);
+    print(PTy->getElementType(), OS);
     OS << '>';
-    break;
+    return;
   }
-  case Type::OpaqueTyID:
-    OS << "opaque";
-    break;
   default:
     OS << "<unrecognized-type>";
-    break;
+    return;
   }
-
-  TypeStack.pop_back();       // Remove self from stack.
 }
 
-/// printTypeInt - The internal guts of printing out a type that has a
-/// potentially named portion.
-///
-void TypePrinting::print(const Type *Ty, raw_ostream &OS,
-                         bool IgnoreTopLevelName) {
-  // Check to see if the type is named.
-  if (!IgnoreTopLevelName) {
-    DenseMap<const Type*, std::string>::iterator I = TypeNames.find(Ty);
-    if (I != TypeNames.end()) {
-      OS << I->second;
-      return;
+void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
+  if (STy->isOpaque()) {
+    OS << "opaque";
+    return;
+  }
+  
+  if (STy->isPacked())
+    OS << '<';
+  
+  if (STy->getNumElements() == 0) {
+    OS << "{}";
+  } else {
+    StructType::element_iterator I = STy->element_begin();
+    OS << "{ ";
+    print(*I++, OS);
+    for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
+      OS << ", ";
+      print(*I, OS);
     }
+  
+    OS << " }";
   }
-
-  // Otherwise we have a type that has not been named but is a derived type.
-  // Carefully recurse the type hierarchy to print out any contained symbolic
-  // names.
-  SmallVector<const Type *, 16> TypeStack;
-  std::string TypeName;
-
-  raw_string_ostream TypeOS(TypeName);
-  CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
-  OS << TypeOS.str();
-
-  // Cache type name for later use.
-  if (!IgnoreTopLevelName)
-    TypeNames.insert(std::make_pair(Ty, TypeOS.str()));
+  if (STy->isPacked())
+    OS << '>';
 }
 
-namespace {
-  class TypeFinder {
-    // To avoid walking constant expressions multiple times and other IR
-    // objects, we keep several helper maps.
-    DenseSet<const Value*> VisitedConstants;
-    DenseSet<const Type*> VisitedTypes;
-
-    TypePrinting &TP;
-    std::vector<const Type*> &NumberedTypes;
-  public:
-    TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
-      : TP(tp), NumberedTypes(numberedTypes) {}
-
-    void Run(const Module &M) {
-      // Get types from the type symbol table.  This gets opaque types referened
-      // only through derived named types.
-      const TypeSymbolTable &ST = M.getTypeSymbolTable();
-      for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
-           TI != E; ++TI)
-        IncorporateType(TI->second);
-
-      // Get types from global variables.
-      for (Module::const_global_iterator I = M.global_begin(),
-           E = M.global_end(); I != E; ++I) {
-        IncorporateType(I->getType());
-        if (I->hasInitializer())
-          IncorporateValue(I->getInitializer());
-      }
-
-      // Get types from aliases.
-      for (Module::const_alias_iterator I = M.alias_begin(),
-           E = M.alias_end(); I != E; ++I) {
-        IncorporateType(I->getType());
-        IncorporateValue(I->getAliasee());
-      }
 
-      // Get types from functions.
-      for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
-        IncorporateType(FI->getType());
-
-        for (Function::const_iterator BB = FI->begin(), E = FI->end();
-             BB != E;++BB)
-          for (BasicBlock::const_iterator II = BB->begin(),
-               E = BB->end(); II != E; ++II) {
-            const Instruction &I = *II;
-            // Incorporate the type of the instruction and all its operands.
-            IncorporateType(I.getType());
-            for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
-                 OI != OE; ++OI)
-              IncorporateValue(*OI);
-          }
-      }
-    }
 
-  private:
-    void IncorporateType(const Type *Ty) {
-      // Check to see if we're already visited this type.
-      if (!VisitedTypes.insert(Ty).second)
-        return;
-
-      // If this is a structure or opaque type, add a name for the type.
-      if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
-            || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
-        TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
-        NumberedTypes.push_back(Ty);
-      }
-
-      // Recursively walk all contained types.
-      for (Type::subtype_iterator I = Ty->subtype_begin(),
-           E = Ty->subtype_end(); I != E; ++I)
-        IncorporateType(*I);
-    }
-
-    /// IncorporateValue - This method is used to walk operand lists finding
-    /// types hiding in constant expressions and other operands that won't be
-    /// walked in other ways.  GlobalValues, basic blocks, instructions, and
-    /// inst operands are all explicitly enumerated.
-    void IncorporateValue(const Value *V) {
-      if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
-
-      // Already visited?
-      if (!VisitedConstants.insert(V).second)
-        return;
-
-      // Check this type.
-      IncorporateType(V->getType());
-
-      // Look in operands for types.
-      const Constant *C = cast<Constant>(V);
-      for (Constant::const_op_iterator I = C->op_begin(),
-           E = C->op_end(); I != E;++I)
-        IncorporateValue(*I);
-    }
-  };
-} // end anonymous namespace
-
-
-/// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
-/// the specified module to the TypePrinter and all numbered types to it and the
-/// NumberedTypes table.
-static void AddModuleTypesToPrinter(TypePrinting &TP,
-                                    std::vector<const Type*> &NumberedTypes,
-                                    const Module *M) {
-  if (M == 0) return;
-
-  // If the module has a symbol table, take all global types and stuff their
-  // names into the TypeNames map.
-  const TypeSymbolTable &ST = M->getTypeSymbolTable();
-  for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
-       TI != E; ++TI) {
-    const Type *Ty = cast<Type>(TI->second);
-
-    // As a heuristic, don't insert pointer to primitive types, because
-    // they are used too often to have a single useful name.
-    if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
-      const Type *PETy = PTy->getElementType();
-      if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
-          !PETy->isOpaqueTy())
-        continue;
-    }
-
-    // Likewise don't insert primitives either.
-    if (Ty->isIntegerTy() || Ty->isPrimitiveType())
-      continue;
-
-    // Get the name as a string and insert it into TypeNames.
-    std::string NameStr;
-    raw_string_ostream NameROS(NameStr);
-    formatted_raw_ostream NameOS(NameROS);
-    PrintLLVMName(NameOS, TI->first, LocalPrefix);
-    NameOS.flush();
-    TP.addTypeName(Ty, NameStr);
-  }
-
-  // Walk the entire module to find references to unnamed structure and opaque
-  // types.  This is required for correctness by opaque types (because multiple
-  // uses of an unnamed opaque type needs to be referred to by the same ID) and
-  // it shrinks complex recursive structure types substantially in some cases.
-  TypeFinder(TP, NumberedTypes).Run(*M);
-}
-
-
-/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
-/// type, iff there is an entry in the modules symbol table for the specified
-/// type or one of it's component types.
-///
 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
-  TypePrinting Printer;
-  std::vector<const Type*> NumberedTypes;
-  AddModuleTypesToPrinter(Printer, NumberedTypes, M);
-  Printer.print(Ty, OS);
+  // FIXME: remove this function.
+  OS << *Ty;
 }
 
 //===----------------------------------------------------------------------===//
@@ -992,7 +819,7 @@
     // As a special case, print the array as a string if it is an array of
     // i8 with ConstantInt values.
     //
-    const Type *ETy = CA->getType()->getElementType();
+    Type *ETy = CA->getType()->getElementType();
     if (CA->isString()) {
       Out << "c\"";
       PrintEscapedString(CA->getAsString(), Out);
@@ -1049,7 +876,7 @@
   }
 
   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
-    const Type *ETy = CP->getType()->getElementType();
+    Type *ETy = CP->getType()->getElementType();
     assert(CP->getNumOperands() > 0 &&
            "Number of operands for a PackedConst must be > 0");
     Out << '<';
@@ -1247,8 +1074,8 @@
   if (Context == 0) Context = getModuleFromVal(V);
 
   TypePrinting TypePrinter;
-  std::vector<const Type*> NumberedTypes;
-  AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
+  if (Context)
+    TypePrinter.incorporateTypes(*Context);
   if (PrintType) {
     TypePrinter.print(V->getType(), Out);
     Out << ' ';
@@ -1265,14 +1092,14 @@
   const Module *TheModule;
   TypePrinting TypePrinter;
   AssemblyAnnotationWriter *AnnotationWriter;
-  std::vector<const Type*> NumberedTypes;
   
 public:
   inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
                         const Module *M,
                         AssemblyAnnotationWriter *AAW)
     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
-    AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
+    if (M)
+      TypePrinter.incorporateTypes(*M);
   }
 
   void printMDNodeBody(const MDNode *MD);
@@ -1285,7 +1112,7 @@
 
   void writeAllMDNodes();
 
-  void printTypeSymbolTable(const TypeSymbolTable &ST);
+  void printTypeIdentities();
   void printGlobal(const GlobalVariable *GV);
   void printAlias(const GlobalAlias *GV);
   void printFunction(const Function *F);
@@ -1380,9 +1207,7 @@
     Out << " ]";
   }
 
-  // Loop over the symbol table, emitting all id'd types.
-  if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
-  printTypeSymbolTable(M->getTypeSymbolTable());
+  printTypeIdentities();
 
   // Output all globals.
   if (!M->global_empty()) Out << '\n';
@@ -1566,26 +1391,40 @@
   Out << '\n';
 }
 
-void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
+void AssemblyWriter::printTypeIdentities() {
+  if (TypePrinter.NumberedTypes.empty() &&
+      TypePrinter.NamedTypes.empty())
+    return;
+  
+  Out << '\n';
+  
+  // We know all the numbers that each type is used and we know that it is a
+  // dense assignment.  Convert the map to an index table.
+  std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
+  for (DenseMap<StructType*, unsigned>::iterator I = 
+       TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
+       I != E; ++I) {
+    assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
+    NumberedTypes[I->second] = I->first;
+  }
+           
   // Emit all numbered types.
   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
     Out << '%' << i << " = type ";
-
+    
     // Make sure we print out at least one level of the type structure, so
     // that we do not get %2 = type %2
-    TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
+    TypePrinter.printStructBody(NumberedTypes[i], Out);
     Out << '\n';
   }
-
-  // Print the named types.
-  for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
-       TI != TE; ++TI) {
-    PrintLLVMName(Out, TI->first, LocalPrefix);
+  
+  for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
+    PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
     Out << " = type ";
 
     // Make sure we print out at least one level of the type structure, so
     // that we do not get %FILE = type %FILE
-    TypePrinter.printAtLeastOneLevel(TI->second, Out);
+    TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
     Out << '\n';
   }
 }
@@ -1948,9 +1787,9 @@
     }
 
     Operand = CI->getCalledValue();
-    const PointerType    *PTy = cast<PointerType>(Operand->getType());
-    const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
-    const Type         *RetTy = FTy->getReturnType();
+    PointerType *PTy = cast<PointerType>(Operand->getType());
+    FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
+    Type *RetTy = FTy->getReturnType();
     const AttrListPtr &PAL = CI->getAttributes();
 
     if (PAL.getRetAttributes() != Attribute::None)
@@ -1981,9 +1820,9 @@
       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
     Operand = II->getCalledValue();
-    const PointerType    *PTy = cast<PointerType>(Operand->getType());
-    const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
-    const Type         *RetTy = FTy->getReturnType();
+    PointerType *PTy = cast<PointerType>(Operand->getType());
+    FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
+    Type *RetTy = FTy->getReturnType();
     const AttrListPtr &PAL = II->getAttributes();
 
     // Print the calling convention being used.
@@ -2066,7 +1905,7 @@
     // omit the type from all but the first operand.  If the instruction has
     // different type operands (for example br), then they are all printed.
     bool PrintAllTypes = false;
-    const Type *TheType = Operand->getType();
+    Type *TheType = Operand->getType();
 
     // Select, Store and ShuffleVector always print all types.
     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
@@ -2186,7 +2025,7 @@
     OS << "<null Type>";
     return;
   }
-  TypePrinting().print(this, OS);
+  TypePrinting().print(const_cast<Type*>(this), OS);
 }
 
 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
@@ -2242,14 +2081,7 @@
 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
 
 // Type::dump - allow easy printing of Types from the debugger.
-// This one uses type names from the given context module
-void Type::dump(const Module *Context) const {
-  WriteTypeSymbolic(dbgs(), this, Context);
-  dbgs() << '\n';
-}
-
-// Type::dump - allow easy printing of Types from the debugger.
-void Type::dump() const { dump(0); }
+void Type::dump() const { print(dbgs()); }
 
 // Module::dump() - Allow printing of Modules from the debugger.
 void Module::dump() const { print(dbgs(), 0); }

Modified: llvm/branches/type-system-rewrite/lib/VMCore/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/CMakeLists.txt?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/CMakeLists.txt (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/CMakeLists.txt Mon Jun 20 01:45:54 2011
@@ -29,7 +29,6 @@
   PassRegistry.cpp
   PrintModulePass.cpp
   Type.cpp
-  TypeSymbolTable.cpp
   Use.cpp
   User.cpp
   Value.cpp

Modified: llvm/branches/type-system-rewrite/lib/VMCore/ConstantFold.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/ConstantFold.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/ConstantFold.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/ConstantFold.cpp Mon Jun 20 01:45:54 2011
@@ -1443,8 +1443,8 @@
 /// isZeroSizedType - This type is zero sized if its an array or structure of
 /// zero sized types.  The only leaf zero sized type is an empty structure.
 static bool isMaybeZeroSizedType(const Type *Ty) {
-  if (Ty->isOpaqueTy()) return true;  // Can't say.
   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
+    if (STy->isOpaque()) return true;  // Can't say.
 
     // If all of elements have zero size, this does too.
     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Constants.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Constants.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Constants.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Constants.cpp Mon Jun 20 01:45:54 2011
@@ -31,6 +31,7 @@
 #include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/STLExtras.h"
 #include <algorithm>
 #include <cstdarg>
 using namespace llvm;
@@ -980,14 +981,14 @@
 /// destroyConstant - Remove the constant from the constant table...
 ///
 void ConstantAggregateZero::destroyConstant() {
-  getRawType()->getContext().pImpl->AggZeroConstants.remove(this);
+  getType()->getContext().pImpl->AggZeroConstants.remove(this);
   destroyConstantImpl();
 }
 
 /// destroyConstant - Remove the constant from the constant table...
 ///
 void ConstantArray::destroyConstant() {
-  getRawType()->getContext().pImpl->ArrayConstants.remove(this);
+  getType()->getContext().pImpl->ArrayConstants.remove(this);
   destroyConstantImpl();
 }
 
@@ -1051,14 +1052,14 @@
 // destroyConstant - Remove the constant from the constant table...
 //
 void ConstantStruct::destroyConstant() {
-  getRawType()->getContext().pImpl->StructConstants.remove(this);
+  getType()->getContext().pImpl->StructConstants.remove(this);
   destroyConstantImpl();
 }
 
 // destroyConstant - Remove the constant from the constant table...
 //
 void ConstantVector::destroyConstant() {
-  getRawType()->getContext().pImpl->VectorConstants.remove(this);
+  getType()->getContext().pImpl->VectorConstants.remove(this);
   destroyConstantImpl();
 }
 
@@ -1099,7 +1100,7 @@
 // destroyConstant - Remove the constant from the constant table...
 //
 void ConstantPointerNull::destroyConstant() {
-  getRawType()->getContext().pImpl->NullPtrConstants.remove(this);
+  getType()->getContext().pImpl->NullPtrConstants.remove(this);
   destroyConstantImpl();
 }
 
@@ -1114,7 +1115,7 @@
 // destroyConstant - Remove the constant from the constant table.
 //
 void UndefValue::destroyConstant() {
-  getRawType()->getContext().pImpl->UndefValueConstants.remove(this);
+  getType()->getContext().pImpl->UndefValueConstants.remove(this);
   destroyConstantImpl();
 }
 
@@ -1148,7 +1149,7 @@
 // destroyConstant - Remove the constant from the constant table.
 //
 void BlockAddress::destroyConstant() {
-  getFunction()->getRawType()->getContext().pImpl
+  getFunction()->getType()->getContext().pImpl
     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
   getBasicBlock()->AdjustBlockAddressRefCount(-1);
   destroyConstantImpl();
@@ -1922,7 +1923,7 @@
 // destroyConstant - Remove the constant from the constant table...
 //
 void ConstantExpr::destroyConstant() {
-  getRawType()->getContext().pImpl->ExprConstants.remove(this);
+  getType()->getContext().pImpl->ExprConstants.remove(this);
   destroyConstantImpl();
 }
 
@@ -1963,10 +1964,10 @@
   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
   Constant *ToC = cast<Constant>(To);
 
-  LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
+  LLVMContextImpl *pImpl = getType()->getContext().pImpl;
 
   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
-  Lookup.first.first = cast<ArrayType>(getRawType());
+  Lookup.first.first = cast<ArrayType>(getType());
   Lookup.second = this;
 
   std::vector<Constant*> &Values = Lookup.first.second;
@@ -2000,7 +2001,7 @@
   
   Constant *Replacement = 0;
   if (isAllZeros) {
-    Replacement = ConstantAggregateZero::get(getRawType());
+    Replacement = ConstantAggregateZero::get(getType());
   } else {
     // Check to see if we have this array type already.
     bool Exists;
@@ -2051,7 +2052,7 @@
   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
 
   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
-  Lookup.first.first = cast<StructType>(getRawType());
+  Lookup.first.first = cast<StructType>(getType());
   Lookup.second = this;
   std::vector<Constant*> &Values = Lookup.first.second;
   Values.reserve(getNumOperands());  // Build replacement struct.
@@ -2073,11 +2074,11 @@
   }
   Values[OperandToUpdate] = ToC;
   
-  LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
+  LLVMContextImpl *pImpl = getContext().pImpl;
   
   Constant *Replacement = 0;
   if (isAllZeros) {
-    Replacement = ConstantAggregateZero::get(getRawType());
+    Replacement = ConstantAggregateZero::get(getType());
   } else {
     // Check to see if we have this struct type already.
     bool Exists;
@@ -2120,7 +2121,7 @@
     Values.push_back(Val);
   }
   
-  Constant *Replacement = get(cast<VectorType>(getRawType()), Values);
+  Constant *Replacement = get(cast<VectorType>(getType()), Values);
   assert(Replacement != this && "I didn't contain From!");
   
   // Everyone using this now uses the replacement.
@@ -2168,7 +2169,7 @@
                                                &Indices[0], Indices.size());
   } else if (isCast()) {
     assert(getOperand(0) == From && "Cast only has one use!");
-    Replacement = ConstantExpr::getCast(getOpcode(), To, getRawType());
+    Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
   } else if (getOpcode() == Instruction::Select) {
     Constant *C1 = getOperand(0);
     Constant *C2 = getOperand(1);

Modified: llvm/branches/type-system-rewrite/lib/VMCore/ConstantsContext.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/ConstantsContext.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/ConstantsContext.h (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/ConstantsContext.h Mon Jun 20 01:45:54 2011
@@ -570,13 +570,11 @@
 
 template<class ValType, class TypeClass, class ConstantClass,
          bool HasLargeKey = false /*true for arrays and structs*/ >
-class ConstantUniqueMap : public AbstractTypeUser {
+class ConstantUniqueMap {
 public:
   typedef std::pair<const TypeClass*, ValType> MapKey;
   typedef std::map<MapKey, ConstantClass *> MapTy;
   typedef std::map<ConstantClass *, typename MapTy::iterator> InverseMapTy;
-  typedef std::map<const DerivedType*, typename MapTy::iterator>
-    AbstractTypeMapTy;
 private:
   /// Map - This is the main map from the element descriptor to the Constants.
   /// This is the primary way we avoid creating two of the same shape
@@ -589,10 +587,6 @@
   /// through the map with very large keys.
   InverseMapTy InverseMap;
 
-  /// AbstractTypeMap - Map for abstract type constants.
-  ///
-  AbstractTypeMapTy AbstractTypeMap;
-    
 public:
   typename MapTy::iterator map_begin() { return Map.begin(); }
   typename MapTy::iterator map_end() { return Map.end(); }
@@ -629,7 +623,7 @@
     }
       
     typename MapTy::iterator I =
-      Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
+      Map.find(MapKey(static_cast<const TypeClass*>(CP->getType()),
                       ConstantKeyData<ConstantClass>::getValType(CP)));
     if (I == Map.end() || I->second != CP) {
       // FIXME: This should not use a linear scan.  If this gets to be a
@@ -639,24 +633,8 @@
     }
     return I;
   }
-    
-  void AddAbstractTypeUser(const Type *Ty, typename MapTy::iterator I) {
-    // If the type of the constant is abstract, make sure that an entry
-    // exists for it in the AbstractTypeMap.
-    if (Ty->isAbstract()) {
-      const DerivedType *DTy = static_cast<const DerivedType *>(Ty);
-      typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(DTy);
-
-      if (TI == AbstractTypeMap.end()) {
-        // Add ourselves to the ATU list of the type.
-        cast<DerivedType>(DTy)->addAbstractTypeUser(this);
-
-        AbstractTypeMap.insert(TI, std::make_pair(DTy, I));
-      }
-    }
-  }
 
-  ConstantClass* Create(const TypeClass *Ty, const ValType &V,
+  ConstantClass *Create(const TypeClass *Ty, const ValType &V,
                         typename MapTy::iterator I) {
     ConstantClass* Result =
       ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
@@ -667,8 +645,6 @@
     if (HasLargeKey)  // Remember the reverse mapping if needed.
       InverseMap.insert(std::make_pair(Result, I));
 
-    AddAbstractTypeUser(Ty, I);
-      
     return Result;
   }
 public:
@@ -692,43 +668,6 @@
     return Result;
   }
 
-  void UpdateAbstractTypeMap(const DerivedType *Ty,
-                             typename MapTy::iterator I) {
-    assert(AbstractTypeMap.count(Ty) &&
-           "Abstract type not in AbstractTypeMap?");
-    typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
-    if (ATMEntryIt == I) {
-      // Yes, we are removing the representative entry for this type.
-      // See if there are any other entries of the same type.
-      typename MapTy::iterator TmpIt = ATMEntryIt;
-
-      // First check the entry before this one...
-      if (TmpIt != Map.begin()) {
-        --TmpIt;
-        if (TmpIt->first.first != Ty) // Not the same type, move back...
-          ++TmpIt;
-      }
-
-      // If we didn't find the same type, try to move forward...
-      if (TmpIt == ATMEntryIt) {
-        ++TmpIt;
-        if (TmpIt == Map.end() || TmpIt->first.first != Ty)
-          --TmpIt;   // No entry afterwards with the same type
-      }
-
-      // If there is another entry in the map of the same abstract type,
-      // update the AbstractTypeMap entry now.
-      if (TmpIt != ATMEntryIt) {
-        ATMEntryIt = TmpIt;
-      } else {
-        // Otherwise, we are removing the last instance of this type
-        // from the table.  Remove from the ATM, and from user list.
-        cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
-        AbstractTypeMap.erase(Ty);
-      }
-    }
-  }
-
   void remove(ConstantClass *CP) {
     typename MapTy::iterator I = FindExistingElement(CP);
     assert(I != Map.end() && "Constant not found in constant table!");
@@ -736,12 +675,6 @@
 
     if (HasLargeKey)  // Remember the reverse mapping if needed.
       InverseMap.erase(CP);
-      
-    // Now that we found the entry, make sure this isn't the entry that
-    // the AbstractTypeMap points to.
-    const TypeClass *Ty = I->first.first;
-    if (Ty->isAbstract())
-      UpdateAbstractTypeMap(static_cast<const DerivedType *>(Ty), I);
 
     Map.erase(I);
   }
@@ -755,22 +688,7 @@
     assert(OldI != Map.end() && "Constant not found in constant table!");
     assert(OldI->second == C && "Didn't find correct element?");
       
-    // If this constant is the representative element for its abstract type,
-    // update the AbstractTypeMap so that the representative element is I.
-    //
-    // This must use getRawType() because if the type is under refinement, we
-    // will get the refineAbstractType callback below, and we don't want to
-    // kick union find in on the constant.
-    if (C->getRawType()->isAbstract()) {
-      typename AbstractTypeMapTy::iterator ATI =
-          AbstractTypeMap.find(cast<DerivedType>(C->getRawType()));
-      assert(ATI != AbstractTypeMap.end() &&
-             "Abstract type not in AbstractTypeMap?");
-      if (ATI->second == OldI)
-        ATI->second = I;
-    }
-      
-    // Remove the old entry from the map.
+     // Remove the old entry from the map.
     Map.erase(OldI);
     
     // Update the inverse map so that we know that this constant is now
@@ -780,58 +698,6 @@
       InverseMap[C] = I;
     }
   }
-    
-  void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
-    typename AbstractTypeMapTy::iterator I = AbstractTypeMap.find(OldTy);
-
-    assert(I != AbstractTypeMap.end() &&
-           "Abstract type not in AbstractTypeMap?");
-
-    // Convert a constant at a time until the last one is gone.  The last one
-    // leaving will remove() itself, causing the AbstractTypeMapEntry to be
-    // eliminated eventually.
-    do {
-      ConstantClass *C = I->second->second;
-      MapKey Key(cast<TypeClass>(NewTy),
-                 ConstantKeyData<ConstantClass>::getValType(C));
-
-      std::pair<typename MapTy::iterator, bool> IP =
-        Map.insert(std::make_pair(Key, C));
-      if (IP.second) {
-        // The map didn't previously have an appropriate constant in the
-        // new type.
-        
-        // Remove the old entry.
-        typename MapTy::iterator OldI =
-          Map.find(MapKey(cast<TypeClass>(OldTy), IP.first->first.second));
-        assert(OldI != Map.end() && "Constant not in map!");
-        UpdateAbstractTypeMap(OldTy, OldI);
-        Map.erase(OldI);
-
-        // Set the constant's type. This is done in place!
-        setType(C, NewTy);
-
-        // Update the inverse map so that we know that this constant is now
-        // located at descriptor I.
-        if (HasLargeKey)
-          InverseMap[C] = IP.first;
-
-        AddAbstractTypeUser(NewTy, IP.first);
-      } else {
-        // The map already had an appropriate constant in the new type, so
-        // there's no longer a need for the old constant.
-        C->uncheckedReplaceAllUsesWith(IP.first->second);
-        C->destroyConstant();    // This constant is now dead, destroy it.
-      }
-      I = AbstractTypeMap.find(OldTy);
-    } while (I != AbstractTypeMap.end());
-  }
-
-  // If the type became concrete without being refined to any other existing
-  // type, we just remove ourselves from the ATU list.
-  void typeBecameConcrete(const DerivedType *AbsTy) {
-    AbsTy->removeAbstractTypeUser(this);
-  }
 
   void dump() const {
     DEBUG(dbgs() << "Constant.cpp: ConstantUniqueMap\n");

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Core.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Core.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Core.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Core.cpp Mon Jun 20 01:45:54 2011
@@ -19,7 +19,6 @@
 #include "llvm/GlobalVariable.h"
 #include "llvm/GlobalAlias.h"
 #include "llvm/LLVMContext.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/InlineAsm.h"
 #include "llvm/IntrinsicInst.h"
 #include "llvm/PassManager.h"
@@ -111,27 +110,6 @@
   unwrap(M)->setTargetTriple(Triple);
 }
 
-/*--.. Type names ..........................................................--*/
-LLVMBool LLVMAddTypeName(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
-  return unwrap(M)->addTypeName(Name, unwrap(Ty));
-}
-
-void LLVMDeleteTypeName(LLVMModuleRef M, const char *Name) {
-  TypeSymbolTable &TST = unwrap(M)->getTypeSymbolTable();
-
-  TypeSymbolTable::iterator I = TST.find(Name);
-  if (I != TST.end())
-    TST.remove(I);
-}
-
-LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name) {
-  return wrap(unwrap(M)->getTypeByName(Name));
-}
-
-const char *LLVMGetTypeName(LLVMModuleRef M, LLVMTypeRef Ty) {
-  return unwrap(M)->getTypeName(unwrap(Ty)).c_str();
-}
-
 void LLVMDumpModule(LLVMModuleRef M) {
   unwrap(M)->dump();
 }
@@ -182,8 +160,6 @@
     return LLVMArrayTypeKind;
   case Type::PointerTyID:
     return LLVMPointerTypeKind;
-  case Type::OpaqueTyID:
-    return LLVMOpaqueTypeKind;
   case Type::VectorTyID:
     return LLVMVectorTypeKind;
   case Type::X86_MMXTyID:
@@ -382,9 +358,6 @@
 LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C) {
   return wrap(Type::getLabelTy(*unwrap(C)));
 }
-LLVMTypeRef LLVMOpaqueTypeInContext(LLVMContextRef C) {
-  return wrap(OpaqueType::get(*unwrap(C)));
-}
 
 LLVMTypeRef LLVMVoidType(void)  {
   return LLVMVoidTypeInContext(LLVMGetGlobalContext());
@@ -392,28 +365,6 @@
 LLVMTypeRef LLVMLabelType(void) {
   return LLVMLabelTypeInContext(LLVMGetGlobalContext());
 }
-LLVMTypeRef LLVMOpaqueType(void) {
-  return LLVMOpaqueTypeInContext(LLVMGetGlobalContext());
-}
-
-/*--.. Operations on type handles ..........................................--*/
-
-LLVMTypeHandleRef LLVMCreateTypeHandle(LLVMTypeRef PotentiallyAbstractTy) {
-  return wrap(new PATypeHolder(unwrap(PotentiallyAbstractTy)));
-}
-
-void LLVMDisposeTypeHandle(LLVMTypeHandleRef TypeHandle) {
-  delete unwrap(TypeHandle);
-}
-
-LLVMTypeRef LLVMResolveTypeHandle(LLVMTypeHandleRef TypeHandle) {
-  return wrap(unwrap(TypeHandle)->get());
-}
-
-void LLVMRefineType(LLVMTypeRef AbstractTy, LLVMTypeRef ConcreteTy) {
-  unwrap<DerivedType>(AbstractTy)->refineAbstractTypeTo(unwrap(ConcreteTy));
-}
-
 
 /*===-- Operations on values ----------------------------------------------===*/
 

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Function.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Function.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Function.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Function.cpp Mon Jun 20 01:45:54 2011
@@ -134,7 +134,7 @@
   return getType()->getContext();
 }
 
-const FunctionType *Function::getFunctionType() const {
+FunctionType *Function::getFunctionType() const {
   return cast<FunctionType>(getType()->getElementType());
 }
 
@@ -142,7 +142,7 @@
   return getFunctionType()->isVarArg();
 }
 
-const Type *Function::getReturnType() const {
+Type *Function::getReturnType() const {
   return getFunctionType()->getReturnType();
 }
 
@@ -163,7 +163,7 @@
   : GlobalValue(PointerType::getUnqual(Ty), 
                 Value::FunctionVal, 0, 0, Linkage, name) {
   assert(FunctionType::isValidReturnType(getReturnType()) &&
-         !getReturnType()->isOpaqueTy() && "invalid return type");
+         "invalid return type");
   SymTab = new ValueSymbolTable();
 
   // If the function has arguments, mark them as lazily built.

Modified: llvm/branches/type-system-rewrite/lib/VMCore/InlineAsm.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/InlineAsm.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/InlineAsm.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/InlineAsm.cpp Mon Jun 20 01:45:54 2011
@@ -47,7 +47,7 @@
 }
 
 void InlineAsm::destroyConstant() {
-  getRawType()->getContext().pImpl->InlineAsms.remove(this);
+  getType()->getContext().pImpl->InlineAsms.remove(this);
   delete this;
 }
 

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Instructions.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Instructions.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Instructions.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Instructions.cpp Mon Jun 20 01:45:54 2011
@@ -366,7 +366,7 @@
   // Create the call to Malloc.
   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
   Module* M = BB->getParent()->getParent();
-  const Type *BPTy = Type::getInt8PtrTy(BB->getContext());
+  Type *BPTy = Type::getInt8PtrTy(BB->getContext());
   Value *MallocFunc = MallocF;
   if (!MallocFunc)
     // prototype malloc as "void *malloc(size_t)"
@@ -817,7 +817,7 @@
   return true;
 }
 
-const Type *AllocaInst::getAllocatedType() const {
+Type *AllocaInst::getAllocatedType() const {
   return getType()->getElementType();
 }
 
@@ -1092,7 +1092,7 @@
 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
                                      const Twine &Name, Instruction *InBe)
   : Instruction(PointerType::get(
-      checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
+      checkGEPType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
                 GetElementPtr,
                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
                 2, InBe) {
@@ -1102,7 +1102,7 @@
 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
                                      const Twine &Name, BasicBlock *IAE)
   : Instruction(PointerType::get(
-            checkType(getIndexedType(Ptr->getType(),Idx)),  
+            checkGEPType(getIndexedType(Ptr->getType(),Idx)),  
                 retrieveAddrSpace(Ptr)),
                 GetElementPtr,
                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
@@ -1120,60 +1120,50 @@
 /// pointer type.
 ///
 template <typename IndexTy>
-static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
-                                          unsigned NumIdx) {
+static Type *getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
+                                    unsigned NumIdx) {
   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
   if (!PTy) return 0;   // Type isn't a pointer type!
-  const Type *Agg = PTy->getElementType();
+  Type *Agg = PTy->getElementType();
 
   // Handle the special case of the empty set index set, which is always valid.
   if (NumIdx == 0)
     return Agg;
   
   // If there is at least one index, the top level type must be sized, otherwise
-  // it cannot be 'stepped over'.  We explicitly allow abstract types (those
-  // that contain opaque types) under the assumption that it will be resolved to
-  // a sane type later.
-  if (!Agg->isSized() && !Agg->isAbstract())
+  // it cannot be 'stepped over'.
+  if (!Agg->isSized())
     return 0;
 
   unsigned CurIdx = 1;
   for (; CurIdx != NumIdx; ++CurIdx) {
-    const CompositeType *CT = dyn_cast<CompositeType>(Agg);
+    CompositeType *CT = dyn_cast<CompositeType>(Agg);
     if (!CT || CT->isPointerTy()) return 0;
     IndexTy Index = Idxs[CurIdx];
     if (!CT->indexValid(Index)) return 0;
     Agg = CT->getTypeAtIndex(Index);
-
-    // If the new type forwards to another type, then it is in the middle
-    // of being refined to another type (and hence, may have dropped all
-    // references to what it was using before).  So, use the new forwarded
-    // type.
-    if (const Type *Ty = Agg->getForwardedType())
-      Agg = Ty;
   }
   return CurIdx == NumIdx ? Agg : 0;
 }
 
-const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
-                                              Value* const *Idxs,
-                                              unsigned NumIdx) {
+Type *GetElementPtrInst::getIndexedType(const Type *Ptr, Value* const *Idxs,
+                                        unsigned NumIdx) {
   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
 }
 
-const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
-                                              Constant* const *Idxs,
-                                              unsigned NumIdx) {
+Type *GetElementPtrInst::getIndexedType(const Type *Ptr,
+                                        Constant* const *Idxs,
+                                        unsigned NumIdx) {
   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
 }
 
-const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
-                                              uint64_t const *Idxs,
-                                              unsigned NumIdx) {
+Type *GetElementPtrInst::getIndexedType(const Type *Ptr,
+                                        uint64_t const *Idxs,
+                                        unsigned NumIdx) {
   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
 }
 
-const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
+Type *GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
   if (!PTy) return 0;   // Type isn't a pointer type!
 
@@ -1476,9 +1466,9 @@
 // A null type is returned if the indices are invalid for the specified
 // pointer type.
 //
-const Type* ExtractValueInst::getIndexedType(const Type *Agg,
-                                             const unsigned *Idxs,
-                                             unsigned NumIdx) {
+Type *ExtractValueInst::getIndexedType(const Type *Agg,
+                                       const unsigned *Idxs,
+                                       unsigned NumIdx) {
   for (unsigned CurIdx = 0; CurIdx != NumIdx; ++CurIdx) {
     unsigned Index = Idxs[CurIdx];
     // We can't use CompositeType::indexValid(Index) here.
@@ -1499,19 +1489,11 @@
     }
 
     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
-
-    // If the new type forwards to another type, then it is in the middle
-    // of being refined to another type (and hence, may have dropped all
-    // references to what it was using before).  So, use the new forwarded
-    // type.
-    if (const Type *Ty = Agg->getForwardedType())
-      Agg = Ty;
   }
-  return Agg;
+  return const_cast<Type*>(Agg);
 }
 
-const Type* ExtractValueInst::getIndexedType(const Type *Agg,
-                                             unsigned Idx) {
+Type *ExtractValueInst::getIndexedType(const Type *Agg, unsigned Idx) {
   return getIndexedType(Agg, &Idx, 1);
 }
 

Modified: llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.cpp Mon Jun 20 01:45:54 2011
@@ -31,14 +31,10 @@
     Int8Ty(C, 8),
     Int16Ty(C, 16),
     Int32Ty(C, 32),
-    Int64Ty(C, 64),
-    AlwaysOpaqueTy(new OpaqueType(C)) {
+    Int64Ty(C, 64) {
   InlineAsmDiagHandler = 0;
   InlineAsmDiagContext = 0;
-      
-  // Make sure the AlwaysOpaqueTy stays alive as long as the Context.
-  AlwaysOpaqueTy->addRef();
-  OpaqueTypes.insert(AlwaysOpaqueTy);
+  NamedStructTypesUniqueID = 0;
 }
 
 namespace {
@@ -86,12 +82,7 @@
        I != E; ++I) {
     delete I->second;
   }
-  AlwaysOpaqueTy->dropRef();
-  for (OpaqueTypesTy::iterator I = OpaqueTypes.begin(), E = OpaqueTypes.end();
-       I != E; ++I) {
-    (*I)->AbstractTypeUsers.clear();
-    delete *I;
-  }
+  
   // Destroy MDNodes.  ~MDNode can move and remove nodes between the MDNodeSet
   // and the NonUniquedMDNodes sets, so copy the values out first.
   SmallVector<MDNode*, 8> MDNodes;
@@ -109,7 +100,6 @@
          "Destroying all MDNodes didn't empty the Context's sets.");
   // Destroy MDStrings.
   for (StringMap<MDString*>::iterator I = MDStringCache.begin(),
-         E = MDStringCache.end(); I != E; ++I) {
+         E = MDStringCache.end(); I != E; ++I)
     delete I->second;
-  }
 }

Modified: llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.h (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/LLVMContextImpl.h Mon Jun 20 01:45:54 2011
@@ -15,10 +15,9 @@
 #ifndef LLVM_LLVMCONTEXT_IMPL_H
 #define LLVM_LLVMCONTEXT_IMPL_H
 
+#include "llvm/LLVMContext.h"
 #include "ConstantsContext.h"
 #include "LeaksContext.h"
-#include "TypesContext.h"
-#include "llvm/LLVMContext.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Metadata.h"
@@ -166,34 +165,22 @@
   LeakDetectorImpl<Value> LLVMObjects;
   
   // Basic type instances.
-  const Type VoidTy;
-  const Type LabelTy;
-  const Type FloatTy;
-  const Type DoubleTy;
-  const Type MetadataTy;
-  const Type X86_FP80Ty;
-  const Type FP128Ty;
-  const Type PPC_FP128Ty;
-  const Type X86_MMXTy;
-  const IntegerType Int1Ty;
-  const IntegerType Int8Ty;
-  const IntegerType Int16Ty;
-  const IntegerType Int32Ty;
-  const IntegerType Int64Ty;
-
-  TypeMap<ArrayValType, ArrayType> ArrayTypes;
-  TypeMap<VectorValType, VectorType> VectorTypes;
-  TypeMap<PointerValType, PointerType> PointerTypes;
-  TypeMap<FunctionValType, FunctionType> FunctionTypes;
-  TypeMap<StructValType, StructType> StructTypes;
-  TypeMap<IntegerValType, IntegerType> IntegerTypes;
-
-  // Opaque types are not structurally uniqued, so don't use TypeMap.
-  typedef SmallPtrSet<const OpaqueType*, 8> OpaqueTypesTy;
-  OpaqueTypesTy OpaqueTypes;
-
-  /// Used as an abstract type that will never be resolved.
-  OpaqueType *const AlwaysOpaqueTy;
+  Type VoidTy, LabelTy, FloatTy, DoubleTy, MetadataTy;
+  Type X86_FP80Ty, FP128Ty, PPC_FP128Ty, X86_MMXTy;
+  IntegerType Int1Ty, Int8Ty, Int16Ty, Int32Ty, Int64Ty;
+
+  DenseMap<unsigned, IntegerType*> IntegerTypes;
+  
+  // TODO: Optimize FunctionTypes/AnonStructTypes!
+  std::map<std::vector<Type*>, FunctionType*> FunctionTypes;
+  std::map<std::vector<Type*>, StructType*> AnonStructTypes;
+  StringMap<StructType*> NamedStructTypes;
+  unsigned NamedStructTypesUniqueID;
+    
+  DenseMap<std::pair<Type *, uint64_t>, ArrayType*> ArrayTypes;
+  DenseMap<std::pair<Type *, unsigned>, VectorType*> VectorTypes;
+  DenseMap<Type*, PointerType*> PointerTypes;  // Pointers in AddrSpace = 0
+  DenseMap<std::pair<Type*, unsigned>, PointerType*> ASPointerTypes;
 
 
   /// ValueHandles - This map keeps track of all of the value handles that are

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Metadata.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Metadata.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Metadata.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Metadata.cpp Mon Jun 20 01:45:54 2011
@@ -19,6 +19,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/STLExtras.h"
 #include "SymbolTableListTraitsImpl.h"
 #include "llvm/Support/LeakDetector.h"
 #include "llvm/Support/ValueHandle.h"

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Module.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Module.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Module.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Module.cpp Mon Jun 20 01:45:54 2011
@@ -17,12 +17,12 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/GVMaterializer.h"
 #include "llvm/LLVMContext.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/LeakDetector.h"
 #include "SymbolTableListTraitsImpl.h"
-#include "llvm/TypeSymbolTable.h"
 #include <algorithm>
 #include <cstdarg>
 #include <cstdlib>
@@ -60,7 +60,6 @@
 Module::Module(StringRef MID, LLVMContext& C)
   : Context(C), Materializer(NULL), ModuleID(MID) {
   ValSymTab = new ValueSymbolTable();
-  TypeSymTab = new TypeSymbolTable();
   NamedMDSymTab = new StringMap<NamedMDNode *>();
   Context.addModule(this);
 }
@@ -74,11 +73,10 @@
   LibraryList.clear();
   NamedMDList.clear();
   delete ValSymTab;
-  delete TypeSymTab;
   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
 }
 
-/// Target endian information...
+/// Target endian information.
 Module::Endianness Module::getEndianness() const {
   StringRef temp = DataLayout;
   Module::Endianness ret = AnyEndianness;
@@ -340,51 +338,6 @@
   NamedMDList.erase(NMD);
 }
 
-//===----------------------------------------------------------------------===//
-// Methods for easy access to the types in the module.
-//
-
-
-// addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
-// there is already an entry for this name, true is returned and the symbol
-// table is not modified.
-//
-bool Module::addTypeName(StringRef Name, const Type *Ty) {
-  TypeSymbolTable &ST = getTypeSymbolTable();
-
-  if (ST.lookup(Name)) return true;  // Already in symtab...
-
-  // Not in symbol table?  Set the name with the Symtab as an argument so the
-  // type knows what to update...
-  ST.insert(Name, Ty);
-
-  return false;
-}
-
-/// getTypeByName - Return the type with the specified name in this module, or
-/// null if there is none by that name.
-const Type *Module::getTypeByName(StringRef Name) const {
-  const TypeSymbolTable &ST = getTypeSymbolTable();
-  return cast_or_null<Type>(ST.lookup(Name));
-}
-
-// getTypeName - If there is at least one entry in the symbol table for the
-// specified type, return it.
-//
-std::string Module::getTypeName(const Type *Ty) const {
-  const TypeSymbolTable &ST = getTypeSymbolTable();
-
-  TypeSymbolTable::const_iterator TI = ST.begin();
-  TypeSymbolTable::const_iterator TE = ST.end();
-  if ( TI == TE ) return ""; // No names for types
-
-  while (TI != TE && TI->second != Ty)
-    ++TI;
-
-  if (TI != TE)  // Must have found an entry!
-    return TI->first;
-  return "";     // Must not have found anything...
-}
 
 //===----------------------------------------------------------------------===//
 // Methods to control the materialization of GlobalValues in the Module.
@@ -471,3 +424,98 @@
       return;
     }
 }
+
+//===----------------------------------------------------------------------===//
+// Type finding functionality.
+//===----------------------------------------------------------------------===//
+
+namespace {
+  /// TypeFinder - Walk over a module, identifying all of the types that are
+  /// used by the module.
+  class TypeFinder {
+    // To avoid walking constant expressions multiple times and other IR
+    // objects, we keep several helper maps.
+    DenseSet<const Value*> VisitedConstants;
+    DenseSet<const Type*> VisitedTypes;
+    
+    std::vector<StructType*> &StructTypes;
+  public:
+    TypeFinder(std::vector<StructType*> &structTypes)
+      : StructTypes(structTypes) {}
+    
+    void run(const Module &M) {
+      // Get types from global variables.
+      for (Module::const_global_iterator I = M.global_begin(),
+           E = M.global_end(); I != E; ++I) {
+        incorporateType(I->getType());
+        if (I->hasInitializer())
+          incorporateValue(I->getInitializer());
+      }
+      
+      // Get types from aliases.
+      for (Module::const_alias_iterator I = M.alias_begin(),
+           E = M.alias_end(); I != E; ++I) {
+        incorporateType(I->getType());
+        incorporateValue(I->getAliasee());
+      }
+      
+      // Get types from functions.
+      for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
+        incorporateType(FI->getType());
+        
+        for (Function::const_iterator BB = FI->begin(), E = FI->end();
+             BB != E;++BB)
+          for (BasicBlock::const_iterator II = BB->begin(),
+               E = BB->end(); II != E; ++II) {
+            const Instruction &I = *II;
+            // Incorporate the type of the instruction and all its operands.
+            incorporateType(I.getType());
+            for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
+                 OI != OE; ++OI)
+              incorporateValue(*OI);
+          }
+      }
+    }
+    
+  private:
+    void incorporateType(Type *Ty) {
+      // Check to see if we're already visited this type.
+      if (!VisitedTypes.insert(Ty).second)
+        return;
+      
+      // If this is a structure or opaque type, add a name for the type.
+      if (StructType *STy = dyn_cast<StructType>(Ty))
+        StructTypes.push_back(STy);
+      
+      // Recursively walk all contained types.
+      for (Type::subtype_iterator I = Ty->subtype_begin(),
+           E = Ty->subtype_end(); I != E; ++I)
+        incorporateType(*I);
+    }
+    
+    /// incorporateValue - This method is used to walk operand lists finding
+    /// types hiding in constant expressions and other operands that won't be
+    /// walked in other ways.  GlobalValues, basic blocks, instructions, and
+    /// inst operands are all explicitly enumerated.
+    void incorporateValue(const Value *V) {
+      if (!isa<Constant>(V) || isa<GlobalValue>(V)) return;
+      
+      // Already visited?
+      if (!VisitedConstants.insert(V).second)
+        return;
+      
+      // Check this type.
+      incorporateType(V->getType());
+      
+      // Look in operands for types.
+      const Constant *C = cast<Constant>(V);
+      for (Constant::const_op_iterator I = C->op_begin(),
+           E = C->op_end(); I != E;++I)
+        incorporateValue(*I);
+    }
+  };
+} // end anonymous namespace
+
+void Module::findUsedStructTypes(std::vector<StructType*> &StructTypes) const {
+  TypeFinder(StructTypes).run(*this);
+}

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Type.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Type.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Type.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Type.cpp Mon Jun 20 01:45:54 2011
@@ -12,81 +12,16 @@
 //===----------------------------------------------------------------------===//
 
 #include "LLVMContextImpl.h"
-#include "llvm/ADT/SCCIterator.h"
 #include <algorithm>
 #include <cstdarg>
+#include "llvm/ADT/SmallString.h"
 using namespace llvm;
 
-// DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
-// created and later destroyed, all in an effort to make sure that there is only
-// a single canonical version of a type.
-//
-// #define DEBUG_MERGE_TYPES 1
-
-AbstractTypeUser::~AbstractTypeUser() {}
-
-void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
-  V->VTy = NewTy;
-}
-
 //===----------------------------------------------------------------------===//
 //                         Type Class Implementation
 //===----------------------------------------------------------------------===//
 
-/// Because of the way Type subclasses are allocated, this function is necessary
-/// to use the correct kind of "delete" operator to deallocate the Type object.
-/// Some type objects (FunctionTy, StructTy) allocate additional space
-/// after the space for their derived type to hold the contained types array of
-/// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
-/// allocated with the type object, decreasing allocations and eliminating the
-/// need for a std::vector to be used in the Type class itself. 
-/// @brief Type destruction function
-void Type::destroy() const {
-  // Nothing calls getForwardedType from here on.
-  if (ForwardType && ForwardType->isAbstract()) {
-    ForwardType->dropRef();
-    ForwardType = NULL;
-  }
-
-  // Structures and Functions allocate their contained types past the end of
-  // the type object itself. These need to be destroyed differently than the
-  // other types.
-  if (this->isFunctionTy() || this->isStructTy()) {
-    // First, make sure we destruct any PATypeHandles allocated by these
-    // subclasses.  They must be manually destructed. 
-    for (unsigned i = 0; i < NumContainedTys; ++i)
-      ContainedTys[i].PATypeHandle::~PATypeHandle();
-
-    // Now call the destructor for the subclass directly because we're going
-    // to delete this as an array of char.
-    if (this->isFunctionTy())
-      static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
-    else {
-      assert(isStructTy());
-      static_cast<const StructType*>(this)->StructType::~StructType();
-    }
-
-    // Finally, remove the memory as an array deallocation of the chars it was
-    // constructed from.
-    operator delete(const_cast<Type *>(this));
-
-    return;
-  }
-  
-  if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
-    LLVMContextImpl *pImpl = this->getContext().pImpl;
-    pImpl->OpaqueTypes.erase(opaque_this);
-  }
-
-  // For all the other type subclasses, there is either no contained types or 
-  // just one (all Sequentials). For Sequentials, the PATypeHandle is not
-  // allocated past the type object, its included directly in the SequentialType
-  // class. This means we can safely just do "normal" delete of this object and
-  // all the destructors that need to run will be run.
-  delete this; 
-}
-
-const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
+Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
   switch (IDNumber) {
   case VoidTyID      : return getVoidTy(C);
   case FloatTyID     : return getFloatTy(C);
@@ -253,533 +188,87 @@
   return true;
 }
 
-/// getForwardedTypeInternal - This method is used to implement the union-find
-/// algorithm for when a type is being forwarded to another type.
-const Type *Type::getForwardedTypeInternal() const {
-  assert(ForwardType && "This type is not being forwarded to another type!");
-
-  // Check to see if the forwarded type has been forwarded on.  If so, collapse
-  // the forwarding links.
-  const Type *RealForwardedType = ForwardType->getForwardedType();
-  if (!RealForwardedType)
-    return ForwardType;  // No it's not forwarded again
-
-  // Yes, it is forwarded again.  First thing, add the reference to the new
-  // forward type.
-  if (RealForwardedType->isAbstract())
-    RealForwardedType->addRef();
-
-  // Now drop the old reference.  This could cause ForwardType to get deleted.
-  // ForwardType must be abstract because only abstract types can have their own
-  // ForwardTypes.
-  ForwardType->dropRef();
-
-  // Return the updated type.
-  ForwardType = RealForwardedType;
-  return ForwardType;
-}
-
-void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
-  llvm_unreachable("Attempting to refine a derived type!");
-}
-void Type::typeBecameConcrete(const DerivedType *AbsTy) {
-  llvm_unreachable("DerivedType is already a concrete type!");
-}
-
-const Type *CompositeType::getTypeAtIndex(const Value *V) const {
-  if (const StructType *STy = dyn_cast<StructType>(this)) {
-    unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
-    assert(indexValid(Idx) && "Invalid structure index!");
-    return STy->getElementType(Idx);
-  }
-    
-  return cast<SequentialType>(this)->getElementType();
-}
-const Type *CompositeType::getTypeAtIndex(unsigned Idx) const {
-  if (const StructType *STy = dyn_cast<StructType>(this)) {
-    assert(indexValid(Idx) && "Invalid structure index!");
-    return STy->getElementType(Idx);
-  }
-  
-  return cast<SequentialType>(this)->getElementType();
-}
-bool CompositeType::indexValid(const Value *V) const {
-  if (const StructType *STy = dyn_cast<StructType>(this)) {
-    // Structure indexes require 32-bit integer constants.
-    if (V->getType()->isIntegerTy(32))
-      if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
-        return CU->getZExtValue() < STy->getNumElements();
-    return false;
-  }
-  
-  // Sequential types can be indexed by any integer.
-  return V->getType()->isIntegerTy();
-}
-
-bool CompositeType::indexValid(unsigned Idx) const {
-  if (const StructType *STy = dyn_cast<StructType>(this))
-    return Idx < STy->getNumElements();
-  // Sequential types can be indexed by any integer.
-  return true;
-}
-
-
 //===----------------------------------------------------------------------===//
 //                          Primitive 'Type' data
 //===----------------------------------------------------------------------===//
 
-const Type *Type::getVoidTy(LLVMContext &C) {
-  return &C.pImpl->VoidTy;
-}
-
-const Type *Type::getLabelTy(LLVMContext &C) {
-  return &C.pImpl->LabelTy;
-}
-
-const Type *Type::getFloatTy(LLVMContext &C) {
-  return &C.pImpl->FloatTy;
-}
-
-const Type *Type::getDoubleTy(LLVMContext &C) {
-  return &C.pImpl->DoubleTy;
-}
-
-const Type *Type::getMetadataTy(LLVMContext &C) {
-  return &C.pImpl->MetadataTy;
-}
+Type *Type::getVoidTy(LLVMContext &C) { return &C.pImpl->VoidTy; }
+Type *Type::getLabelTy(LLVMContext &C) { return &C.pImpl->LabelTy; }
+Type *Type::getFloatTy(LLVMContext &C) { return &C.pImpl->FloatTy; }
+Type *Type::getDoubleTy(LLVMContext &C) { return &C.pImpl->DoubleTy; }
+Type *Type::getMetadataTy(LLVMContext &C) { return &C.pImpl->MetadataTy; }
+Type *Type::getX86_FP80Ty(LLVMContext &C) { return &C.pImpl->X86_FP80Ty; }
+Type *Type::getFP128Ty(LLVMContext &C) { return &C.pImpl->FP128Ty; }
+Type *Type::getPPC_FP128Ty(LLVMContext &C) { return &C.pImpl->PPC_FP128Ty; }
+Type *Type::getX86_MMXTy(LLVMContext &C) { return &C.pImpl->X86_MMXTy; }
+
+IntegerType *Type::getInt1Ty(LLVMContext &C) { return &C.pImpl->Int1Ty; }
+IntegerType *Type::getInt8Ty(LLVMContext &C) { return &C.pImpl->Int8Ty; }
+IntegerType *Type::getInt16Ty(LLVMContext &C) { return &C.pImpl->Int16Ty; }
+IntegerType *Type::getInt32Ty(LLVMContext &C) { return &C.pImpl->Int32Ty; }
+IntegerType *Type::getInt64Ty(LLVMContext &C) { return &C.pImpl->Int64Ty; }
 
-const Type *Type::getX86_FP80Ty(LLVMContext &C) {
-  return &C.pImpl->X86_FP80Ty;
-}
-
-const Type *Type::getFP128Ty(LLVMContext &C) {
-  return &C.pImpl->FP128Ty;
-}
-
-const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
-  return &C.pImpl->PPC_FP128Ty;
-}
-
-const Type *Type::getX86_MMXTy(LLVMContext &C) {
-  return &C.pImpl->X86_MMXTy;
-}
-
-const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
+IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
   return IntegerType::get(C, N);
 }
 
-const IntegerType *Type::getInt1Ty(LLVMContext &C) {
-  return &C.pImpl->Int1Ty;
-}
-
-const IntegerType *Type::getInt8Ty(LLVMContext &C) {
-  return &C.pImpl->Int8Ty;
-}
-
-const IntegerType *Type::getInt16Ty(LLVMContext &C) {
-  return &C.pImpl->Int16Ty;
-}
-
-const IntegerType *Type::getInt32Ty(LLVMContext &C) {
-  return &C.pImpl->Int32Ty;
-}
-
-const IntegerType *Type::getInt64Ty(LLVMContext &C) {
-  return &C.pImpl->Int64Ty;
-}
-
-const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
   return getFloatTy(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
   return getDoubleTy(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
   return getX86_FP80Ty(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
   return getFP128Ty(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
   return getPPC_FP128Ty(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
   return getX86_MMXTy(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
+PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
   return getIntNTy(C, N)->getPointerTo(AS);
 }
 
-const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
   return getInt1Ty(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
   return getInt8Ty(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
   return getInt16Ty(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
   return getInt32Ty(C)->getPointerTo(AS);
 }
 
-const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
+PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
   return getInt64Ty(C)->getPointerTo(AS);
 }
 
-//===----------------------------------------------------------------------===//
-//                          Derived Type Constructors
-//===----------------------------------------------------------------------===//
-
-/// isValidReturnType - Return true if the specified type is valid as a return
-/// type.
-bool FunctionType::isValidReturnType(const Type *RetTy) {
-  return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
-         !RetTy->isMetadataTy();
-}
-
-/// isValidArgumentType - Return true if the specified type is valid as an
-/// argument type.
-bool FunctionType::isValidArgumentType(const Type *ArgTy) {
-  return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
-}
-
-FunctionType::FunctionType(const Type *Result,
-                           ArrayRef<const Type*> Params,
-                           bool IsVarArgs)
-  : DerivedType(Result->getContext(), FunctionTyID) {
-  ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
-  NumContainedTys = Params.size() + 1; // + 1 for result type
-  assert(isValidReturnType(Result) && "invalid return type for function");
-  setSubclassData(IsVarArgs);
-
-  bool isAbstract = Result->isAbstract();
-  new (&ContainedTys[0]) PATypeHandle(Result, this);
-
-  for (unsigned i = 0; i != Params.size(); ++i) {
-    assert(isValidArgumentType(Params[i]) &&
-           "Not a valid type for function argument!");
-    new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
-    isAbstract |= Params[i]->isAbstract();
-  }
-
-  // Calculate whether or not this type is abstract
-  setAbstract(isAbstract);
-}
-
-StructType::StructType(LLVMContext &C, 
-                       ArrayRef<const Type*> Types, bool isPacked)
-  : CompositeType(C, StructTyID) {
-  ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
-  NumContainedTys = Types.size();
-  setSubclassData(isPacked);
-  bool isAbstract = false;
-  for (unsigned i = 0; i < Types.size(); ++i) {
-    assert(Types[i] && "<null> type for structure field!");
-    assert(isValidElementType(Types[i]) &&
-           "Invalid type for structure element!");
-    new (&ContainedTys[i]) PATypeHandle(Types[i], this);
-    isAbstract |= Types[i]->isAbstract();
-  }
-
-  // Calculate whether or not this type is abstract
-  setAbstract(isAbstract);
-}
-
-ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
-  : SequentialType(ArrayTyID, ElType) {
-  NumElements = NumEl;
-
-  // Calculate whether or not this type is abstract
-  setAbstract(ElType->isAbstract());
-}
-
-VectorType::VectorType(const Type *ElType, unsigned NumEl)
-  : SequentialType(VectorTyID, ElType) {
-  NumElements = NumEl;
-  setAbstract(ElType->isAbstract());
-  assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
-  assert(isValidElementType(ElType) &&
-         "Elements of a VectorType must be a primitive type");
-
-}
-
-
-PointerType::PointerType(const Type *E, unsigned AddrSpace)
-  : SequentialType(PointerTyID, E) {
-  setSubclassData(AddrSpace);
-  // Calculate whether or not this type is abstract
-  setAbstract(E->isAbstract());
-}
-
-OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
-  setAbstract(true);
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "Derived new type: " << *this << "\n");
-#endif
-}
-
-void PATypeHolder::destroy() {
-  Ty = 0;
-}
-
-// dropAllTypeUses - When this (abstract) type is resolved to be equal to
-// another (more concrete) type, we must eliminate all references to other
-// types, to avoid some circular reference problems.
-void DerivedType::dropAllTypeUses() {
-  if (NumContainedTys != 0) {
-    // The type must stay abstract.  To do this, we insert a pointer to a type
-    // that will never get resolved, thus will always be abstract.
-    ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
-
-    // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
-    // pick so long as it doesn't point back to this type.  We choose something
-    // concrete to avoid overhead for adding to AbstractTypeUser lists and
-    // stuff.
-    const Type *ConcreteTy = Type::getInt32Ty(getContext());
-    for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
-      ContainedTys[i] = ConcreteTy;
-  }
-}
-
-
-namespace {
-
-/// TypePromotionGraph and graph traits - this is designed to allow us to do
-/// efficient SCC processing of type graphs.  This is the exact same as
-/// GraphTraits<Type*>, except that we pretend that concrete types have no
-/// children to avoid processing them.
-struct TypePromotionGraph {
-  Type *Ty;
-  TypePromotionGraph(Type *T) : Ty(T) {}
-};
-
-}
-
-namespace llvm {
-  template <> struct GraphTraits<TypePromotionGraph> {
-    typedef Type NodeType;
-    typedef Type::subtype_iterator ChildIteratorType;
-
-    static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
-    static inline ChildIteratorType child_begin(NodeType *N) {
-      if (N->isAbstract())
-        return N->subtype_begin();
-      // No need to process children of concrete types.
-      return N->subtype_end();
-    }
-    static inline ChildIteratorType child_end(NodeType *N) {
-      return N->subtype_end();
-    }
-  };
-}
-
-
-// PromoteAbstractToConcrete - This is a recursive function that walks a type
-// graph calculating whether or not a type is abstract.
-//
-void Type::PromoteAbstractToConcrete() {
-  if (!isAbstract()) return;
-
-  scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
-  scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
-
-  for (; SI != SE; ++SI) {
-    std::vector<Type*> &SCC = *SI;
-
-    // Concrete types are leaves in the tree.  Since an SCC will either be all
-    // abstract or all concrete, we only need to check one type.
-    if (!SCC[0]->isAbstract()) continue;
-    
-    if (SCC[0]->isOpaqueTy())
-      return;     // Not going to be concrete, sorry.
-
-    // If all of the children of all of the types in this SCC are concrete,
-    // then this SCC is now concrete as well.  If not, neither this SCC, nor
-    // any parent SCCs will be concrete, so we might as well just exit.
-    for (unsigned i = 0, e = SCC.size(); i != e; ++i)
-      for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
-             E = SCC[i]->subtype_end(); CI != E; ++CI)
-        if ((*CI)->isAbstract())
-          // If the child type is in our SCC, it doesn't make the entire SCC
-          // abstract unless there is a non-SCC abstract type.
-          if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
-            return;               // Not going to be concrete, sorry.
-
-    // Okay, we just discovered this whole SCC is now concrete, mark it as
-    // such!
-    for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
-      assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
-
-      SCC[i]->setAbstract(false);
-    }
-
-    for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
-      assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
-      // The type just became concrete, notify all users!
-      cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
-    }
-  }
-}
-
 
 //===----------------------------------------------------------------------===//
-//                      Type Structural Equality Testing
+//                       IntegerType Implementation
 //===----------------------------------------------------------------------===//
 
-// TypesEqual - Two types are considered structurally equal if they have the
-// same "shape": Every level and element of the types have identical primitive
-// ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
-// be pointer equals to be equivalent though.  This uses an optimistic algorithm
-// that assumes that two graphs are the same until proven otherwise.
-//
-static bool TypesEqual(const Type *Ty, const Type *Ty2,
-                       std::map<const Type *, const Type *> &EqTypes) {
-  if (Ty == Ty2) return true;
-  if (Ty->getTypeID() != Ty2->getTypeID()) return false;
-  if (Ty->isOpaqueTy())
-    return false;  // Two unequal opaque types are never equal
-
-  std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
-  if (It != EqTypes.end())
-    return It->second == Ty2;    // Looping back on a type, check for equality
-
-  // Otherwise, add the mapping to the table to make sure we don't get
-  // recursion on the types...
-  EqTypes.insert(It, std::make_pair(Ty, Ty2));
-
-  // Two really annoying special cases that breaks an otherwise nice simple
-  // algorithm is the fact that arraytypes have sizes that differentiates types,
-  // and that function types can be varargs or not.  Consider this now.
-  //
-  if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
-    const IntegerType *ITy2 = cast<IntegerType>(Ty2);
-    return ITy->getBitWidth() == ITy2->getBitWidth();
-  }
-  
-  if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
-    const PointerType *PTy2 = cast<PointerType>(Ty2);
-    return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
-           TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
-  }
-  
-  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
-    const StructType *STy2 = cast<StructType>(Ty2);
-    if (STy->getNumElements() != STy2->getNumElements()) return false;
-    if (STy->isPacked() != STy2->isPacked()) return false;
-    for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
-      if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
-        return false;
-    return true;
-  }
-  
-  if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
-    const ArrayType *ATy2 = cast<ArrayType>(Ty2);
-    return ATy->getNumElements() == ATy2->getNumElements() &&
-           TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
-  }
-  
-  if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
-    const VectorType *PTy2 = cast<VectorType>(Ty2);
-    return PTy->getNumElements() == PTy2->getNumElements() &&
-           TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
-  }
-  
-  if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
-    const FunctionType *FTy2 = cast<FunctionType>(Ty2);
-    if (FTy->isVarArg() != FTy2->isVarArg() ||
-        FTy->getNumParams() != FTy2->getNumParams() ||
-        !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
-      return false;
-    for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
-      if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
-        return false;
-    }
-    return true;
-  }
-  
-  llvm_unreachable("Unknown derived type!");
-  return false;
-}
-
-namespace llvm { // in namespace llvm so findable by ADL
-static bool TypesEqual(const Type *Ty, const Type *Ty2) {
-  std::map<const Type *, const Type *> EqTypes;
-  return ::TypesEqual(Ty, Ty2, EqTypes);
-}
-}
-
-// AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
-// TargetTy in the type graph.  We know that Ty is an abstract type, so if we
-// ever reach a non-abstract type, we know that we don't need to search the
-// subgraph.
-static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
-                                SmallPtrSet<const Type*, 128> &VisitedTypes) {
-  if (TargetTy == CurTy) return true;
-  if (!CurTy->isAbstract()) return false;
-
-  if (!VisitedTypes.insert(CurTy))
-    return false;  // Already been here.
-
-  for (Type::subtype_iterator I = CurTy->subtype_begin(),
-       E = CurTy->subtype_end(); I != E; ++I)
-    if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
-      return true;
-  return false;
-}
-
-static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
-                                SmallPtrSet<const Type*, 128> &VisitedTypes) {
-  if (TargetTy == CurTy) return true;
-
-  if (!VisitedTypes.insert(CurTy))
-    return false;  // Already been here.
-
-  for (Type::subtype_iterator I = CurTy->subtype_begin(),
-       E = CurTy->subtype_end(); I != E; ++I)
-    if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
-      return true;
-  return false;
-}
-
-/// TypeHasCycleThroughItself - Return true if the specified type has
-/// a cycle back to itself.
-
-namespace llvm { // in namespace llvm so it's findable by ADL
-static bool TypeHasCycleThroughItself(const Type *Ty) {
-  SmallPtrSet<const Type*, 128> VisitedTypes;
-
-  if (Ty->isAbstract()) {  // Optimized case for abstract types.
-    for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
-         I != E; ++I)
-      if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
-        return true;
-  } else {
-    for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
-         I != E; ++I)
-      if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
-        return true;
-  }
-  return false;
-}
-}
-
-//===----------------------------------------------------------------------===//
-// Function Type Factory and Value Class...
-//
-const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
+IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
-
+  
   // Check for the built-in integer types
   switch (NumBits) {
   case  1: return cast<IntegerType>(Type::getInt1Ty(C));
@@ -790,25 +279,13 @@
   default: 
     break;
   }
-
-  LLVMContextImpl *pImpl = C.pImpl;
   
-  IntegerValType IVT(NumBits);
-  IntegerType *ITy = 0;
+  IntegerType *&Entry = C.pImpl->IntegerTypes[NumBits];
   
-  // First, see if the type is already in the table, for which
-  // a reader lock suffices.
-  ITy = pImpl->IntegerTypes.get(IVT);
-    
-  if (!ITy) {
-    // Value not found.  Derive a new type!
-    ITy = new IntegerType(C, NumBits);
-    pImpl->IntegerTypes.add(IVT, ITy);
-  }
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
-#endif
-  return ITy;
+  if (Entry == 0)
+    Entry = new IntegerType(C, NumBits);
+  
+  return Entry;
 }
 
 bool IntegerType::isPowerOf2ByteWidth() const {
@@ -820,123 +297,173 @@
   return APInt::getAllOnesValue(getBitWidth());
 }
 
-FunctionValType FunctionValType::get(const FunctionType *FT) {
-  // Build up a FunctionValType
-  std::vector<const Type *> ParamTypes;
-  ParamTypes.reserve(FT->getNumParams());
-  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
-    ParamTypes.push_back(FT->getParamType(i));
-  return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
-}
+//===----------------------------------------------------------------------===//
+//                       FunctionType Implementation
+//===----------------------------------------------------------------------===//
 
-FunctionType *FunctionType::get(const Type *Result, bool isVarArg) {
-  return get(Result, ArrayRef<const Type *>(), isVarArg);
+FunctionType::FunctionType(const Type *Result, ArrayRef<const Type*> Params,
+                           bool IsVarArgs)
+  : DerivedType(Result->getContext(), FunctionTyID) {
+  Type **SubTys = reinterpret_cast<Type**>(this+1);
+  assert(isValidReturnType(Result) && "invalid return type for function");
+  setSubclassData(IsVarArgs);
+
+  SubTys[0] = const_cast<Type*>(Result);
+
+  for (unsigned i = 0, e = Params.size(); i != e; ++i) {
+    assert(isValidArgumentType(Params[i]) &&
+           "Not a valid type for function argument!");
+    SubTys[i+1] = const_cast<Type*>(Params[i]);
+  }
+
+  ContainedTys = SubTys;
+  NumContainedTys = Params.size() + 1; // + 1 for result type
 }
 
-// FunctionType::get - The factory function for the FunctionType class...
+
+// FunctionType::get - The factory function for the FunctionType class.
 FunctionType *FunctionType::get(const Type *ReturnType,
-                                ArrayRef<const Type*> Params,
-                                bool isVarArg) {
-  FunctionValType VT(ReturnType, Params, isVarArg);
-  FunctionType *FT = 0;
-  
-  LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
+                                ArrayRef<const Type*> Params, bool isVarArg) {
+  // TODO: This is brutally slow.
+  std::vector<Type*> Key;
+  Key.reserve(Params.size()+2);
+  Key.push_back(const_cast<Type*>(ReturnType));
+  for (unsigned i = 0, e = Params.size(); i != e; ++i)
+    Key.push_back(const_cast<Type*>(Params[i]));
+  if (isVarArg)
+    Key.push_back(0);
   
-  FT = pImpl->FunctionTypes.get(VT);
+  FunctionType *&FT = ReturnType->getContext().pImpl->FunctionTypes[Key];
   
-  if (!FT) {
+  if (FT == 0) {
     FT = (FunctionType*) operator new(sizeof(FunctionType) +
-                                    sizeof(PATypeHandle)*(Params.size()+1));
+                                    sizeof(Type*)*(Params.size()+1));
     new (FT) FunctionType(ReturnType, Params, isVarArg);
-    pImpl->FunctionTypes.add(VT, FT);
   }
 
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "Derived new type: " << FT << "\n");
-#endif
   return FT;
 }
 
-ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
-  assert(ElementType && "Can't get array of <null> types!");
-  assert(isValidElementType(ElementType) && "Invalid type for array element!");
 
-  ArrayValType AVT(ElementType, NumElements);
-  ArrayType *AT = 0;
+FunctionType *FunctionType::get(const Type *Result, bool isVarArg) {
+  return get(Result, ArrayRef<const Type *>(), isVarArg);
+}
+
 
-  LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
-  
-  AT = pImpl->ArrayTypes.get(AVT);
-      
-  if (!AT) {
-    // Value not found.  Derive a new type!
-    pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
-  }
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
-#endif
-  return AT;
+/// isValidReturnType - Return true if the specified type is valid as a return
+/// type.
+bool FunctionType::isValidReturnType(const Type *RetTy) {
+  return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
+  !RetTy->isMetadataTy();
 }
 
-bool ArrayType::isValidElementType(const Type *ElemTy) {
-  return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
-         !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
+/// isValidArgumentType - Return true if the specified type is valid as an
+/// argument type.
+bool FunctionType::isValidArgumentType(const Type *ArgTy) {
+  return ArgTy->isFirstClassType();
 }
 
-VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
-  assert(ElementType && "Can't get vector of <null> types!");
+//===----------------------------------------------------------------------===//
+//                       StructType Implementation
+//===----------------------------------------------------------------------===//
+
+// Primitive Constructors.
 
-  VectorValType PVT(ElementType, NumElements);
-  VectorType *PT = 0;
-  
-  LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
+StructType *StructType::get(LLVMContext &Context, ArrayRef<Type*> ETypes, 
+                            bool isPacked) {
+  // FIXME: std::vector is horribly inefficient for this probe.
+  std::vector<Type*> Key;
+  for (unsigned i = 0, e = ETypes.size(); i != e; ++i) {
+    assert(isValidElementType(ETypes[i]) &&
+           "Invalid type for structure element!");
+    Key.push_back(ETypes[i]);
+  }
+  if (isPacked)
+    Key.push_back(0);
   
-  PT = pImpl->VectorTypes.get(PVT);
+  StructType *&ST = Context.pImpl->AnonStructTypes[Key];
     
-  if (!PT) {
-    pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
-  }
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
-#endif
-  return PT;
+  if (ST) return ST;
+  
+  // Value not found.  Create a new type!
+  ST = new StructType(Context);
+  ST->setSubclassData(SCDB_IsAnonymous);  // Anonymous struct.
+  ST->setBody(ETypes, isPacked);
+  return ST;
 }
 
-bool VectorType::isValidElementType(const Type *ElemTy) {
-  return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
-         ElemTy->isOpaqueTy();
+void StructType::setBody(ArrayRef<Type*> Elements, bool isPacked) {
+  assert(isOpaque() && "Struct body already set!");
+  
+  setSubclassData(getSubclassData() | SCDB_HasBody);
+  if (isPacked)
+    setSubclassData(getSubclassData() | SCDB_Packed);
+  
+  Type **Elts = new Type*[Elements.size()];
+  memcpy(Elts, Elements.data(), sizeof(Elements[0])*sizeof(Type*));
+  
+  ContainedTys = Elts;
+  NumContainedTys = Elements.size();
 }
 
-//===----------------------------------------------------------------------===//
-// Struct Type Factory.
-//
-
-StructType *StructType::get(LLVMContext &Context, bool isPacked) {
-  return get(Context, llvm::ArrayRef<const Type*>(), isPacked);
+StructType *StructType::createNamed(LLVMContext &Context, StringRef Name) {
+  StructType *ST = new StructType(Context);
+  ST->setName(Name);
+  return ST;
 }
 
+void StructType::setName(StringRef Name) {
+  if (Name == getName()) return;
 
-StructType *StructType::get(LLVMContext &Context,
-                            ArrayRef<const Type*> ETypes, 
-                            bool isPacked) {
-  StructValType STV(ETypes, isPacked);
-  StructType *ST = 0;
+  if (SymbolTableEntry) {
+    // REMOVE 
+    
+    SymbolTableEntry = 0;
+  }
   
-  LLVMContextImpl *pImpl = Context.pImpl;
   
-  ST = pImpl->StructTypes.get(STV);
-    
-  if (!ST) {
-    // Value not found.  Derive a new type!
-    ST = (StructType*) operator new(sizeof(StructType) +
-                                    sizeof(PATypeHandle) * ETypes.size());
-    new (ST) StructType(Context, ETypes, isPacked);
-    pImpl->StructTypes.add(STV, ST);
+  // If this is just removing the name, we're done.
+  if (Name.empty())
+    return;
+  
+  // Look up the entry for the name.
+  StringMapEntry<StructType*> *Entry =
+    &getContext().pImpl->NamedStructTypes.GetOrCreateValue(Name);
+  
+  // While we have a name collision, try a random rename.
+  if (Entry->getValue()) {
+    SmallString<64> TempStr(Name);
+    TempStr.push_back('.');
+    raw_svector_ostream TmpStream(TempStr);
+   
+    do {
+      TempStr.resize(Name.size()+1);
+      TmpStream.resync();
+      TmpStream << getContext().pImpl->NamedStructTypesUniqueID++;
+      
+      Entry = &getContext().pImpl->
+                 NamedStructTypes.GetOrCreateValue(TmpStream.str());
+    } while (Entry->getValue());
   }
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
-#endif
-  return ST;
+
+  // Okay, we found an entry that isn't used.  It's us!
+  Entry->setValue(this);
+    
+  SymbolTableEntry = Entry;
+}
+
+//===----------------------------------------------------------------------===//
+// StructType Helper functions.
+
+// FIXME: Remove this version.
+StructType *StructType::get(LLVMContext &Context, ArrayRef<const Type*>Elements,
+                            bool isPacked) {
+  return get(Context, ArrayRef<Type*>((Type**)Elements.data(), Elements.size()),
+             isPacked);
+}
+
+StructType *StructType::get(LLVMContext &Context, bool isPacked) {
+  return get(Context, llvm::ArrayRef<const Type*>(), isPacked);
 }
 
 StructType *StructType::get(const Type *type, ...) {
@@ -952,272 +479,172 @@
   return llvm::StructType::get(Ctx, StructFields);
 }
 
-bool StructType::isValidElementType(const Type *ElemTy) {
-  return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
-         !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
+StructType *StructType::createNamed(LLVMContext &Context, StringRef Name,
+                                    ArrayRef<Type*> Elements, bool isPacked) {
+  StructType *ST = createNamed(Context, Name);
+  ST->setBody(Elements, isPacked);
+  return ST;
 }
 
-
-//===----------------------------------------------------------------------===//
-// Pointer Type Factory...
-//
-
-PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
-  assert(ValueType && "Can't get a pointer to <null> type!");
-  assert(ValueType->getTypeID() != VoidTyID &&
-         "Pointer to void is not valid, use i8* instead!");
-  assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
-  PointerValType PVT(ValueType, AddressSpace);
-
-  PointerType *PT = 0;
-  
-  LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
-  
-  PT = pImpl->PointerTypes.get(PVT);
-  
-  if (!PT) {
-    // Value not found.  Derive a new type!
-    pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
-  }
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
-#endif
-  return PT;
+StructType *StructType::createNamed(StringRef Name, ArrayRef<Type*> Elements,
+                                    bool isPacked) {
+  assert(!Elements.empty() &&
+         "This method may not be invoked with an empty list");
+  return createNamed(Elements[0]->getContext(), Name, Elements, isPacked);
 }
 
-const PointerType *Type::getPointerTo(unsigned addrs) const {
-  return PointerType::get(this, addrs);
+StringRef StructType::getName() const {
+  assert(!isAnonymous() && "Anonymous structs never have names");
+  if (SymbolTableEntry == 0) return StringRef();
+  
+  return ((StringMapEntry<StructType*> *)SymbolTableEntry)->getKey();
 }
 
-bool PointerType::isValidElementType(const Type *ElemTy) {
+bool StructType::isValidElementType(const Type *ElemTy) {
   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
-         !ElemTy->isMetadataTy();
+         !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
 }
 
-
-//===----------------------------------------------------------------------===//
-// Opaque Type Factory...
-//
-
-OpaqueType *OpaqueType::get(LLVMContext &C) {
-  OpaqueType *OT = new OpaqueType(C);       // All opaque types are distinct.
-  LLVMContextImpl *pImpl = C.pImpl;
-  pImpl->OpaqueTypes.insert(OT);
-  return OT;
+/// isLayoutIdentical - Return true if this is layout identical to the
+/// specified struct.
+bool StructType::isLayoutIdentical(const StructType *Other) const {
+  if (this == Other) return true;
+  
+  if (isPacked() != Other->isPacked() ||
+      getNumElements() != Other->getNumElements())
+    return false;
+  
+  return std::equal(element_begin(), element_end(), Other->element_begin());
 }
 
 
-
 //===----------------------------------------------------------------------===//
-//                     Derived Type Refinement Functions
+//                       CompositeType Implementation
 //===----------------------------------------------------------------------===//
 
-// addAbstractTypeUser - Notify an abstract type that there is a new user of
-// it.  This function is called primarily by the PATypeHandle class.
-void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
-  assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
-  AbstractTypeUsers.push_back(U);
-}
-
-
-// removeAbstractTypeUser - Notify an abstract type that a user of the class
-// no longer has a handle to the type.  This function is called primarily by
-// the PATypeHandle class.  When there are no users of the abstract type, it
-// is annihilated, because there is no way to get a reference to it ever again.
-//
-void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
-  
-  // Search from back to front because we will notify users from back to
-  // front.  Also, it is likely that there will be a stack like behavior to
-  // users that register and unregister users.
-  //
-  unsigned i;
-  for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
-    assert(i != 0 && "AbstractTypeUser not in user list!");
-
-  --i;  // Convert to be in range 0 <= i < size()
-  assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
-
-  AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
-
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "  remAbstractTypeUser[" << (void*)this << ", "
-               << *this << "][" << i << "] User = " << U << "\n");
-#endif
-
-  if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
-#ifdef DEBUG_MERGE_TYPES
-    DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
-                 << ">[" << (void*)this << "]" << "\n");
-#endif
+Type *CompositeType::getTypeAtIndex(const Value *V) const {
+  if (const StructType *STy = dyn_cast<StructType>(this)) {
+    unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
+    assert(indexValid(Idx) && "Invalid structure index!");
+    return STy->getElementType(Idx);
+  }
   
-    this->destroy();
+  return cast<SequentialType>(this)->getElementType();
+}
+Type *CompositeType::getTypeAtIndex(unsigned Idx) const {
+  if (const StructType *STy = dyn_cast<StructType>(this)) {
+    assert(indexValid(Idx) && "Invalid structure index!");
+    return STy->getElementType(Idx);
   }
+  
+  return cast<SequentialType>(this)->getElementType();
 }
-
-// refineAbstractTypeTo - This function is used when it is discovered
-// that the 'this' abstract type is actually equivalent to the NewType
-// specified. This causes all users of 'this' to switch to reference the more 
-// concrete type NewType and for 'this' to be deleted.  Only used for internal
-// callers.
-//
-void DerivedType::refineAbstractTypeTo(const Type *NewType) {
-  assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
-  assert(this != NewType && "Can't refine to myself!");
-  assert(ForwardType == 0 && "This type has already been refined!");
-
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
-               << *this << "] to [" << (void*)NewType << " "
-               << *NewType << "]!\n");
-#endif
-
-  // Make sure to put the type to be refined to into a holder so that if IT gets
-  // refined, that we will not continue using a dead reference...
-  //
-  PATypeHolder NewTy(NewType);
-  // Any PATypeHolders referring to this type will now automatically forward to
-  // the type we are resolved to.
-  ForwardType = NewType;
-  if (ForwardType->isAbstract())
-    ForwardType->addRef();
-
-  // Add a self use of the current type so that we don't delete ourself until
-  // after the function exits.
-  //
-  PATypeHolder CurrentTy(this);
-
-  // To make the situation simpler, we ask the subclass to remove this type from
-  // the type map, and to replace any type uses with uses of non-abstract types.
-  // This dramatically limits the amount of recursive type trouble we can find
-  // ourselves in.
-  dropAllTypeUses();
-
-  // Iterate over all of the uses of this type, invoking callback.  Each user
-  // should remove itself from our use list automatically.  We have to check to
-  // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
-  // will not cause users to drop off of the use list.  If we resolve to ourself
-  // we succeed!
-  //
-  while (!AbstractTypeUsers.empty() && NewTy != this) {
-    AbstractTypeUser *User = AbstractTypeUsers.back();
-
-    unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
-#ifdef DEBUG_MERGE_TYPES
-    DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
-                 << "] of abstract type [" << (void*)this << " "
-                 << *this << "] to [" << (void*)NewTy.get() << " "
-                 << *NewTy << "]!\n");
-#endif
-    User->refineAbstractType(this, NewTy);
-
-    assert(AbstractTypeUsers.size() != OldSize &&
-           "AbsTyUser did not remove self from user list!");
+bool CompositeType::indexValid(const Value *V) const {
+  if (const StructType *STy = dyn_cast<StructType>(this)) {
+    // Structure indexes require 32-bit integer constants.
+    if (V->getType()->isIntegerTy(32))
+      if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
+        return CU->getZExtValue() < STy->getNumElements();
+    return false;
   }
+  
+  // Sequential types can be indexed by any integer.
+  return V->getType()->isIntegerTy();
+}
 
-  // If we were successful removing all users from the type, 'this' will be
-  // deleted when the last PATypeHolder is destroyed or updated from this type.
-  // This may occur on exit of this function, as the CurrentTy object is
-  // destroyed.
+bool CompositeType::indexValid(unsigned Idx) const {
+  if (const StructType *STy = dyn_cast<StructType>(this))
+    return Idx < STy->getNumElements();
+  // Sequential types can be indexed by any integer.
+  return true;
 }
 
-// notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
-// the current type has transitioned from being abstract to being concrete.
-//
-void DerivedType::notifyUsesThatTypeBecameConcrete() {
-#ifdef DEBUG_MERGE_TYPES
-  DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
-#endif
-
-  unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
-  while (!AbstractTypeUsers.empty()) {
-    AbstractTypeUser *ATU = AbstractTypeUsers.back();
-    ATU->typeBecameConcrete(this);
 
-    assert(AbstractTypeUsers.size() < OldSize-- &&
-           "AbstractTypeUser did not remove itself from the use list!");
-  }
+//===----------------------------------------------------------------------===//
+//                           ArrayType Implementation
+//===----------------------------------------------------------------------===//
+
+ArrayType::ArrayType(Type *ElType, uint64_t NumEl)
+  : SequentialType(ArrayTyID, ElType) {
+  NumElements = NumEl;
 }
 
-// refineAbstractType - Called when a contained type is found to be more
-// concrete - this could potentially change us from an abstract type to a
-// concrete type.
-//
-void FunctionType::refineAbstractType(const DerivedType *OldType,
-                                      const Type *NewType) {
-  LLVMContextImpl *pImpl = OldType->getContext().pImpl;
-  pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
+
+ArrayType *ArrayType::get(const Type *elementType, uint64_t NumElements) {
+  Type *ElementType = const_cast<Type*>(elementType);
+  assert(isValidElementType(ElementType) && "Invalid type for array element!");
+    
+  ArrayType *&Entry = ElementType->getContext().pImpl
+     ->ArrayTypes[std::make_pair(ElementType, NumElements)];
+  
+  if (Entry == 0)
+    Entry = new ArrayType(ElementType, NumElements);
+  return Entry;
 }
 
-void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
-  LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
-  pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
+bool ArrayType::isValidElementType(const Type *ElemTy) {
+  return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
+         !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
 }
 
+//===----------------------------------------------------------------------===//
+//                          VectorType Implementation
+//===----------------------------------------------------------------------===//
 
-// refineAbstractType - Called when a contained type is found to be more
-// concrete - this could potentially change us from an abstract type to a
-// concrete type.
-//
-void ArrayType::refineAbstractType(const DerivedType *OldType,
-                                   const Type *NewType) {
-  LLVMContextImpl *pImpl = OldType->getContext().pImpl;
-  pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
+VectorType::VectorType(Type *ElType, unsigned NumEl)
+  : SequentialType(VectorTyID, ElType) {
+  NumElements = NumEl;
 }
 
-void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
-  LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
-  pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
+VectorType *VectorType::get(const Type *elementType, unsigned NumElements) {
+  Type *ElementType = const_cast<Type*>(elementType);
+  assert(NumElements > 0 && "#Elements of a VectorType must be greater than 0");
+  assert(isValidElementType(ElementType) &&
+         "Elements of a VectorType must be a primitive type");
+  
+  VectorType *&Entry = ElementType->getContext().pImpl
+    ->VectorTypes[std::make_pair(ElementType, NumElements)];
+  
+  if (Entry == 0)
+    Entry = new VectorType(ElementType, NumElements);
+  return Entry;
 }
 
-// refineAbstractType - Called when a contained type is found to be more
-// concrete - this could potentially change us from an abstract type to a
-// concrete type.
-//
-void VectorType::refineAbstractType(const DerivedType *OldType,
-                                   const Type *NewType) {
-  LLVMContextImpl *pImpl = OldType->getContext().pImpl;
-  pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
+bool VectorType::isValidElementType(const Type *ElemTy) {
+  return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy();
 }
 
-void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
-  LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
-  pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
-}
+//===----------------------------------------------------------------------===//
+//                         PointerType Implementation
+//===----------------------------------------------------------------------===//
 
-// refineAbstractType - Called when a contained type is found to be more
-// concrete - this could potentially change us from an abstract type to a
-// concrete type.
-//
-void StructType::refineAbstractType(const DerivedType *OldType,
-                                    const Type *NewType) {
-  LLVMContextImpl *pImpl = OldType->getContext().pImpl;
-  pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
-}
+PointerType *PointerType::get(const Type *eltTy, unsigned AddressSpace) {
+  Type *EltTy = const_cast<Type*>(eltTy);
+  assert(EltTy && "Can't get a pointer to <null> type!");
+  assert(isValidElementType(EltTy) && "Invalid type for pointer element!");
+  
+  LLVMContextImpl *CImpl = EltTy->getContext().pImpl;
+  
+  // Since AddressSpace #0 is the common case, we special case it.
+  PointerType *&Entry = AddressSpace == 0 ? CImpl->PointerTypes[EltTy]
+     : CImpl->ASPointerTypes[std::make_pair(EltTy, AddressSpace)];
 
-void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
-  LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
-  pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
+  if (Entry == 0)
+    Entry = new PointerType(EltTy, AddressSpace);
+  return Entry;
 }
 
-// refineAbstractType - Called when a contained type is found to be more
-// concrete - this could potentially change us from an abstract type to a
-// concrete type.
-//
-void PointerType::refineAbstractType(const DerivedType *OldType,
-                                     const Type *NewType) {
-  LLVMContextImpl *pImpl = OldType->getContext().pImpl;
-  pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
-}
 
-void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
-  LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
-  pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
+PointerType::PointerType(Type *E, unsigned AddrSpace)
+  : SequentialType(PointerTyID, E) {
+  setSubclassData(AddrSpace);
 }
 
-namespace llvm {
-raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
-  T.print(OS);
-  return OS;
+PointerType *Type::getPointerTo(unsigned addrs) const {
+  return PointerType::get(this, addrs);
 }
+
+bool PointerType::isValidElementType(const Type *ElemTy) {
+  return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
+         !ElemTy->isMetadataTy();
 }

Modified: llvm/branches/type-system-rewrite/lib/VMCore/TypeSymbolTable.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/TypeSymbolTable.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/TypeSymbolTable.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/TypeSymbolTable.cpp Mon Jun 20 01:45:54 2011
@@ -11,158 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "llvm/TypeSymbolTable.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/ADT/StringExtras.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/ManagedStatic.h"
-#include "llvm/Support/raw_ostream.h"
-#include <algorithm>
-using namespace llvm;
-
-#define DEBUG_SYMBOL_TABLE 0
-#define DEBUG_ABSTYPE 0
-
-TypeSymbolTable::~TypeSymbolTable() {
-  // Drop all abstract type references in the type plane...
-  for (iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
-    if (TI->second->isAbstract())   // If abstract, drop the reference...
-      cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
-  }
-}
-
-std::string TypeSymbolTable::getUniqueName(StringRef BaseName) const {
-  std::string TryName = BaseName;
-  
-  const_iterator End = tmap.end();
-
-  // See if the name exists
-  while (tmap.find(TryName) != End)            // Loop until we find a free
-    TryName = BaseName.str() + utostr(++LastUnique); // name in the symbol table
-  return TryName;
-}
-
-// lookup a type by name - returns null on failure
-Type* TypeSymbolTable::lookup(StringRef Name) const {
-  const_iterator TI = tmap.find(Name);
-  Type* result = 0;
-  if (TI != tmap.end())
-    result = const_cast<Type*>(TI->second);
-  return result;
-}
-
-// remove - Remove a type from the symbol table...
-Type* TypeSymbolTable::remove(iterator Entry) {
-  assert(Entry != tmap.end() && "Invalid entry to remove!");
-  const Type* Result = Entry->second;
-
-#if DEBUG_SYMBOL_TABLE
-  dump();
-  dbgs() << " Removing Value: " << *Result << "\n";
+#if 0
+#error REMOVE ME
 #endif
 
-  tmap.erase(Entry);
-  
-  // If we are removing an abstract type, remove the symbol table from it's use
-  // list...
-  if (Result->isAbstract()) {
-#if DEBUG_ABSTYPE
-    dbgs() << "Removing abstract type from symtab"
-           << *Result << "\n";
-#endif
-    cast<DerivedType>(Result)->removeAbstractTypeUser(this);
-  }
-
-  return const_cast<Type*>(Result);
-}
-
-
-// insert - Insert a type into the symbol table with the specified name...
-void TypeSymbolTable::insert(StringRef Name, const Type* T) {
-  assert(T && "Can't insert null type into symbol table!");
-
-  if (tmap.insert(std::make_pair(Name, T)).second) {
-    // Type inserted fine with no conflict.
-    
-#if DEBUG_SYMBOL_TABLE
-    dump();
-    dbgs() << " Inserted type: " << Name << ": " << *T << "\n";
-#endif
-  } else {
-    // If there is a name conflict...
-    
-    // Check to see if there is a naming conflict.  If so, rename this type!
-    std::string UniqueName = Name;
-    if (lookup(Name))
-      UniqueName = getUniqueName(Name);
-    
-#if DEBUG_SYMBOL_TABLE
-    dump();
-    dbgs() << " Inserting type: " << UniqueName << ": "
-           << *T << "\n";
-#endif
-
-    // Insert the tmap entry
-    tmap.insert(make_pair(UniqueName, T));
-  }
-  
-  // If we are adding an abstract type, add the symbol table to it's use list.
-  if (T->isAbstract()) {
-    cast<DerivedType>(T)->addAbstractTypeUser(this);
-#if DEBUG_ABSTYPE
-    dbgs() << "Added abstract type to ST: " << *T << "\n";
-#endif
-  }
-}
-
-// This function is called when one of the types in the type plane are refined
-void TypeSymbolTable::refineAbstractType(const DerivedType *OldType,
-                                         const Type *NewType) {
-  // Loop over all of the types in the symbol table, replacing any references
-  // to OldType with references to NewType.  Note that there may be multiple
-  // occurrences, and although we only need to remove one at a time, it's
-  // faster to remove them all in one pass.
-  //
-  for (iterator I = begin(), E = end(); I != E; ++I) {
-    // FIXME when Types aren't const.
-    if (I->second == const_cast<DerivedType *>(OldType)) {
-#if DEBUG_ABSTYPE
-      dbgs() << "Removing type " << *OldType << "\n";
-#endif
-      OldType->removeAbstractTypeUser(this);
-
-      // TODO FIXME when types aren't const
-      I->second = const_cast<Type *>(NewType);
-      if (NewType->isAbstract()) {
-#if DEBUG_ABSTYPE
-        dbgs() << "Added type " << *NewType << "\n";
-#endif
-        cast<DerivedType>(NewType)->addAbstractTypeUser(this);
-      }
-    }
-  }
-}
-
-
-// Handle situation where type becomes Concreate from Abstract
-void TypeSymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
-  // Loop over all of the types in the symbol table, dropping any abstract
-  // type user entries for AbsTy which occur because there are names for the
-  // type.
-  for (iterator TI = begin(), TE = end(); TI != TE; ++TI)
-    if (TI->second == const_cast<Type*>(static_cast<const Type*>(AbsTy)))
-      AbsTy->removeAbstractTypeUser(this);
-}
-
-static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
-  dbgs() << "  '" << T.first << "' = ";
-  T.second->dump();
-  dbgs() << "\n";
-}
-
-void TypeSymbolTable::dump() const {
-  dbgs() << "TypeSymbolPlane: ";
-  for_each(tmap.begin(), tmap.end(), DumpTypes);
-}
-
+int x;

Modified: llvm/branches/type-system-rewrite/lib/VMCore/TypesContext.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/TypesContext.h?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/TypesContext.h (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/TypesContext.h Mon Jun 20 01:45:54 2011
@@ -1,426 +1,4 @@
 //===-- TypesContext.h - Types-related Context Internals ------------------===//
-//
-//                     The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-//  This file defines various helper methods and classes used by
-// LLVMContextImpl for creating and managing types.
-//
-//===----------------------------------------------------------------------===//
 
-#ifndef LLVM_TYPESCONTEXT_H
-#define LLVM_TYPESCONTEXT_H
 
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/STLExtras.h"
-#include <map>
-
-
-//===----------------------------------------------------------------------===//
-//                       Derived Type Factory Functions
-//===----------------------------------------------------------------------===//
-namespace llvm {
-
-/// getSubElementHash - Generate a hash value for all of the SubType's of this
-/// type.  The hash value is guaranteed to be zero if any of the subtypes are 
-/// an opaque type.  Otherwise we try to mix them in as well as possible, but do
-/// not look at the subtype's subtype's.
-static unsigned getSubElementHash(const Type *Ty) {
-  unsigned HashVal = 0;
-  for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
-       I != E; ++I) {
-    HashVal *= 32;
-    const Type *SubTy = I->get();
-    HashVal += SubTy->getTypeID();
-    switch (SubTy->getTypeID()) {
-    default: break;
-    case Type::OpaqueTyID: return 0;    // Opaque -> hash = 0 no matter what.
-    case Type::IntegerTyID:
-      HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
-      break;
-    case Type::FunctionTyID:
-      HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 
-                 cast<FunctionType>(SubTy)->isVarArg();
-      break;
-    case Type::ArrayTyID:
-      HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
-      break;
-    case Type::VectorTyID:
-      HashVal ^= cast<VectorType>(SubTy)->getNumElements();
-      break;
-    case Type::StructTyID:
-      HashVal ^= cast<StructType>(SubTy)->getNumElements();
-      break;
-    case Type::PointerTyID:
-      HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
-      break;
-    }
-  }
-  return HashVal ? HashVal : 1;  // Do not return zero unless opaque subty.
-}
-
-//===----------------------------------------------------------------------===//
-// Integer Type Factory...
-//
-class IntegerValType {
-  uint32_t bits;
-public:
-  IntegerValType(uint32_t numbits) : bits(numbits) {}
-
-  static IntegerValType get(const IntegerType *Ty) {
-    return IntegerValType(Ty->getBitWidth());
-  }
-
-  static unsigned hashTypeStructure(const IntegerType *Ty) {
-    return (unsigned)Ty->getBitWidth();
-  }
-
-  inline bool operator<(const IntegerValType &IVT) const {
-    return bits < IVT.bits;
-  }
-};
-
-// PointerValType - Define a class to hold the key that goes into the TypeMap
-//
-class PointerValType {
-  const Type *ValTy;
-  unsigned AddressSpace;
-public:
-  PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
-
-  static PointerValType get(const PointerType *PT) {
-    return PointerValType(PT->getElementType(), PT->getAddressSpace());
-  }
-
-  static unsigned hashTypeStructure(const PointerType *PT) {
-    return getSubElementHash(PT);
-  }
-
-  bool operator<(const PointerValType &MTV) const {
-    if (AddressSpace < MTV.AddressSpace) return true;
-    return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
-  }
-};
-
-//===----------------------------------------------------------------------===//
-// Array Type Factory...
-//
-class ArrayValType {
-  const Type *ValTy;
-  uint64_t Size;
-public:
-  ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
-
-  static ArrayValType get(const ArrayType *AT) {
-    return ArrayValType(AT->getElementType(), AT->getNumElements());
-  }
-
-  static unsigned hashTypeStructure(const ArrayType *AT) {
-    return (unsigned)AT->getNumElements();
-  }
-
-  inline bool operator<(const ArrayValType &MTV) const {
-    if (Size < MTV.Size) return true;
-    return Size == MTV.Size && ValTy < MTV.ValTy;
-  }
-};
-
-//===----------------------------------------------------------------------===//
-// Vector Type Factory...
-//
-class VectorValType {
-  const Type *ValTy;
-  unsigned Size;
-public:
-  VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
-
-  static VectorValType get(const VectorType *PT) {
-    return VectorValType(PT->getElementType(), PT->getNumElements());
-  }
-
-  static unsigned hashTypeStructure(const VectorType *PT) {
-    return PT->getNumElements();
-  }
-
-  inline bool operator<(const VectorValType &MTV) const {
-    if (Size < MTV.Size) return true;
-    return Size == MTV.Size && ValTy < MTV.ValTy;
-  }
-};
-
-// StructValType - Define a class to hold the key that goes into the TypeMap
-//
-class StructValType {
-  std::vector<const Type*> ElTypes;
-  bool packed;
-public:
-  StructValType(ArrayRef<const Type*> args, bool isPacked)
-    : ElTypes(args.vec()), packed(isPacked) {}
-
-  static StructValType get(const StructType *ST) {
-    std::vector<const Type *> ElTypes;
-    ElTypes.reserve(ST->getNumElements());
-    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
-      ElTypes.push_back(ST->getElementType(i));
-
-    return StructValType(ElTypes, ST->isPacked());
-  }
-
-  static unsigned hashTypeStructure(const StructType *ST) {
-    return ST->getNumElements();
-  }
-
-  inline bool operator<(const StructValType &STV) const {
-    if (ElTypes < STV.ElTypes) return true;
-    else if (ElTypes > STV.ElTypes) return false;
-    else return (int)packed < (int)STV.packed;
-  }
-};
-
-// FunctionValType - Define a class to hold the key that goes into the TypeMap
-//
-class FunctionValType {
-  const Type *RetTy;
-  std::vector<const Type*> ArgTypes;
-  bool isVarArg;
-public:
-  FunctionValType(const Type *ret, ArrayRef<const Type*> args, bool isVA)
-    : RetTy(ret), ArgTypes(args.vec()), isVarArg(isVA) {}
-
-  static FunctionValType get(const FunctionType *FT);
-
-  static unsigned hashTypeStructure(const FunctionType *FT) {
-    unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
-    return Result;
-  }
-
-  inline bool operator<(const FunctionValType &MTV) const {
-    if (RetTy < MTV.RetTy) return true;
-    if (RetTy > MTV.RetTy) return false;
-    if (isVarArg < MTV.isVarArg) return true;
-    if (isVarArg > MTV.isVarArg) return false;
-    if (ArgTypes < MTV.ArgTypes) return true;
-    if (ArgTypes > MTV.ArgTypes) return false;
-    return false;
-  }
-};
-
-class TypeMapBase {
-protected:
-  /// TypesByHash - Keep track of types by their structure hash value.  Note
-  /// that we only keep track of types that have cycles through themselves in
-  /// this map.
-  ///
-  std::multimap<unsigned, PATypeHolder> TypesByHash;
-
-  ~TypeMapBase() {
-    // PATypeHolder won't destroy non-abstract types.
-    // We can't destroy them by simply iterating, because
-    // they may contain references to each-other.
-    for (std::multimap<unsigned, PATypeHolder>::iterator I
-         = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
-      Type *Ty = const_cast<Type*>(I->second.Ty);
-      I->second.destroy();
-      // We can't invoke destroy or delete, because the type may
-      // contain references to already freed types.
-      // So we have to destruct the object the ugly way.
-      if (Ty) {
-        Ty->AbstractTypeUsers.clear();
-        static_cast<const Type*>(Ty)->Type::~Type();
-        operator delete(Ty);
-      }
-    }
-  }
-
-public:
-  void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
-    std::multimap<unsigned, PATypeHolder>::iterator I =
-      TypesByHash.lower_bound(Hash);
-    for (; I != TypesByHash.end() && I->first == Hash; ++I) {
-      if (I->second == Ty) {
-        TypesByHash.erase(I);
-        return;
-      }
-    }
-
-    // This must be do to an opaque type that was resolved.  Switch down to hash
-    // code of zero.
-    assert(Hash && "Didn't find type entry!");
-    RemoveFromTypesByHash(0, Ty);
-  }
-
-  /// TypeBecameConcrete - When Ty gets a notification that TheType just became
-  /// concrete, drop uses and make Ty non-abstract if we should.
-  void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
-    // If the element just became concrete, remove 'ty' from the abstract
-    // type user list for the type.  Do this for as many times as Ty uses
-    // OldType.
-    for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
-         I != E; ++I)
-      if (I->get() == TheType)
-        TheType->removeAbstractTypeUser(Ty);
-
-    // If the type is currently thought to be abstract, rescan all of our
-    // subtypes to see if the type has just become concrete!  Note that this
-    // may send out notifications to AbstractTypeUsers that types become
-    // concrete.
-    if (Ty->isAbstract())
-      Ty->PromoteAbstractToConcrete();
-  }
-};
-
-// TypeMap - Make sure that only one instance of a particular type may be
-// created on any given run of the compiler... note that this involves updating
-// our map if an abstract type gets refined somehow.
-//
-template<class ValType, class TypeClass>
-class TypeMap : public TypeMapBase {
-  std::map<ValType, PATypeHolder> Map;
-public:
-  typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
-
-  inline TypeClass *get(const ValType &V) {
-    iterator I = Map.find(V);
-    return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
-  }
-
-  inline void add(const ValType &V, TypeClass *Ty) {
-    Map.insert(std::make_pair(V, Ty));
-
-    // If this type has a cycle, remember it.
-    TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
-    print("add");
-  }
-  
-  /// RefineAbstractType - This method is called after we have merged a type
-  /// with another one.  We must now either merge the type away with
-  /// some other type or reinstall it in the map with it's new configuration.
-  void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
-                        const Type *NewType) {
-#ifdef DEBUG_MERGE_TYPES
-    DEBUG(dbgs() << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
-                 << "], " << (void*)NewType << " [" << *NewType << "])\n");
-#endif
-    
-    // Otherwise, we are changing one subelement type into another.  Clearly the
-    // OldType must have been abstract, making us abstract.
-    assert(Ty->isAbstract() && "Refining a non-abstract type!");
-    assert(OldType != NewType);
-
-    // Make a temporary type holder for the type so that it doesn't disappear on
-    // us when we erase the entry from the map.
-    PATypeHolder TyHolder = Ty;
-
-    // The old record is now out-of-date, because one of the children has been
-    // updated.  Remove the obsolete entry from the map.
-    unsigned NumErased = Map.erase(ValType::get(Ty));
-    assert(NumErased && "Element not found!"); (void)NumErased;
-
-    // Remember the structural hash for the type before we start hacking on it,
-    // in case we need it later.
-    unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
-
-    // Find the type element we are refining... and change it now!
-    for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
-      if (Ty->ContainedTys[i] == OldType)
-        Ty->ContainedTys[i] = NewType;
-    unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
-    
-    // If there are no cycles going through this node, we can do a simple,
-    // efficient lookup in the map, instead of an inefficient nasty linear
-    // lookup.
-    if (!TypeHasCycleThroughItself(Ty)) {
-      typename std::map<ValType, PATypeHolder>::iterator I;
-      bool Inserted;
-
-      tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
-      if (!Inserted) {
-        // Refined to a different type altogether?
-        RemoveFromTypesByHash(OldTypeHash, Ty);
-
-        // We already have this type in the table.  Get rid of the newly refined
-        // type.
-        TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
-        Ty->refineAbstractTypeTo(NewTy);
-        return;
-      }
-    } else {
-      // Now we check to see if there is an existing entry in the table which is
-      // structurally identical to the newly refined type.  If so, this type
-      // gets refined to the pre-existing type.
-      //
-      std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
-      tie(I, E) = TypesByHash.equal_range(NewTypeHash);
-      Entry = E;
-      for (; I != E; ++I) {
-        if (I->second == Ty) {
-          // Remember the position of the old type if we see it in our scan.
-          Entry = I;
-          continue;
-        }
-        
-        if (!TypesEqual(Ty, I->second))
-          continue;
-        
-        TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
-
-        // Remove the old entry form TypesByHash.  If the hash values differ
-        // now, remove it from the old place.  Otherwise, continue scanning
-        // within this hashcode to reduce work.
-        if (NewTypeHash != OldTypeHash) {
-          RemoveFromTypesByHash(OldTypeHash, Ty);
-        } else {
-          if (Entry == E) {
-            // Find the location of Ty in the TypesByHash structure if we
-            // haven't seen it already.
-            while (I->second != Ty) {
-              ++I;
-              assert(I != E && "Structure doesn't contain type??");
-            }
-            Entry = I;
-          }
-          TypesByHash.erase(Entry);
-        }
-        Ty->refineAbstractTypeTo(NewTy);
-        return;
-      }
-
-      // If there is no existing type of the same structure, we reinsert an
-      // updated record into the map.
-      Map.insert(std::make_pair(ValType::get(Ty), Ty));
-    }
-
-    // If the hash codes differ, update TypesByHash
-    if (NewTypeHash != OldTypeHash) {
-      RemoveFromTypesByHash(OldTypeHash, Ty);
-      TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
-    }
-    
-    // If the type is currently thought to be abstract, rescan all of our
-    // subtypes to see if the type has just become concrete!  Note that this
-    // may send out notifications to AbstractTypeUsers that types become
-    // concrete.
-    if (Ty->isAbstract())
-      Ty->PromoteAbstractToConcrete();
-  }
-
-  void print(const char *Arg) const {
-#ifdef DEBUG_MERGE_TYPES
-    DEBUG(dbgs() << "TypeMap<>::" << Arg << " table contents:\n");
-    unsigned i = 0;
-    for (typename std::map<ValType, PATypeHolder>::const_iterator I
-           = Map.begin(), E = Map.end(); I != E; ++I)
-      DEBUG(dbgs() << " " << (++i) << ". " << (void*)I->second.get() << " "
-                   << *I->second.get() << "\n");
-#endif
-  }
-
-  void dump() const { print("dump output"); }
-};
-}
-
-#endif
+#error REMOVE THIS FILE
\ No newline at end of file

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Value.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Value.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Value.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Value.cpp Mon Jun 20 01:45:54 2011
@@ -35,22 +35,21 @@
 //                                Value Class
 //===----------------------------------------------------------------------===//
 
-static inline const Type *checkType(const Type *Ty) {
+static inline Type *checkType(const Type *Ty) {
   assert(Ty && "Value defined with a null type: Error!");
-  return Ty;
+  return const_cast<Type*>(Ty);
 }
 
 Value::Value(const Type *ty, unsigned scid)
   : SubclassID(scid), HasValueHandle(0),
-    SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
+    SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
     UseList(0), Name(0) {
+  // FIXME: Why isn't this in the subclass gunk??
   if (isa<CallInst>(this) || isa<InvokeInst>(this))
-    assert((VTy->isFirstClassType() || VTy->isVoidTy() ||
-            ty->isOpaqueTy() || VTy->isStructTy()) &&
-           "invalid CallInst  type!");
+    assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
+           "invalid CallInst type!");
   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
-    assert((VTy->isFirstClassType() || VTy->isVoidTy() ||
-            ty->isOpaqueTy()) &&
+    assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
            "Cannot create non-first-class values except for constants!");
 }
 

Modified: llvm/branches/type-system-rewrite/lib/VMCore/Verifier.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/type-system-rewrite/lib/VMCore/Verifier.cpp?rev=133420&r1=133419&r2=133420&view=diff
==============================================================================
--- llvm/branches/type-system-rewrite/lib/VMCore/Verifier.cpp (original)
+++ llvm/branches/type-system-rewrite/lib/VMCore/Verifier.cpp Mon Jun 20 01:45:54 2011
@@ -49,7 +49,6 @@
 #include "llvm/Module.h"
 #include "llvm/Pass.h"
 #include "llvm/PassManager.h"
-#include "llvm/TypeSymbolTable.h"
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/CodeGen/ValueTypes.h"
@@ -109,54 +108,6 @@
 static char &PreVerifyID = PreVerifier::ID;
 
 namespace {
-  class TypeSet : public AbstractTypeUser {
-  public:
-    TypeSet() {}
-
-    /// Insert a type into the set of types.
-    bool insert(const Type *Ty) {
-      if (!Types.insert(Ty))
-        return false;
-      if (Ty->isAbstract())
-        Ty->addAbstractTypeUser(this);
-      return true;
-    }
-
-    // Remove ourselves as abstract type listeners for any types that remain
-    // abstract when the TypeSet is destroyed.
-    ~TypeSet() {
-      for (SmallSetVector<const Type *, 16>::iterator I = Types.begin(),
-             E = Types.end(); I != E; ++I) {
-        const Type *Ty = *I;
-        if (Ty->isAbstract())
-          Ty->removeAbstractTypeUser(this);
-      }
-    }
-
-    // Abstract type user interface.
-
-    /// Remove types from the set when refined. Do not insert the type it was
-    /// refined to because that type hasn't been verified yet.
-    void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
-      Types.remove(OldTy);
-      OldTy->removeAbstractTypeUser(this);
-    }
-
-    /// Stop listening for changes to a type which is no longer abstract.
-    void typeBecameConcrete(const DerivedType *AbsTy) {
-      AbsTy->removeAbstractTypeUser(this);
-    }
-
-    void dump() const {}
-
-  private:
-    SmallSetVector<const Type *, 16> Types;
-
-    // Disallow copying.
-    TypeSet(const TypeSet &);
-    TypeSet &operator=(const TypeSet &);
-  };
-
   struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
     static char ID; // Pass ID, replacement for typeid
     bool Broken;          // Is this module found to be broken?
@@ -176,9 +127,6 @@
     /// an instruction in the same block.
     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
 
-    /// Types - keep track of the types that have been checked already.
-    TypeSet Types;
-
     /// MDNodes - keep track of the metadata nodes that have been checked
     /// already.
     SmallPtrSet<MDNode *, 32> MDNodes;
@@ -199,7 +147,6 @@
     bool doInitialization(Module &M) {
       Mod = &M;
       Context = &M.getContext();
-      verifyTypeSymbolTable(M.getTypeSymbolTable());
 
       // If this is a real pass, in a pass manager, we must abort before
       // returning back to the pass manager, or else the pass manager may try to
@@ -285,7 +232,6 @@
 
 
     // Verification methods...
-    void verifyTypeSymbolTable(TypeSymbolTable &ST);
     void visitGlobalValue(GlobalValue &GV);
     void visitGlobalVariable(GlobalVariable &GV);
     void visitGlobalAlias(GlobalAlias &GA);
@@ -345,7 +291,6 @@
                               bool isReturnValue, const Value *V);
     void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
                              const Value *V);
-    void VerifyType(const Type *Ty);
 
     void WriteValue(const Value *V) {
       if (!V) return;
@@ -359,8 +304,7 @@
 
     void WriteType(const Type *T) {
       if (!T) return;
-      MessagesStr << ' ';
-      WriteTypeSymbolic(MessagesStr, T, Mod);
+      MessagesStr << ' ' << *T;
     }
 
 
@@ -568,11 +512,6 @@
   }
 }
 
-void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
-  for (TypeSymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
-    VerifyType(I->second);
-}
-
 // VerifyParameterAttrs - Check the given attributes for an argument or return
 // value of the specified type.  The value V is printed in error messages.
 void Verifier::VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
@@ -1195,11 +1134,11 @@
     }
 
   // Verify that there's no metadata unless it's a direct call to an intrinsic.
-  if (!CS.getCalledFunction() ||
+  if (CS.getCalledFunction() == 0 ||
       !CS.getCalledFunction()->getName().startswith("llvm.")) {
     for (FunctionType::param_iterator PI = FTy->param_begin(),
            PE = FTy->param_end(); PI != PE; ++PI)
-      Assert1(!PI->get()->isMetadataTy(),
+      Assert1(!(*PI)->isMetadataTy(),
               "Function has metadata parameter but isn't an intrinsic", I);
   }
 
@@ -1542,69 +1481,6 @@
     }
   }
   InstsInThisBlock.insert(&I);
-
-  VerifyType(I.getType());
-}
-
-/// VerifyType - Verify that a type is well formed.
-///
-void Verifier::VerifyType(const Type *Ty) {
-  if (!Types.insert(Ty)) return;
-
-  Assert1(Context == &Ty->getContext(),
-          "Type context does not match Module context!", Ty);
-
-  switch (Ty->getTypeID()) {
-  case Type::FunctionTyID: {
-    const FunctionType *FTy = cast<FunctionType>(Ty);
-
-    const Type *RetTy = FTy->getReturnType();
-    Assert2(FunctionType::isValidReturnType(RetTy),
-            "Function type with invalid return type", RetTy, FTy);
-    VerifyType(RetTy);
-
-    for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
-      const Type *ElTy = FTy->getParamType(i);
-      Assert2(FunctionType::isValidArgumentType(ElTy),
-              "Function type with invalid parameter type", ElTy, FTy);
-      VerifyType(ElTy);
-    }
-    break;
-  }
-  case Type::StructTyID: {
-    const StructType *STy = cast<StructType>(Ty);
-    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
-      const Type *ElTy = STy->getElementType(i);
-      Assert2(StructType::isValidElementType(ElTy),
-              "Structure type with invalid element type", ElTy, STy);
-      VerifyType(ElTy);
-    }
-    break;
-  }
-  case Type::ArrayTyID: {
-    const ArrayType *ATy = cast<ArrayType>(Ty);
-    Assert1(ArrayType::isValidElementType(ATy->getElementType()),
-            "Array type with invalid element type", ATy);
-    VerifyType(ATy->getElementType());
-    break;
-  }
-  case Type::PointerTyID: {
-    const PointerType *PTy = cast<PointerType>(Ty);
-    Assert1(PointerType::isValidElementType(PTy->getElementType()),
-            "Pointer type with invalid element type", PTy);
-    VerifyType(PTy->getElementType());
-    break;
-  }
-  case Type::VectorTyID: {
-    const VectorType *VTy = cast<VectorType>(Ty);
-    Assert1(VectorType::isValidElementType(VTy->getElementType()),
-            "Vector type with invalid element type", VTy);
-    VerifyType(VTy->getElementType());
-    break;
-  }
-  default:
-    break;
-  }
 }
 
 // Flags used by TableGen to mark intrinsic parameters with the





More information about the llvm-branch-commits mailing list