Start using the new and improve interface to FunctionType arguments
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
index 773ea7a0f5f9eda0c3c984ba1ebe7e5775b2de8a..0981eabd82ed7d5c68b146dfd9de54b8762baba5 100644 (file)
@@ -1,8 +1,15 @@
-//===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
+//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
 //
 //  This file implements the bison parser for LLVM assembly languages files.
 //
-//===------------------------------------------------------------------------=//
+//===----------------------------------------------------------------------===//
 
 %{
 #include "ParserInternals.h"
@@ -13,7 +20,6 @@
 #include "llvm/iOperators.h"
 #include "llvm/iPHINode.h"
 #include "Support/STLExtras.h"
-#include "Support/DepthFirstIterator.h"
 #include <list>
 #include <utility>
 #include <algorithm>
@@ -22,6 +28,8 @@ int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
 int yylex();                       // declaration" of xxx warnings.
 int yyparse();
 
+namespace llvm {
+
 static Module *ParserResult;
 std::string CurFilename;
 
@@ -37,6 +45,14 @@ std::string CurFilename;
 
 #define YYERROR_VERBOSE 1
 
+// HACK ALERT: This variable is used to implement the automatic conversion of
+// variable argument instructions from their old to new forms.  When this
+// compatiblity "Feature" is removed, this should be too.
+//
+static BasicBlock *CurBB;
+static bool ObsoleteVarArgs;
+
+
 // This contains info used when building the body of a function.  It is
 // destroyed when the function is completed.
 //
@@ -103,7 +119,7 @@ static struct PerModuleInfo {
       
       // Loop over all of the uses of the GlobalValue.  The only thing they are
       // allowed to be is ConstantPointerRef's.
-      assert(OldGV->use_size() == 1 && "Only one reference should exist!");
+      assert(OldGV->hasOneUse() && "Only one reference should exist!");
       User *U = OldGV->use_back();  // Must be a ConstantPointerRef...
       ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
         
@@ -130,6 +146,7 @@ static struct PerFunctionInfo {
   std::vector<ValueList> LateResolveValues;
   std::vector<PATypeHolder> Types;
   std::map<ValID, PATypeHolder> LateResolveTypes;
+  SymbolTable LocalSymtab;
   bool isDeclare;                // Is this function a forward declararation?
 
   inline PerFunctionInfo() {
@@ -137,8 +154,6 @@ static struct PerFunctionInfo {
     isDeclare = false;
   }
 
-  inline ~PerFunctionInfo() {}
-
   inline void FunctionStart(Function *M) {
     CurrentFunction = M;
   }
@@ -168,13 +183,14 @@ static struct PerFunctionInfo {
     CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
 
     Values.clear();         // Clear out function local definitions
-    Types.clear();
+    Types.clear();          // Clear out function local types
+    LocalSymtab.clear();    // Clear out function local symbol table
     CurrentFunction = 0;
     isDeclare = false;
   }
-} CurMeth;  // Info for the current function...
+} CurFun;  // Info for the current function...
 
-static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
+static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
 
 
 //===----------------------------------------------------------------------===//
@@ -182,7 +198,7 @@ static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
 //===----------------------------------------------------------------------===//
 
 static int InsertValue(Value *D,
-                       std::vector<ValueList> &ValueTab = CurMeth.Values) {
+                       std::vector<ValueList> &ValueTab = CurFun.Values) {
   if (D->hasName()) return -1;           // Is this a numbered definition?
 
   // Yes, insert the value into the value table...
@@ -211,8 +227,8 @@ static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
     Num -= CurModule.Types.size();
 
     // Check that the number is within bounds...
-    if (Num <= CurMeth.Types.size())
-      return CurMeth.Types[Num];
+    if (Num <= CurFun.Types.size())
+      return CurFun.Types[Num];
     break;
   }
   case ValID::NameVal: {                // Is it a named definition?
@@ -220,7 +236,7 @@ static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
     SymbolTable *SymTab = 0;
     Value *N = 0;
     if (inFunctionScope()) {
-      SymTab = &CurMeth.CurrentFunction->getSymbolTable();
+      SymTab = &CurFun.CurrentFunction->getSymbolTable();
       N = SymTab->lookup(Type::TypeTy, Name);
     }
 
@@ -247,7 +263,7 @@ static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
 
   std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
-    CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
+    CurFun.LateResolveTypes : CurModule.LateResolveTypes;
   
   std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
   if (I != LateResolver.end()) {
@@ -261,7 +277,7 @@ static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
 
 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
   SymbolTable &SymTab = 
-    inFunctionScope() ? CurMeth.CurrentFunction->getSymbolTable() :
+    inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
                         CurModule.CurrentModule->getSymbolTable();
   return SymTab.lookup(Ty, Name);
 }
@@ -289,12 +305,12 @@ static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
     }
 
     // Make sure that our type is within bounds
-    if (CurMeth.Values.size() <= type) return 0;
+    if (CurFun.Values.size() <= type) return 0;
 
     // Check that the number is within bounds...
-    if (CurMeth.Values[type].size() <= Num) return 0;
+    if (CurFun.Values[type].size() <= Num) return 0;
   
-    return CurMeth.Values[type][Num];
+    return CurFun.Values[type][Num];
   }
 
   case ValID::NameVal: {                // Is it a named definition?
@@ -376,7 +392,7 @@ static Value *getVal(const Type *Ty, const ValID &D) {
 
   assert(d != 0 && "How did we not make something?");
   if (inFunctionScope())
-    InsertValue(d, CurMeth.LateResolveValues);
+    InsertValue(d, CurFun.LateResolveValues);
   else 
     InsertValue(d, CurModule.LateResolveValues);
   return d;
@@ -391,7 +407,7 @@ static Value *getVal(const Type *Ty, const ValID &D) {
 // values not defined yet... for example, a forward branch, or the PHI node for
 // a loop body.
 //
-// This keeps a table (CurMeth.LateResolveValues) of all such forward references
+// This keeps a table (CurFun.LateResolveValues) of all such forward references
 // and back patchs after we are done.
 //
 
@@ -441,14 +457,14 @@ static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
 //
 static void ResolveTypeTo(char *Name, const Type *ToTy) {
   std::vector<PATypeHolder> &Types = inFunctionScope() ? 
-     CurMeth.Types : CurModule.Types;
+     CurFun.Types : CurModule.Types;
 
    ValID D;
    if (Name) D = ValID::create(Name);
    else      D = ValID::create((int)Types.size());
 
    std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
-     CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
+     CurFun.LateResolveTypes : CurModule.LateResolveTypes;
   
    std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
    if (I != LateResolver.end()) {
@@ -491,7 +507,7 @@ static bool setValueName(Value *V, char *NameStr) {
                   "' to a null valued instruction!");
 
   SymbolTable &ST = inFunctionScope() ? 
-    CurMeth.CurrentFunction->getSymbolTable() : 
+    CurFun.CurrentFunction->getSymbolTable() : 
     CurModule.CurrentModule->getSymbolTable();
 
   Value *Existing = ST.lookup(V->getType(), Name);
@@ -536,11 +552,31 @@ static bool setValueName(Value *V, char *NameStr) {
         }
       }
     }
+
     ThrowException("Redefinition of value named '" + Name + "' in the '" +
                   V->getType()->getDescription() + "' type plane!");
   }
 
+  // Set the name
   V->setName(Name, &ST);
+
+  // If we're in function scope
+  if (inFunctionScope()) {
+    // Look up the symbol in the function's local symboltable
+    Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
+
+    // If it already exists
+    if (Existing) {
+      // Bail
+      ThrowException("Redefinition of value named '" + Name + "' in the '" +
+                  V->getType()->getDescription() + "' type plane!");
+
+    // otherwise, since it doesn't exist
+    } else {
+      // Insert it.
+      CurFun.LocalSymtab.insert(V);
+    }
+  }
   return false;
 }
 
@@ -549,42 +585,69 @@ static bool setValueName(Value *V, char *NameStr) {
 // Code for handling upreferences in type names...
 //
 
-// TypeContains - Returns true if Ty contains E in it.
+// TypeContains - Returns true if Ty directly contains E in it.
 //
 static bool TypeContains(const Type *Ty, const Type *E) {
-  return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
+  return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
 }
 
+namespace {
+  struct UpRefRecord {
+    // 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(unsigned NL, OpaqueType *URTy)
+      : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
+  };
+}
 
-static std::vector<std::pair<unsigned, OpaqueType *> > UpRefs;
+// UpRefs - A list of the outstanding upreferences that need to be resolved.
+static std::vector<UpRefRecord> UpRefs;
 
+/// 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 upreferenced type is the type that is passed in:
+/// thus we can complete the cycle.
+///
 static PATypeHolder HandleUpRefs(const Type *ty) {
+  if (!ty->isAbstract()) return ty;
   PATypeHolder Ty(ty);
-  UR_OUT("Type '" << ty->getDescription() << 
+  UR_OUT("Type '" << Ty->getDescription() << 
          "' newly formed.  Resolving upreferences.\n" <<
          UpRefs.size() << " upreferences active!\n");
-  for (unsigned i = 0; i < UpRefs.size(); ) {
+  for (unsigned i = 0; i != UpRefs.size(); ++i) {
     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " 
           << UpRefs[i].second->getDescription() << ") = " 
-          << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
-    if (TypeContains(Ty, UpRefs[i].second)) {
-      unsigned Level = --UpRefs[i].first;   // Decrement level of upreference
-      UR_OUT("  Uplevel Ref Level = " << Level << endl);
+          << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
+    if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
+      // Decrement level of upreference
+      unsigned Level = --UpRefs[i].NestingLevel;
+      UpRefs[i].LastContainedTy = Ty;
+      UR_OUT("  Uplevel Ref Level = " << Level << "\n");
       if (Level == 0) {                     // Upreference should be resolved! 
        UR_OUT("  * Resolving upreference for "
-               << UpRefs[i].second->getDescription() << endl;
-              std::string OldName = UpRefs[i].second->getDescription());
-       UpRefs[i].second->refineAbstractTypeTo(Ty);
-       UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
+               << UpRefs[i].second->getDescription() << "\n";
+              std::string OldName = UpRefs[i].UpRefTy->getDescription());
+       UpRefs[i].UpRefTy->refineAbstractTypeTo(Ty);
        UR_OUT("  * Type '" << OldName << "' refined upreference to: "
-              << (const void*)Ty << ", " << Ty->getDescription() << endl);
-       continue;
+              << (const void*)Ty << ", " << Ty->getDescription() << "\n");
+       UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
+        --i;                                // Do not skip the next element...
       }
     }
-
-    ++i;                                  // Otherwise, no resolve, move on...
   }
-  // FIXME: TODO: this should return the updated type
+
   return Ty;
 }
 
@@ -597,41 +660,118 @@ Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
   llvmAsmin = F;
   CurFilename = Filename;
   llvmAsmlineno = 1;      // Reset the current line number...
+  ObsoleteVarArgs = false;
 
   // Allocate a new module to read
   CurModule.CurrentModule = new Module(Filename);
-  yyparse();       // Parse the file.
+
+  try {
+    yyparse();       // Parse the file.
+  } catch (...) {
+    // Clear the symbol table so it doesn't complain when it
+    // gets destructed
+    CurFun.LocalSymtab.clear();
+    throw;
+  }
+
   Module *Result = ParserResult;
+
+  // Check to see if they called va_start but not va_arg..
+  if (!ObsoleteVarArgs)
+    if (Function *F = Result->getNamedFunction("llvm.va_start"))
+      if (F->asize() == 1) {
+        std::cerr << "WARNING: this file uses obsolete features.  "
+                  << "Assemble and disassemble to update it.\n";
+        ObsoleteVarArgs = true;
+      }
+
+
+  if (ObsoleteVarArgs) {
+    // If the user is making use of obsolete varargs intrinsics, adjust them for
+    // the user.
+    if (Function *F = Result->getNamedFunction("llvm.va_start")) {
+      assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
+
+      const Type *RetTy = F->getFunctionType()->getParamType(0);
+      RetTy = cast<PointerType>(RetTy)->getElementType();
+      Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
+      
+      while (!F->use_empty()) {
+        CallInst *CI = cast<CallInst>(F->use_back());
+        Value *V = new CallInst(NF, "", CI);
+        new StoreInst(V, CI->getOperand(1), CI);
+        CI->getParent()->getInstList().erase(CI);
+      }
+      Result->getFunctionList().erase(F);
+    }
+    
+    if (Function *F = Result->getNamedFunction("llvm.va_end")) {
+      assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
+      const Type *ArgTy = F->getFunctionType()->getParamType(0);
+      ArgTy = cast<PointerType>(ArgTy)->getElementType();
+      Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
+                                                 ArgTy, 0);
+
+      while (!F->use_empty()) {
+        CallInst *CI = cast<CallInst>(F->use_back());
+        Value *V = new LoadInst(CI->getOperand(1), "", CI);
+        new CallInst(NF, V, "", CI);
+        CI->getParent()->getInstList().erase(CI);
+      }
+      Result->getFunctionList().erase(F);
+    }
+
+    if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
+      assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
+      const Type *ArgTy = F->getFunctionType()->getParamType(0);
+      ArgTy = cast<PointerType>(ArgTy)->getElementType();
+      Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
+                                                 ArgTy, 0);
+
+      while (!F->use_empty()) {
+        CallInst *CI = cast<CallInst>(F->use_back());
+        Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
+        new StoreInst(V, CI->getOperand(1), CI);
+        CI->getParent()->getInstList().erase(CI);
+      }
+      Result->getFunctionList().erase(F);
+    }
+  }
+
   llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
   ParserResult = 0;
 
   return Result;
 }
 
+} // End llvm namespace
+
+using namespace llvm;
+
 %}
 
 %union {
-  Module                           *ModuleVal;
-  Function                         *FunctionVal;
-  std::pair<PATypeHolder*, char*>  *ArgVal;
-  BasicBlock                       *BasicBlockVal;
-  TerminatorInst                   *TermInstVal;
-  Instruction                      *InstVal;
-  Constant                         *ConstVal;
-
-  const Type                       *PrimType;
-  PATypeHolder                     *TypeVal;
-  Value                            *ValueVal;
-
-  std::vector<std::pair<PATypeHolder*,char*> > *ArgList;
-  std::vector<Value*>              *ValueList;
-  std::list<PATypeHolder>          *TypeList;
-  std::list<std::pair<Value*,
-                      BasicBlock*> > *PHIList; // Represent the RHS of PHI node
-  std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
-  std::vector<Constant*>           *ConstVector;
-
-  GlobalValue::LinkageTypes         Linkage;
+  llvm::Module                           *ModuleVal;
+  llvm::Function                         *FunctionVal;
+  std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
+  llvm::BasicBlock                       *BasicBlockVal;
+  llvm::TerminatorInst                   *TermInstVal;
+  llvm::Instruction                      *InstVal;
+  llvm::Constant                         *ConstVal;
+
+  const llvm::Type                       *PrimType;
+  llvm::PATypeHolder                     *TypeVal;
+  llvm::Value                            *ValueVal;
+
+  std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
+  std::vector<llvm::Value*>              *ValueList;
+  std::list<llvm::PATypeHolder>          *TypeList;
+  std::list<std::pair<llvm::Value*,
+                      llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
+  std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
+  std::vector<llvm::Constant*>           *ConstVector;
+
+  llvm::GlobalValue::LinkageTypes         Linkage;
   int64_t                           SInt64Val;
   uint64_t                          UInt64Val;
   int                               SIntVal;
@@ -640,13 +780,13 @@ Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
   bool                              BoolVal;
 
   char                             *StrVal;   // This memory is strdup'd!
-  ValID                             ValIDVal; // strdup'd memory maybe!
+  llvm::ValID                             ValIDVal; // strdup'd memory maybe!
 
-  Instruction::BinaryOps            BinaryOpVal;
-  Instruction::TermOps              TermOpVal;
-  Instruction::MemoryOps            MemOpVal;
-  Instruction::OtherOps             OtherOpVal;
-  Module::Endianness                Endianness;
+  llvm::Instruction::BinaryOps            BinaryOpVal;
+  llvm::Instruction::TermOps              TermOpVal;
+  llvm::Instruction::MemoryOps            MemOpVal;
+  llvm::Instruction::OtherOps             OtherOpVal;
+  llvm::Module::Endianness                Endianness;
 }
 
 %type <ModuleVal>     Module FunctionList
@@ -697,7 +837,7 @@ Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
 
 %token IMPLEMENTATION ZEROINITIALIZER TRUE FALSE BEGINTOK ENDTOK
 %token DECLARE GLOBAL CONSTANT VOLATILE
-%token TO EXCEPT DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE APPENDING
+%token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK  APPENDING
 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
 
 // Basic Block Terminating Operators 
@@ -714,7 +854,8 @@ Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
 
 // Other Operators
 %type  <OtherOpVal> ShiftOps
-%token <OtherOpVal> PHI CALL CAST SHL SHR VA_ARG
+%token <OtherOpVal> PHI_TOK CALL CAST SHL SHR VAARG VANEXT
+%token VA_ARG // FIXME: OBSOLETE
 
 %start Module
 %%
@@ -763,6 +904,7 @@ OptAssign : Name '=' {
 
 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
+             WEAK      { $$ = GlobalValue::WeakLinkage; } |
              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
 
@@ -777,7 +919,7 @@ TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
 
 Types     : UpRTypes {
-    if (UpRefs.size())
+    if (!UpRefs.empty())
       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
     $$ = $1;
   };
@@ -800,9 +942,9 @@ UpRTypes : SymbolicValueRef {            // Named types are also simple types...
 // Include derived types in the Types production.
 //
 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
-    if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
+    if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
-    UpRefs.push_back(std::make_pair((unsigned)$2, OT));  // Add to vector...
+    UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
     $$ = new PATypeHolder(OT);
     UR_OUT("New Upreference!\n");
   }
@@ -815,7 +957,7 @@ UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
 
     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
     delete $3;      // Delete the argument list
-    delete $1;      // Delete the old type handle
+    delete $1;      // Delete the return type handle
   }
   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
@@ -985,12 +1127,12 @@ ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
     // which throws things all off.  To get around this, we just tell
     // getValNonImprovising that we are at global scope here.
     //
-    Function *SavedCurFn = CurMeth.CurrentFunction;
-    CurMeth.CurrentFunction = 0;
+    Function *SavedCurFn = CurFun.CurrentFunction;
+    CurFun.CurrentFunction = 0;
 
     Value *V = getValNonImprovising(Ty, $2);
 
-    CurMeth.CurrentFunction = SavedCurFn;
+    CurFun.CurrentFunction = SavedCurFn;
 
     // If this is an initializer for a constant pointer, which is referencing a
     // (currently) undefined variable, create a stub now that shall be replaced
@@ -1006,10 +1148,8 @@ ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
     
       if (I != CurModule.GlobalRefs.end()) {
        V = I->second;             // Placeholder already exists, use it...
+        $2.destroy();
       } else {
-       // TODO: Include line number info by creating a subclass of
-       // TODO: GlobalVariable here that includes the said information!
-       
        // Create a placeholder for the global variable reference...
        GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
                                                 false,
@@ -1060,6 +1200,12 @@ ConstVal : SIntType EINT64VAL {      // integral constants
 
 
 ConstExpr: CAST '(' ConstVal TO Types ')' {
+    if (!$3->getType()->isFirstClassType())
+      ThrowException("cast constant expression from a non-primitive type: '" +
+                     $3->getType()->getDescription() + "'!");
+    if (!$5->get()->isFirstClassType())
+      ThrowException("cast constant expression to a non-primitive type: '" +
+                     $5->get()->getDescription() + "'!");
     $$ = ConstantExpr::getCast($3, $5->get());
     delete $5;
   }
@@ -1091,9 +1237,9 @@ ConstExpr: CAST '(' ConstVal TO Types ')' {
   | ShiftOps '(' ConstVal ',' ConstVal ')' {
     if ($5->getType() != Type::UByteTy)
       ThrowException("Shift count for shift constant must be unsigned byte!");
-    if (!$3->getType()->isIntegral())
-      ThrowException("Shift constant expression requires integral operand!");
-    $$ = ConstantExpr::getShift($1, $3, $5);
+    if (!$3->getType()->isInteger())
+      ThrowException("Shift constant expression requires integer operand!");
+    $$ = ConstantExpr::get($1, $3, $5);
   };
 
 
@@ -1129,7 +1275,7 @@ FunctionList : FunctionList Function {
     $$ = $1;
     assert($2->getParent() == 0 && "Function already in module!");
     $1->getFunctionList().push_back($2);
-    CurMeth.FunctionDone();
+    CurFun.FunctionDone();
   } 
   | FunctionList FunctionProto {
     $$ = $1;
@@ -1165,7 +1311,7 @@ ConstPool : ConstPool OptAssign CONST ConstVal {
       // If this is not a redefinition of a type...
       if (!$2) {
         InsertType($4->get(),
-                   inFunctionScope() ? CurMeth.Types : CurModule.Types);
+                   inFunctionScope() ? CurFun.Types : CurModule.Types);
       }
     }
 
@@ -1278,6 +1424,9 @@ FunctionHeaderH : TypesV Name '(' ArgList ')' {
   UnEscapeLexed($2);
   std::string FunctionName($2);
   
+  if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
+    ThrowException("LLVM functions cannot return aggregate types!");
+
   std::vector<const Type*> ParamTypeList;
   if ($4) {   // If there are arguments...
     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
@@ -1297,7 +1446,7 @@ FunctionHeaderH : TypesV Name '(' ArgList ')' {
   if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
     // Yes it is.  If this is the case, either we need to be a forward decl,
     // or it needs to be.
-    if (!CurMeth.isDeclare && !Fn->isExternal())
+    if (!CurFun.isDeclare && !Fn->isExternal())
       ThrowException("Redefinition of function '" + FunctionName + "'!");
     
     // If we found a preexisting function prototype, remove it from the
@@ -1317,7 +1466,7 @@ FunctionHeaderH : TypesV Name '(' ArgList ')' {
   }
   free($2);  // Free strdup'd memory!
 
-  CurMeth.FunctionStart(Fn);
+  CurFun.FunctionStart(Fn);
 
   // Add all of the arguments we parsed to the function...
   if ($4) {                     // Is null if empty...
@@ -1345,14 +1494,14 @@ FunctionHeaderH : TypesV Name '(' ArgList ')' {
 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
 
 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
-  $$ = CurMeth.CurrentFunction;
+  $$ = CurFun.CurrentFunction;
 
   // Make sure that we keep track of the linkage type even if there was a
   // previous "declare".
   $$->setLinkage($1);
 
   // Resolve circular types before we parse the body of the function.
-  ResolveTypes(CurMeth.LateResolveTypes);
+  ResolveTypes(CurFun.LateResolveTypes);
 };
 
 END : ENDTOK | '}';                    // Allow end of '}' to end a function
@@ -1361,11 +1510,11 @@ Function : BasicBlockList END {
   $$ = $1;
 };
 
-FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
-  $$ = CurMeth.CurrentFunction;
+FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
+  $$ = CurFun.CurrentFunction;
   assert($$->getParent() == 0 && "Function already in module!");
   CurModule.CurrentModule->getFunctionList().push_back($$);
-  CurMeth.FunctionDone();
+  CurFun.FunctionDone();
 };
 
 //===----------------------------------------------------------------------===//
@@ -1450,7 +1599,7 @@ InstructionList : InstructionList Inst {
     $$ = $1;
   }
   | /* empty */ {
-    $$ = new BasicBlock();
+    $$ = CurBB = new BasicBlock();
   };
 
 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
@@ -1483,7 +1632,7 @@ BBTerminatorInst : RET ResolvedVal {              // Return with a result...
     $$ = S;
   }
   | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal 
-    EXCEPT ResolvedVal {
+    UNWIND ResolvedVal {
     const PointerType *PFTy;
     const FunctionType *Ty;
 
@@ -1503,7 +1652,6 @@ BBTerminatorInst : RET ResolvedVal {              // Return with a result...
       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
       PFTy = PointerType::get(Ty);
     }
-    delete $2;
 
     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
 
@@ -1520,8 +1668,8 @@ BBTerminatorInst : RET ResolvedVal {              // Return with a result...
       // Loop through FunctionType's arguments and ensure they are specified
       // correctly!
       //
-      FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
-      FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
+      FunctionType::param_iterator I = Ty->param_begin();
+      FunctionType::param_iterator E = Ty->param_end();
       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
 
       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
@@ -1534,6 +1682,7 @@ BBTerminatorInst : RET ResolvedVal {              // Return with a result...
 
       $$ = new InvokeInst(V, Normal, Except, *$5);
     }
+    delete $2;
     delete $5;
   }
   | UNWIND {
@@ -1629,19 +1778,54 @@ InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
   | ShiftOps ResolvedVal ',' ResolvedVal {
     if ($4->getType() != Type::UByteTy)
       ThrowException("Shift amount must be ubyte!");
+    if (!$2->getType()->isInteger())
+      ThrowException("Shift constant expression requires integer operand!");
     $$ = new ShiftInst($1, $2, $4);
   }
   | CAST ResolvedVal TO Types {
+    if (!$4->get()->isFirstClassType())
+      ThrowException("cast instruction to a non-primitive type: '" +
+                     $4->get()->getDescription() + "'!");
     $$ = new CastInst($2, *$4);
     delete $4;
   }
   | VA_ARG ResolvedVal ',' Types {
-    $$ = new VarArgInst($2, *$4);
+    // FIXME: This is emulation code for an obsolete syntax.  This should be
+    // removed at some point.
+    if (!ObsoleteVarArgs) {
+      std::cerr << "WARNING: this file uses obsolete features.  "
+                << "Assemble and disassemble to update it.\n";
+      ObsoleteVarArgs = true;
+    }
+
+    // First, load the valist...
+    Instruction *CurVAList = new LoadInst($2, "");
+    CurBB->getInstList().push_back(CurVAList);
+
+    // Emit the vaarg instruction.
+    $$ = new VAArgInst(CurVAList, *$4);
+    
+    // Now we must advance the pointer and update it in memory.
+    Instruction *TheVANext = new VANextInst(CurVAList, *$4);
+    CurBB->getInstList().push_back(TheVANext);
+
+    CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
     delete $4;
   }
-  | PHI PHIList {
+  | VAARG ResolvedVal ',' Types {
+    $$ = new VAArgInst($2, *$4);
+    delete $4;
+  }
+  | VANEXT ResolvedVal ',' Types {
+    $$ = new VANextInst($2, *$4);
+    delete $4;
+  }
+  | PHI_TOK PHIList {
     const Type *Ty = $2->front().first->getType();
+    if (!Ty->isFirstClassType())
+      ThrowException("PHI node operands must be of first class type!");
     $$ = new PHINode(Ty);
+    $$->op_reserve($2->size()*2);
     while ($2->begin() != $2->end()) {
       if ($2->front().first->getType() != Ty) 
        ThrowException("All elements of a PHI node must be of the same type!");
@@ -1670,7 +1854,6 @@ InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
       PFTy = PointerType::get(Ty);
     }
-    delete $2;
 
     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
 
@@ -1686,8 +1869,8 @@ InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
       // Loop through FunctionType's arguments and ensure they are specified
       // correctly!
       //
-      FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
-      FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
+      FunctionType::param_iterator I = Ty->param_begin();
+      FunctionType::param_iterator E = Ty->param_end();
       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
 
       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
@@ -1700,6 +1883,7 @@ InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
 
       $$ = new CallInst(V, *$5);
     }
+    delete $2;
     delete $5;
   }
   | MemoryInst {
@@ -1774,6 +1958,7 @@ MemoryInst : MALLOC Types {
     delete $2; delete $4;
   };
 
+
 %%
 int yyerror(const char *ErrorMsg) {
   std::string where