Push LLVMContext through GlobalVariables and IRBuilder.
[oota-llvm.git] / lib / AsmParser / LLParser.cpp
index eefdc6c239d38e70b1425b42074fd565119641a0..49509d5224574d2bbb07542bcf1d574e209eadbc 100644 (file)
@@ -18,6 +18,8 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/InlineAsm.h"
 #include "llvm/Instructions.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/MDNode.h"
 #include "llvm/Module.h"
 #include "llvm/ValueSymbolTable.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
 
-// 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 type
-// can depend on later context.  This may either
-// be a numeric reference or a symbolic (%var) reference.  This is just a
-// discriminated union.
-//
-// Note that I can't implement this class in a straight forward manner with
-// constructors and stuff because it goes in a union.
-//
 namespace llvm {
+  /// 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
+  /// type can depend on later context.  This may either be a numeric reference
+  /// or a symbolic (%var) reference.  This is just a discriminated union.
   struct ValID {
     enum {
       t_LocalID, t_GlobalID,      // ID in UIntVal.
       t_LocalName, t_GlobalName,  // Name in StrVal.
       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
       t_Null, t_Undef, t_Zero,    // No value.
+      t_EmptyArray,               // No value:  []
       t_Constant,                 // Value in ConstantVal.
       t_InlineAsm                 // Value in StrVal/StrVal2/UIntVal.
     } Kind;
@@ -55,17 +53,13 @@ namespace llvm {
   };
 }
 
-/// Parse: module ::= toplevelentity*
-Module *LLParser::Run() {
-  M = new Module(Lex.getFilename());
-  
-  if (ParseTopLevelEntities() ||
-      ValidateEndOfModule()) {
-    delete M;
-    return 0;
-  }
-  
-  return M;
+/// Run: module ::= toplevelentity*
+bool LLParser::Run() {
+  // Prime the lexer.
+  Lex.Lex();
+
+  return ParseTopLevelEntities() ||
+         ValidateEndOfModule();
 }
 
 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
@@ -102,7 +96,6 @@ bool LLParser::ValidateEndOfModule() {
 //===----------------------------------------------------------------------===//
 
 bool LLParser::ParseTopLevelEntities() {
-  Lex.Lex();
   while (1) {
     switch (Lex.getKind()) {
     default:         return TokError("expected top-level entity");
@@ -117,14 +110,18 @@ bool LLParser::ParseTopLevelEntities() {
     case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
+    case lltok::Metadata:   if (ParseStandaloneMetadata()) return true; break;
 
     // The Global variable production with no name can have many different
     // optional leading prefixes, the production is:
     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
     //               OptionalAddrSpace ('constant'|'global') ...
+    case lltok::kw_private:       // OptionalLinkage
     case lltok::kw_internal:      // OptionalLinkage
     case lltok::kw_weak:          // OptionalLinkage
+    case lltok::kw_weak_odr:      // OptionalLinkage
     case lltok::kw_linkonce:      // OptionalLinkage
+    case lltok::kw_linkonce_odr:  // OptionalLinkage
     case lltok::kw_appending:     // OptionalLinkage
     case lltok::kw_dllexport:     // OptionalLinkage
     case lltok::kw_common:        // OptionalLinkage
@@ -134,7 +131,7 @@ bool LLParser::ParseTopLevelEntities() {
       unsigned Linkage, Visibility;
       if (ParseOptionalLinkage(Linkage) ||
           ParseOptionalVisibility(Visibility) ||
-          ParseGlobal("", 0, Linkage, true, Visibility))
+          ParseGlobal("", SMLoc(), Linkage, true, Visibility))
         return true;
       break;
     }
@@ -143,7 +140,7 @@ bool LLParser::ParseTopLevelEntities() {
     case lltok::kw_protected: {   // OptionalVisibility
       unsigned Visibility;
       if (ParseOptionalVisibility(Visibility) ||
-          ParseGlobal("", 0, 0, false, Visibility))
+          ParseGlobal("", SMLoc(), 0, false, Visibility))
         return true;
       break;
     }
@@ -152,7 +149,7 @@ bool LLParser::ParseTopLevelEntities() {
     case lltok::kw_addrspace:     // OptionalAddrSpace
     case lltok::kw_constant:      // GlobalType
     case lltok::kw_global:        // GlobalType
-      if (ParseGlobal("", 0, 0, false, 0)) return true;
+      if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
       break;
     }
   }
@@ -165,17 +162,15 @@ bool LLParser::ParseModuleAsm() {
   assert(Lex.getKind() == lltok::kw_module);
   Lex.Lex();
   
-  if (ParseToken(lltok::kw_asm, "expected 'module asm'")) return true;
-  
-  if (Lex.getKind() != lltok::StringConstant)
-    return TokError("expected 'module asm \"foo\"'");
+  std::string AsmStr; 
+  if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
+      ParseStringConstant(AsmStr)) return true;
   
   const std::string &AsmSoFar = M->getModuleInlineAsm();
   if (AsmSoFar.empty())
-    M->setModuleInlineAsm(Lex.getStrVal());
+    M->setModuleInlineAsm(AsmStr);
   else
-    M->setModuleInlineAsm(AsmSoFar+"\n"+Lex.getStrVal());
-  Lex.Lex();
+    M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
   return false;
 }
 
@@ -184,25 +179,22 @@ bool LLParser::ParseModuleAsm() {
 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
 bool LLParser::ParseTargetDefinition() {
   assert(Lex.getKind() == lltok::kw_target);
+  std::string Str;
   switch (Lex.Lex()) {
   default: return TokError("unknown target property");
   case lltok::kw_triple:
     Lex.Lex();
-    if (ParseToken(lltok::equal, "expected '=' after target triple"))
+    if (ParseToken(lltok::equal, "expected '=' after target triple") ||
+        ParseStringConstant(Str))
       return true;
-    if (Lex.getKind() != lltok::StringConstant)
-      return TokError("expected string after target triple '='");
-    M->setTargetTriple(Lex.getStrVal());
-    Lex.Lex();
+    M->setTargetTriple(Str);
     return false;
   case lltok::kw_datalayout:
     Lex.Lex();
-    if (ParseToken(lltok::equal, "expected '=' after target datalayout"))
+    if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
+        ParseStringConstant(Str))
       return true;
-    if (Lex.getKind() != lltok::StringConstant)
-      return TokError("expected string after target datalayout '='");
-    M->setDataLayout(Lex.getStrVal());
-    Lex.Lex();
+    M->setDataLayout(Str);
     return false;
   }
 }
@@ -212,32 +204,24 @@ bool LLParser::ParseTargetDefinition() {
 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
 bool LLParser::ParseDepLibs() {
   assert(Lex.getKind() == lltok::kw_deplibs);
-  if (Lex.Lex() != lltok::equal)
-    return TokError("expected '=' after deplibs");
-
-  if (Lex.Lex() != lltok::lsquare)
-    return TokError("expected '=' after deplibs");
+  Lex.Lex();
+  if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
+      ParseToken(lltok::lsquare, "expected '=' after deplibs"))
+    return true;
 
-  if (Lex.Lex() == lltok::rsquare) {
-    Lex.Lex();
+  if (EatIfPresent(lltok::rsquare))
     return false;
-  }
   
-  if (Lex.getKind() != lltok::StringConstant)
-    return TokError("expected string in deplib list");
-
-  M->addLibrary(Lex.getStrVal());
+  std::string Str;
+  if (ParseStringConstant(Str)) return true;
+  M->addLibrary(Str);
 
-  while (Lex.Lex() == lltok::comma) {
-    if (Lex.Lex() != lltok::StringConstant)
-      return TokError("expected string in deplibs list");
-    M->addLibrary(Lex.getStrVal());
+  while (EatIfPresent(lltok::comma)) {
+    if (ParseStringConstant(Str)) return true;
+    M->addLibrary(Str);
   }
 
-  if (Lex.getKind() != lltok::rsquare)
-    return TokError("expected ']' at end of list");
-  Lex.Lex();
-  return false;
+  return ParseToken(lltok::rsquare, "expected ']' at end of list");
 }
 
 /// toplevelentity
@@ -252,14 +236,13 @@ bool LLParser::ParseUnnamedType() {
  
   unsigned TypeID = NumberedTypes.size();
   
-  // We don't allow assigning names to void type
-  if (Ty == Type::VoidTy)
-    return Error(TypeLoc, "can't assign name to the void type");
-  
   // 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);
@@ -275,20 +258,15 @@ bool LLParser::ParseUnnamedType() {
 bool LLParser::ParseNamedType() {
   std::string Name = Lex.getStrVal();
   LocTy NameLoc = Lex.getLoc();
-  
-  if (Lex.Lex() != lltok::equal)
-    return TokError("expected '=' after name");
-  if (Lex.Lex() != lltok::kw_type)
-    return TokError("expected 'type' after name");
-  Lex.Lex(); // consume 'type'.
+  Lex.Lex();  // eat LocalVar.
   
   PATypeHolder Ty(Type::VoidTy);
-  if (ParseType(Ty)) return true;
   
-  // We don't allow assigning names to void type
-  if (Ty == Type::VoidTy)
-    return Error(NameLoc, "can't assign name '" + Name + "' to the void type");
-
+  if (ParseToken(lltok::equal, "expected '=' after name") ||
+      ParseToken(lltok::kw_type, "expected 'type' after name") ||
+      ParseType(Ty))
+    return true;
+  
   // Set the type name, checking for conflicts as we do so.
   bool AlreadyExists = M->addTypeName(Name, Ty);
   if (!AlreadyExists) return false;
@@ -298,6 +276,9 @@ bool LLParser::ParseNamedType() {
   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);
@@ -335,18 +316,22 @@ bool LLParser::ParseDefine() {
   Lex.Lex();
   
   Function *F;
-  if (ParseFunctionHeader(F, true)) return true;
-  
-  return ParseFunctionBody(*F);
+  return ParseFunctionHeader(F, true) ||
+         ParseFunctionBody(*F);
 }
 
+/// ParseGlobalType
+///   ::= 'constant'
+///   ::= 'global'
 bool LLParser::ParseGlobalType(bool &IsConstant) {
   if (Lex.getKind() == lltok::kw_constant)
     IsConstant = true;
   else if (Lex.getKind() == lltok::kw_global)
     IsConstant = false;
-  else
+  else {
+    IsConstant = false;
     return TokError("expected 'global' or 'constant'");
+  }
   Lex.Lex();
   return false;
 }
@@ -372,10 +357,40 @@ bool LLParser::ParseNamedGlobal() {
   return ParseAlias(Name, NameLoc, Visibility);
 }
 
+/// ParseStandaloneMetadata:
+///   !42 = !{...} 
+bool LLParser::ParseStandaloneMetadata() {
+  assert(Lex.getKind() == lltok::Metadata);
+  Lex.Lex();
+  unsigned MetadataID = 0;
+  if (ParseUInt32(MetadataID))
+    return true;
+  if (MetadataCache.find(MetadataID) != MetadataCache.end())
+    return TokError("Metadata id is already used");
+  if (ParseToken(lltok::equal, "expected '=' here"))
+    return true;
+
+  LocTy TyLoc;
+  bool IsConstant;    
+  PATypeHolder Ty(Type::VoidTy);
+  if (ParseGlobalType(IsConstant) ||
+      ParseType(Ty, TyLoc))
+    return true;
+  
+  Constant *Init = 0;
+  if (ParseGlobalValue(Ty, Init))
+      return true;
+
+  MetadataCache[MetadataID] = Init;
+  return false;
+}
+
 /// ParseAlias:
 ///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
 /// Aliasee
-///   ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
+///   ::= TypeAndValue
+///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
+///   ::= 'getelementptr' '(' ... ')'
 ///
 /// Everything through visibility has already been parsed.
 ///
@@ -389,13 +404,16 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
     return true;
 
   if (Linkage != GlobalValue::ExternalLinkage &&
-      Linkage != GlobalValue::WeakLinkage &&
-      Linkage != GlobalValue::InternalLinkage)
+      Linkage != GlobalValue::WeakAnyLinkage &&
+      Linkage != GlobalValue::WeakODRLinkage &&
+      Linkage != GlobalValue::InternalLinkage &&
+      Linkage != GlobalValue::PrivateLinkage)
     return Error(LinkageLoc, "invalid linkage type for alias");
   
   Constant *Aliasee;
   LocTy AliaseeLoc = Lex.getLoc();
-  if (Lex.getKind() != lltok::kw_bitcast) {
+  if (Lex.getKind() != lltok::kw_bitcast &&
+      Lex.getKind() != lltok::kw_getelementptr) {
     if (ParseGlobalTypeAndValue(Aliasee)) return true;
   } else {
     // The bitcast dest type is not present, it is implied by the dest type.
@@ -479,13 +497,14 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
   }
 
   if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
-    return Error(TyLoc, "invald type for global variable");
+    return Error(TyLoc, "invalid type for global variable");
   
   GlobalVariable *GV = 0;
 
   // See if the global was forward referenced, if so, use the global.
-  if (!Name.empty() && (GV = M->getGlobalVariable(Name, true))) {
-    if (!ForwardRefVals.erase(Name))
+  if (!Name.empty()) {
+    if ((GV = M->getGlobalVariable(Name, true)) &&
+        !ForwardRefVals.erase(Name))
       return Error(NameLoc, "redefinition of global '@" + Name + "'");
   } else {
     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
@@ -497,7 +516,8 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
   }
 
   if (GV == 0) {
-    GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
+    GV = new GlobalVariable(Context, Ty, false,
+                            GlobalValue::ExternalLinkage, 0, Name,
                             M, false, AddrSpace);
   } else {
     if (GV->getType()->getElementType() != Ty)
@@ -579,11 +599,18 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
   
   // Otherwise, create a new forward reference for this value and remember it.
   GlobalValue *FwdVal;
-  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
+  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
+    // Function types can return opaque but functions can't.
+    if (isa<OpaqueType>(FT->getReturnType())) {
+      Error(Loc, "function may not return opaque type");
+      return 0;
+    }
+    
     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
-  else
-    FwdVal = new GlobalVariable(PTy->getElementType(), false,
+  } else {
+    FwdVal = new GlobalVariable(Context, PTy->getElementType(), false,
                                 GlobalValue::ExternalWeakLinkage, 0, Name, M);
+  }
   
   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
   return FwdVal;
@@ -617,11 +644,17 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
   
   // Otherwise, create a new forward reference for this value and remember it.
   GlobalValue *FwdVal;
-  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
+  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
+    // Function types can return opaque but functions can't.
+    if (isa<OpaqueType>(FT->getReturnType())) {
+      Error(Loc, "function may not return opaque type");
+      return 0;
+    }
     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
-  else
-    FwdVal = new GlobalVariable(PTy->getElementType(), false,
+  } else {
+    FwdVal = new GlobalVariable(Context, PTy->getElementType(), false,
                                 GlobalValue::ExternalWeakLinkage, 0, "", M);
+  }
   
   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
   return FwdVal;
@@ -641,7 +674,19 @@ bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
   return false;
 }
 
-bool LLParser::ParseUnsigned(unsigned &Val) {
+/// ParseStringConstant
+///   ::= StringConstant
+bool LLParser::ParseStringConstant(std::string &Result) {
+  if (Lex.getKind() != lltok::StringConstant)
+    return TokError("expected string constant");
+  Result = Lex.getStrVal();
+  Lex.Lex();
+  return false;
+}
+
+/// ParseUInt32
+///   ::= uint32
+bool LLParser::ParseUInt32(unsigned &Val) {
   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
     return TokError("expected integer");
   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
@@ -658,19 +703,17 @@ bool LLParser::ParseUnsigned(unsigned &Val) {
 ///   := 'addrspace' '(' uint32 ')'
 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
   AddrSpace = 0;
-  bool HasAddrSpace;
-  ParseOptionalToken(lltok::kw_addrspace, HasAddrSpace);
-  if (!HasAddrSpace)
+  if (!EatIfPresent(lltok::kw_addrspace))
     return false;
-  
   return ParseToken(lltok::lparen, "expected '(' in address space") ||
-         ParseUnsigned(AddrSpace) ||
+         ParseUInt32(AddrSpace) ||
          ParseToken(lltok::rparen, "expected ')' in address space");
 }  
 
 /// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
 /// 2: function attr.
+/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
   Attrs = Attribute::None;
   LocTy AttrLoc = Lex.getLoc();
@@ -679,9 +722,12 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
     switch (Lex.getKind()) {
     case lltok::kw_sext:
     case lltok::kw_zext:
-      // Treat these as signext/zeroext unless they are function attrs.
+      // Treat these as signext/zeroext if they occur in the argument list after
+      // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
+      // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
+      // expr.
       // FIXME: REMOVE THIS IN LLVM 3.0
-      if (AttrKind != 2) {
+      if (AttrKind == 3) {
         if (Lex.getKind() == lltok::kw_sext)
           Attrs |= Attribute::SExt;
         else
@@ -693,29 +739,30 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
       if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
         return Error(AttrLoc, "invalid use of function-only attribute");
         
-      if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
+      if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
         return Error(AttrLoc, "invalid use of parameter-only attribute");
         
       return false;
-    case lltok::kw_zeroext:      Attrs |= Attribute::ZExt; break;
-    case lltok::kw_signext:      Attrs |= Attribute::SExt; break;
-    case lltok::kw_inreg:        Attrs |= Attribute::InReg; break;
-    case lltok::kw_sret:         Attrs |= Attribute::StructRet; break;
-    case lltok::kw_noalias:      Attrs |= Attribute::NoAlias; break;
-    case lltok::kw_nocapture:    Attrs |= Attribute::NoCapture; break;
-    case lltok::kw_byval:        Attrs |= Attribute::ByVal; break;
-    case lltok::kw_nest:         Attrs |= Attribute::Nest; break;
-
-    case lltok::kw_noreturn:     Attrs |= Attribute::NoReturn; break;
-    case lltok::kw_nounwind:     Attrs |= Attribute::NoUnwind; break;
-    case lltok::kw_noinline:     Attrs |= Attribute::NoInline; break;
-    case lltok::kw_readnone:     Attrs |= Attribute::ReadNone; break;
-    case lltok::kw_readonly:     Attrs |= Attribute::ReadOnly; break;
-    case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
-    case lltok::kw_optsize:      Attrs |= Attribute::OptimizeForSize; break;
-    case lltok::kw_ssp:          Attrs |= Attribute::StackProtect; break;
-    case lltok::kw_sspreq:       Attrs |= Attribute::StackProtectReq; break;
-
+    case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
+    case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
+    case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
+    case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
+    case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
+    case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
+    case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
+    case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
+
+    case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
+    case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
+    case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
+    case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
+    case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
+    case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
+    case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
+    case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
+    case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
+    case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
+    case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
         
     case lltok::kw_align: {
       unsigned Alignment;
@@ -731,9 +778,12 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
 
 /// ParseOptionalLinkage
 ///   ::= /*empty*/
+///   ::= 'private'
 ///   ::= 'internal'
 ///   ::= 'weak'
+///   ::= 'weak_odr'
 ///   ::= 'linkonce'
+///   ::= 'linkonce_odr'
 ///   ::= 'appending'
 ///   ::= 'dllexport'
 ///   ::= 'common'
@@ -743,16 +793,22 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
   HasLinkage = false;
   switch (Lex.getKind()) {
-  default:                    Res = GlobalValue::ExternalLinkage; return false;
-  case lltok::kw_internal:    Res = GlobalValue::InternalLinkage; break;
-  case lltok::kw_weak:        Res = GlobalValue::WeakLinkage; break;
-  case lltok::kw_linkonce:    Res = GlobalValue::LinkOnceLinkage; break;
-  case lltok::kw_appending:   Res = GlobalValue::AppendingLinkage; break;
-  case lltok::kw_dllexport:   Res = GlobalValue::DLLExportLinkage; break;
-  case lltok::kw_common:      Res = GlobalValue::CommonLinkage; break;
-  case lltok::kw_dllimport:   Res = GlobalValue::DLLImportLinkage; break;
-  case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
-  case lltok::kw_external:    Res = GlobalValue::ExternalLinkage; break;
+  default:                     Res = GlobalValue::ExternalLinkage; return false;
+  case lltok::kw_private:      Res = GlobalValue::PrivateLinkage; break;
+  case lltok::kw_internal:     Res = GlobalValue::InternalLinkage; break;
+  case lltok::kw_weak:         Res = GlobalValue::WeakAnyLinkage; break;
+  case lltok::kw_weak_odr:     Res = GlobalValue::WeakODRLinkage; break;
+  case lltok::kw_linkonce:     Res = GlobalValue::LinkOnceAnyLinkage; break;
+  case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
+  case lltok::kw_available_externally:
+    Res = GlobalValue::AvailableExternallyLinkage;
+    break;
+  case lltok::kw_appending:    Res = GlobalValue::AppendingLinkage; break;
+  case lltok::kw_dllexport:    Res = GlobalValue::DLLExportLinkage; break;
+  case lltok::kw_common:       Res = GlobalValue::CommonLinkage; break;
+  case lltok::kw_dllimport:    Res = GlobalValue::DLLImportLinkage; break;
+  case lltok::kw_extern_weak:  Res = GlobalValue::ExternalWeakLinkage; break;
+  case lltok::kw_external:     Res = GlobalValue::ExternalLinkage; break;
   }
   Lex.Lex();
   HasLinkage = true;
@@ -783,8 +839,11 @@ bool LLParser::ParseOptionalVisibility(unsigned &Res) {
 ///   ::= 'coldcc'
 ///   ::= 'x86_stdcallcc'
 ///   ::= 'x86_fastcallcc'
+///   ::= 'arm_apcscc'
+///   ::= 'arm_aapcscc'
+///   ::= 'arm_aapcs_vfpcc'
 ///   ::= 'cc' UINT
-/// 
+///
 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
   switch (Lex.getKind()) {
   default:                       CC = CallingConv::C; return false;
@@ -793,7 +852,10 @@ bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
-  case lltok::kw_cc:             Lex.Lex(); return ParseUnsigned(CC);
+  case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
+  case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
+  case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
+  case lltok::kw_cc:             Lex.Lex(); return ParseUInt32(CC);
   }
   Lex.Lex();
   return false;
@@ -804,10 +866,13 @@ bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
 ///   ::= 'align' 4
 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
   Alignment = 0;
-  bool HasAlignment;
-  if (ParseOptionalToken(lltok::kw_align, HasAlignment)) return true;
-  
-  return HasAlignment && ParseUnsigned(Alignment);
+  if (!EatIfPresent(lltok::kw_align))
+    return false;
+  LocTy AlignLoc = Lex.getLoc();
+  if (ParseUInt32(Alignment)) return true;
+  if (!isPowerOf2_32(Alignment))
+    return Error(AlignLoc, "alignment is not a power of two");
+  return false;
 }
 
 /// ParseOptionalCommaAlignment
@@ -815,13 +880,10 @@ bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
 ///   ::= ',' 'align' 4
 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
   Alignment = 0;
-  bool HasComma;
-  ParseOptionalToken(lltok::comma, HasComma);
-  if (!HasComma)
+  if (!EatIfPresent(lltok::comma))
     return false;
-  
   return ParseToken(lltok::kw_align, "expected 'align'") ||
-         ParseUnsigned(Alignment);
+         ParseUInt32(Alignment);
 }
 
 /// ParseIndexList
@@ -830,10 +892,9 @@ bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
   if (Lex.getKind() != lltok::comma)
     return TokError("expected ',' as start of index list");
   
-  while (Lex.getKind() == lltok::comma) {
-    Lex.Lex();
+  while (EatIfPresent(lltok::comma)) {
     unsigned Idx;
-    if (ParseUnsigned(Idx)) return true;
+    if (ParseUInt32(Idx)) return true;
     Indices.push_back(Idx);
   }
   
@@ -845,13 +906,16 @@ bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
 //===----------------------------------------------------------------------===//
 
 /// ParseType - Parse and resolve a full type.
-bool LLParser::ParseType(PATypeHolder &Result) {
+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");
-  //  GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
+  
+  if (!AllowVoid && Result.get() == Type::VoidTy)
+    return Error(TypeLoc, "void type only allowed for function results");
   
   return false;
 }
@@ -935,7 +999,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) {
     break;
   case lltok::kw_opaque:
     // TypeRec ::= 'opaque'
-    Result = OpaqueType::get();
+    Result = Context.getOpaqueType();
     Lex.Lex();
     break;
   case lltok::lbrace:
@@ -951,12 +1015,11 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) {
     break;
   case lltok::less: // Either vector or packed struct.
     // TypeRec ::= '<' ... '>'
-    if (Lex.Lex() == lltok::lbrace) {
-      if (ParseStructType(Result, true))
+    Lex.Lex();
+    if (Lex.getKind() == lltok::lbrace) {
+      if (ParseStructType(Result, true) ||
+          ParseToken(lltok::greater, "expected '>' at end of packed struct"))
         return true;
-      if (Lex.getKind() != lltok::greater)
-        return TokError("expected '>' at end of packed struct");
-      Lex.Lex();
     } else if (ParseArrayVectorType(Result, true))
       return true;
     break;
@@ -966,7 +1029,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) {
     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
       Result = T;
     } else {
-      Result = OpaqueType::get();
+      Result = Context.getOpaqueType();
       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
                                             std::make_pair(Result,
                                                            Lex.getLoc())));
@@ -985,7 +1048,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) {
       if (I != ForwardRefTypeIDs.end())
         Result = I->second.first;
       else {
-        Result = OpaqueType::get();
+        Result = Context.getOpaqueType();
         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
                                                 std::make_pair(Result,
                                                                Lex.getLoc())));
@@ -995,10 +1058,10 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) {
     break;
   case lltok::backslash: {
     // TypeRec ::= '\' 4
-    unsigned Val;
     Lex.Lex();
-    if (ParseUnsigned(Val)) return true;
-    OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder.
+    unsigned Val;
+    if (ParseUInt32(Val)) return true;
+    OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
     Result = OT;
     break;
@@ -1015,7 +1078,11 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) {
     case lltok::star:
       if (Result.get() == Type::LabelTy)
         return TokError("basic block pointers are invalid");
-      Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
+      if (Result.get() == Type::VoidTy)
+        return TokError("pointers to void are invalid; use i8* instead");
+      if (!PointerType::isValidElementType(Result.get()))
+        return TokError("pointer to this type is invalid");
+      Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
       Lex.Lex();
       break;
 
@@ -1023,12 +1090,16 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) {
     case lltok::kw_addrspace: {
       if (Result.get() == Type::LabelTy)
         return TokError("basic block pointers are invalid");
+      if (Result.get() == Type::VoidTy)
+        return TokError("pointers to void are invalid; use i8* instead");
+      if (!PointerType::isValidElementType(Result.get()))
+        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 = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
       break;
     }
         
@@ -1067,7 +1138,7 @@ bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
         ParseValue(ArgTy, V, PFS) ||
         // FIXME: Should not allow attributes after the argument, remove this in
         // LLVM 3.0.
-        ParseOptionalAttrs(ArgAttrs2, 0))
+        ParseOptionalAttrs(ArgAttrs2, 3))
       return true;
     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
   }
@@ -1078,15 +1149,17 @@ bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
 
 
 
-/// ParseArgumentList
+/// ParseArgumentList - Parse the argument list for a function type or function
+/// prototype.  If 'inType' is true then we are parsing a FunctionType.
 ///   ::= '(' ArgTypeListI ')'
 /// ArgTypeListI
 ///   ::= /*empty*/
 ///   ::= '...'
 ///   ::= ArgTypeList ',' '...'
 ///   ::= ArgType (',' ArgType)*
+///
 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
-                                 bool &isVarArg) {
+                                 bool &isVarArg, bool inType) {
   isVarArg = false;
   assert(Lex.getKind() == lltok::lparen);
   Lex.Lex(); // eat the (.
@@ -1099,42 +1172,44 @@ bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
   } else {
     LocTy TypeLoc = Lex.getLoc();
     PATypeHolder ArgTy(Type::VoidTy);
+    unsigned Attrs;
+    std::string Name;
     
-    if (ParseTypeRec(ArgTy)) return true;
+    // 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)) ||
+        ParseOptionalAttrs(Attrs, 0)) return true;
     
-    if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
-      return Error(TypeLoc, "invalid type for function argument");
+    if (ArgTy == Type::VoidTy)
+      return Error(TypeLoc, "argument can not have void type");
     
-    unsigned Attrs;
-    if (ParseOptionalAttrs(Attrs, 0)) return true;
-    
-    std::string Name;
     if (Lex.getKind() == lltok::LocalVar ||
         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
       Name = Lex.getStrVal();
       Lex.Lex();
     }
+
+    if (!FunctionType::isValidArgumentType(ArgTy))
+      return Error(TypeLoc, "invalid type for function argument");
     
     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
     
-    while (Lex.getKind() == lltok::comma) {
-      Lex.Lex(); // eat the comma.
-      
+    while (EatIfPresent(lltok::comma)) {
       // Handle ... at end of arg list.
-      if (Lex.getKind() == lltok::dotdotdot) {
+      if (EatIfPresent(lltok::dotdotdot)) {
         isVarArg = true;
-        Lex.Lex();
         break;
       }
       
       // Otherwise must be an argument type.
       TypeLoc = Lex.getLoc();
-      if (ParseTypeRec(ArgTy)) return true;
-      if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
-        return Error(TypeLoc, "invalid type for function argument");
-      
-      if (ParseOptionalAttrs(Attrs, 0)) return true;
-      
+      if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
+          ParseOptionalAttrs(Attrs, 0)) return true;
+
+      if (ArgTy == Type::VoidTy)
+        return Error(TypeLoc, "argument can not have void type");
+
       if (Lex.getKind() == lltok::LocalVar ||
           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
         Name = Lex.getStrVal();
@@ -1142,15 +1217,15 @@ bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
       } else {
         Name = "";
       }
+
+      if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
+        return Error(TypeLoc, "invalid type for function argument");
       
       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
     }
   }
   
-  if (Lex.getKind() != lltok::rparen)
-    return TokError("expected ')' at end of function argument list");
-  Lex.Lex();
-  return false;
+  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
 }
   
 /// ParseFunctionType
@@ -1158,10 +1233,13 @@ bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
   assert(Lex.getKind() == lltok::lparen);
 
+  if (!FunctionType::isValidReturnType(Result))
+    return TokError("invalid function return type");
+  
   std::vector<ArgInfo> ArgList;
   bool isVarArg;
   unsigned Attrs;
-  if (ParseArgumentList(ArgList, isVarArg) ||
+  if (ParseArgumentList(ArgList, isVarArg, true) ||
       // FIXME: Allow, but ignore attributes on function types!
       // FIXME: Remove in LLVM 3.0
       ParseOptionalAttrs(Attrs, 2))
@@ -1182,7 +1260,8 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) {
   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
     ArgListTy.push_back(ArgList[i].Type);
     
-  Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
+  Result = HandleUpRefs(Context.getFunctionType(Result.get(),
+                                                ArgListTy, isVarArg));
   return false;
 }
 
@@ -1196,31 +1275,40 @@ bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
   assert(Lex.getKind() == lltok::lbrace);
   Lex.Lex(); // Consume the '{'
   
-  if (Lex.getKind() == lltok::rbrace) {
-    Result = StructType::get(std::vector<const Type*>(), Packed);
-    Lex.Lex();
+  if (EatIfPresent(lltok::rbrace)) {
+    Result = Context.getStructType(Packed);
     return false;
   }
 
   std::vector<PATypeHolder> ParamsList;
+  LocTy EltTyLoc = Lex.getLoc();
   if (ParseTypeRec(Result)) return true;
   ParamsList.push_back(Result);
   
-  while (Lex.getKind() == lltok::comma) {
-    Lex.Lex(); // eat the comma.
-    
+  if (Result == Type::VoidTy)
+    return Error(EltTyLoc, "struct element can not have void type");
+  if (!StructType::isValidElementType(Result))
+    return Error(EltTyLoc, "invalid element type for struct");
+  
+  while (EatIfPresent(lltok::comma)) {
+    EltTyLoc = Lex.getLoc();
     if (ParseTypeRec(Result)) return true;
+    
+    if (Result == Type::VoidTy)
+      return Error(EltTyLoc, "struct element can not have void type");
+    if (!StructType::isValidElementType(Result))
+      return Error(EltTyLoc, "invalid element type for struct");
+    
     ParamsList.push_back(Result);
   }
   
-  if (Lex.getKind() != lltok::rbrace)
-    return TokError("expected '}' at end of struct");
-  Lex.Lex(); // Consume the '}'
+  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(ParamsListTy, Packed));
+  Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
   return false;
 }
 
@@ -1236,28 +1324,34 @@ bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
   
   LocTy SizeLoc = Lex.getLoc();
   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
-  if (Lex.Lex() != lltok::kw_x)
-    return TokError("expected 'x' after element count");
-  Lex.Lex();  // eat the 'x'.
+  Lex.Lex();
+      
+  if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
+      return true;
 
   LocTy TypeLoc = Lex.getLoc();
   PATypeHolder EltTy(Type::VoidTy);
   if (ParseTypeRec(EltTy)) return true;
   
-  if (Lex.getKind() != (isVector ? lltok::greater : lltok::rsquare))
-    return TokError("expected end of sequential type");
-  Lex.Lex();
+  if (EltTy == Type::VoidTy)
+    return Error(TypeLoc, "array and vector element type cannot be void");
+
+  if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
+                 "expected end of sequential type"))
+    return true;
   
   if (isVector) {
+    if (Size == 0)
+      return Error(SizeLoc, "zero element vector is illegal");
     if ((unsigned)Size != Size)
       return Error(SizeLoc, "size too large for vector");
-    if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
+    if (!VectorType::isValidElementType(EltTy))
       return Error(TypeLoc, "vector element type must be fp or integer");
-    Result = VectorType::get(EltTy, unsigned(Size));
+    Result = Context.getVectorType(EltTy, unsigned(Size));
   } else {
-    if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
+    if (!ArrayType::isValidElementType(EltTy))
       return Error(TypeLoc, "invalid array element type");
-    Result = HandleUpRefs(ArrayType::get(EltTy, Size));
+    Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
   }
   return false;
 }
@@ -1281,8 +1375,8 @@ LLParser::PerFunctionState::~PerFunctionState() {
   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
     if (!isa<BasicBlock>(I->second.first)) {
-      I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
-                                                          ->getType()));
+      I->second.first->replaceAllUsesWith(
+                           P.getContext().getUndef(I->second.first->getType()));
       delete I->second.first;
       I->second.first = 0;
     }
@@ -1290,8 +1384,8 @@ LLParser::PerFunctionState::~PerFunctionState() {
   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
     if (!isa<BasicBlock>(I->second.first)) {
-      I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
-                                                          ->getType()));
+      I->second.first->replaceAllUsesWith(
+                           P.getContext().getUndef(I->second.first->getType()));
       delete I->second.first;
       I->second.first = 0;
     }
@@ -1521,6 +1615,38 @@ bool LLParser::ParseValID(ValID &ID) {
     ID.StrVal = Lex.getStrVal();
     ID.Kind = ValID::t_LocalName;
     break;
+  case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
+    ID.Kind = ValID::t_Constant;
+    Lex.Lex();
+    if (Lex.getKind() == lltok::lbrace) {
+      SmallVector<Value*, 16> Elts;
+      if (ParseMDNodeVector(Elts) ||
+          ParseToken(lltok::rbrace, "expected end of metadata node"))
+        return true;
+
+      ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
+      return false;
+    }
+
+    // Standalone metadata reference
+    // !{ ..., !42, ... }
+    unsigned MID = 0;
+    if (!ParseUInt32(MID)) {
+      std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
+      if (I == MetadataCache.end())
+       return TokError("Unknown metadata reference");
+      ID.ConstantVal = I->second;
+      return false;
+    }
+    
+    // MDString:
+    //   ::= '!' STRINGCONSTANT
+    std::string Str;
+    if (ParseStringConstant(Str)) return true;
+
+    ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
+    return false;
+  }
   case lltok::APSInt:
     ID.APSIntVal = Lex.getAPSIntVal(); 
     ID.Kind = ValID::t_APSInt;
@@ -1530,11 +1656,11 @@ bool LLParser::ParseValID(ValID &ID) {
     ID.Kind = ValID::t_APFloat;
     break;
   case lltok::kw_true:
-    ID.ConstantVal = ConstantInt::getTrue();
+    ID.ConstantVal = Context.getConstantIntTrue();
     ID.Kind = ValID::t_Constant;
     break;
   case lltok::kw_false:
-    ID.ConstantVal = ConstantInt::getFalse();
+    ID.ConstantVal = Context.getConstantIntFalse();
     ID.Kind = ValID::t_Constant;
     break;
   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
@@ -1549,7 +1675,7 @@ bool LLParser::ParseValID(ValID &ID) {
         ParseToken(lltok::rbrace, "expected end of struct constant"))
       return true;
     
-    ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
+    ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
     ID.Kind = ValID::t_Constant;
     return false;
   }
@@ -1557,8 +1683,7 @@ bool LLParser::ParseValID(ValID &ID) {
     // ValID ::= '<' ConstVector '>'         --> Vector.
     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
     Lex.Lex();
-    bool isPackedStruct;
-    ParseOptionalToken(lltok::lbrace, isPackedStruct);
+    bool isPackedStruct = EatIfPresent(lltok::lbrace);
     
     SmallVector<Constant*, 16> Elts;
     LocTy FirstEltLoc = Lex.getLoc();
@@ -1569,7 +1694,8 @@ bool LLParser::ParseValID(ValID &ID) {
       return true;
     
     if (isPackedStruct) {
-      ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
+      ID.ConstantVal =
+        Context.getConstantStruct(Elts.data(), Elts.size(), true);
       ID.Kind = ValID::t_Constant;
       return false;
     }
@@ -1589,7 +1715,7 @@ bool LLParser::ParseValID(ValID &ID) {
                      "vector element #" + utostr(i) +
                     " is not of type '" + Elts[0]->getType()->getDescription());
     
-    ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
+    ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
     ID.Kind = ValID::t_Constant;
     return false;
   }
@@ -1605,7 +1731,7 @@ bool LLParser::ParseValID(ValID &ID) {
     if (Elts.empty()) {
       // Use undef instead of an array because it's inconvenient to determine
       // the element type at this point, there being no elements to examine.
-      ID.Kind = ValID::t_Undef;
+      ID.Kind = ValID::t_EmptyArray;
       return false;
     }
     
@@ -1613,23 +1739,23 @@ bool LLParser::ParseValID(ValID &ID) {
       return Error(FirstEltLoc, "invalid array element type: " + 
                    Elts[0]->getType()->getDescription());
           
-    ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
+    ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
     
     // Verify all elements are correct type!
-    for (unsigned i = i, e = Elts.size() ; i != e; ++i) {
+    for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
       if (Elts[i]->getType() != Elts[0]->getType())
         return Error(FirstEltLoc,
                      "array element #" + utostr(i) +
                      " is not of type '" +Elts[0]->getType()->getDescription());
     }
-          
-    ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
+    
+    ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
     ID.Kind = ValID::t_Constant;
     return false;
   }
   case lltok::kw_c:  // c "foo"
     Lex.Lex();
-    ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
+    ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
     if (ParseToken(lltok::StringConstant, "expected string")) return true;
     ID.Kind = ValID::t_Constant;
     return false;
@@ -1639,11 +1765,8 @@ bool LLParser::ParseValID(ValID &ID) {
     bool HasSideEffect;
     Lex.Lex();
     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
-        ParseToken(lltok::StringConstant, "expected asm string"))
-      return true;
-    ID.StrVal = Lex.getStrVal();
-
-    if (ParseToken(lltok::comma, "expected comma in inline asm expression") ||
+        ParseStringConstant(ID.StrVal) ||
+        ParseToken(lltok::comma, "expected comma in inline asm expression") ||
         ParseToken(lltok::StringConstant, "expected constraint string"))
       return true;
     ID.StrVal2 = Lex.getStrVal();
@@ -1670,7 +1793,7 @@ bool LLParser::ParseValID(ValID &ID) {
     Lex.Lex();
     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
         ParseGlobalTypeAndValue(SrcVal) ||
-        ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
+        ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
         ParseType(DestTy) ||
         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
       return true;
@@ -1678,8 +1801,8 @@ bool LLParser::ParseValID(ValID &ID) {
       return Error(ID.Loc, "invalid cast opcode for cast from '" +
                    SrcVal->getType()->getDescription() + "' to '" +
                    DestTy->getDescription() + "'");
-    ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
-                                           DestTy);
+    ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc, 
+                                                 SrcVal, DestTy);
     ID.Kind = ValID::t_Constant;
     return false;
   }
@@ -1697,8 +1820,8 @@ bool LLParser::ParseValID(ValID &ID) {
     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
                                           Indices.end()))
       return Error(ID.Loc, "invalid indices for extractvalue");
-    ID.ConstantVal = ConstantExpr::getExtractValue(Val,
-                                                   &Indices[0], Indices.size());
+    ID.ConstantVal =
+      Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
     ID.Kind = ValID::t_Constant;
     return false;
   }
@@ -1718,8 +1841,8 @@ bool LLParser::ParseValID(ValID &ID) {
     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
                                           Indices.end()))
       return Error(ID.Loc, "invalid indices for insertvalue");
-    ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
-                                                  &Indices[0], Indices.size());
+    ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
+                       Indices.data(), Indices.size());
     ID.Kind = ValID::t_Constant;
     return false;
   }
@@ -1746,18 +1869,24 @@ bool LLParser::ParseValID(ValID &ID) {
     if (Opc == Instruction::FCmp) {
       if (!Val0->getType()->isFPOrFPVector())
         return Error(ID.Loc, "fcmp requires floating point operands");
-      ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
+      ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
     } else if (Opc == Instruction::ICmp) {
       if (!Val0->getType()->isIntOrIntVector() &&
           !isa<PointerType>(Val0->getType()))
         return Error(ID.Loc, "icmp requires pointer or integer operands");
-      ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
+      ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
     } else if (Opc == Instruction::VFCmp) {
       // FIXME: REMOVE VFCMP Support
-      ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
+      if (!Val0->getType()->isFPOrFPVector() ||
+          !isa<VectorType>(Val0->getType()))
+        return Error(ID.Loc, "vfcmp requires vector floating point operands");
+      ID.ConstantVal = Context.getConstantExprVFCmp(Pred, Val0, Val1);
     } else if (Opc == Instruction::VICmp) {
-      // FIXME: REMOVE VFCMP Support
-      ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
+      // FIXME: REMOVE VICMP Support
+      if (!Val0->getType()->isIntOrIntVector() ||
+          !isa<VectorType>(Val0->getType()))
+        return Error(ID.Loc, "vicmp requires vector floating point operands");
+      ID.ConstantVal = Context.getConstantExprVICmp(Pred, Val0, Val1);
     }
     ID.Kind = ValID::t_Constant;
     return false;
@@ -1765,8 +1894,11 @@ bool LLParser::ParseValID(ValID &ID) {
       
   // Binary Operators.
   case lltok::kw_add:
+  case lltok::kw_fadd:
   case lltok::kw_sub:
+  case lltok::kw_fsub:
   case lltok::kw_mul:
+  case lltok::kw_fmul:
   case lltok::kw_udiv:
   case lltok::kw_sdiv:
   case lltok::kw_fdiv:
@@ -1787,7 +1919,7 @@ bool LLParser::ParseValID(ValID &ID) {
     if (!Val0->getType()->isIntOrIntVector() &&
         !Val0->getType()->isFPOrFPVector())
       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
-    ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
+    ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
     ID.Kind = ValID::t_Constant;
     return false;
   }
@@ -1813,7 +1945,7 @@ bool LLParser::ParseValID(ValID &ID) {
     if (!Val0->getType()->isIntOrIntVector())
       return Error(ID.Loc,
                    "constexpr requires integer or integer vector operands");
-    ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
+    ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
     ID.Kind = ValID::t_Constant;
     return false;
   }  
@@ -1838,7 +1970,7 @@ bool LLParser::ParseValID(ValID &ID) {
       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
                                              (Value**)&Elts[1], Elts.size()-1))
         return Error(ID.Loc, "invalid indices for getelementptr");
-      ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
+      ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
                                                       &Elts[1], Elts.size()-1);
     } else if (Opc == Instruction::Select) {
       if (Elts.size() != 3)
@@ -1846,26 +1978,28 @@ bool LLParser::ParseValID(ValID &ID) {
       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
                                                               Elts[2]))
         return Error(ID.Loc, Reason);
-      ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
+      ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
     } else if (Opc == Instruction::ShuffleVector) {
       if (Elts.size() != 3)
         return Error(ID.Loc, "expected three operands to shufflevector");
       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
         return Error(ID.Loc, "invalid operands to shufflevector");
-      ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
+      ID.ConstantVal =
+                 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
     } else if (Opc == Instruction::ExtractElement) {
       if (Elts.size() != 2)
         return Error(ID.Loc, "expected two operands to extractelement");
       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
         return Error(ID.Loc, "invalid extractelement operands");
-      ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
+      ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
     } else {
       assert(Opc == Instruction::InsertElement && "Unknown opcode");
       if (Elts.size() != 3)
       return Error(ID.Loc, "expected three operands to insertelement");
       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
         return Error(ID.Loc, "invalid insertelement operands");
-      ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
+      ID.ConstantVal =
+                 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
     }
     
     ID.Kind = ValID::t_Constant;
@@ -1881,10 +2015,8 @@ bool LLParser::ParseValID(ValID &ID) {
 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
   V = 0;
   ValID ID;
-  if (ParseValID(ID) ||
-      ConvertGlobalValIDToValue(Ty, ID, V))
-    return true;
-  return false;
+  return ParseValID(ID) ||
+         ConvertGlobalValIDToValue(Ty, ID, V);
 }
 
 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
@@ -1911,7 +2043,7 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
     if (!isa<IntegerType>(Ty))
       return Error(ID.Loc, "integer constant must have integer type");
     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
-    V = ConstantInt::get(ID.APSIntVal);
+    V = Context.getConstantInt(ID.APSIntVal);
     return false;
   case ValID::t_APFloat:
     if (!Ty->isFloatingPoint() ||
@@ -1926,20 +2058,35 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
                             &Ignored);
     }
-    V = ConstantFP::get(ID.APFloatVal);
+    V = Context.getConstantFP(ID.APFloatVal);
+      
+    if (V->getType() != Ty)
+      return Error(ID.Loc, "floating point constant does not have type '" +
+                   Ty->getDescription() + "'");
+      
     return false;
   case ValID::t_Null:
     if (!isa<PointerType>(Ty))
       return Error(ID.Loc, "null must be a pointer type");
-    V = ConstantPointerNull::get(cast<PointerType>(Ty));
+    V = Context.getConstantPointerNull(cast<PointerType>(Ty));
     return false;
   case ValID::t_Undef:
-    V = UndefValue::get(Ty);
+    // FIXME: LabelTy should not be a first-class type.
+    if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
+        !isa<OpaqueType>(Ty))
+      return Error(ID.Loc, "invalid type for undef constant");
+    V = Context.getUndef(Ty);
+    return false;
+  case ValID::t_EmptyArray:
+    if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
+      return Error(ID.Loc, "invalid empty array initializer");
+    V = Context.getUndef(Ty);
     return false;
   case ValID::t_Zero:
-    if (!Ty->isFirstClassType())
+    // FIXME: LabelTy should not be a first-class type.
+    if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
       return Error(ID.Loc, "invalid type for null constant");
-    V = Constant::getNullValue(Ty);
+    V = Context.getNullValue(Ty);
     return false;
   case ValID::t_Constant:
     if (ID.ConstantVal->getType() != Ty)
@@ -1955,6 +2102,9 @@ bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
          ParseGlobalValue(Type, V);
 }    
 
+/// ParseGlobalValueVector
+///   ::= /*empty*/
+///   ::= TypeAndValue (',' TypeAndValue)*
 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
   // Empty list.
   if (Lex.getKind() == lltok::rbrace ||
@@ -1967,8 +2117,7 @@ bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
   if (ParseGlobalTypeAndValue(C)) return true;
   Elts.push_back(C);
   
-  while (Lex.getKind() == lltok::comma) {
-    Lex.Lex();
+  while (EatIfPresent(lltok::comma)) {
     if (ParseGlobalTypeAndValue(C)) return true;
     Elts.push_back(C);
   }
@@ -1987,7 +2136,7 @@ bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
   else if (ID.Kind == ValID::t_LocalName)
     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
-  else if (ID.Kind == ValID::ValID::t_InlineAsm) {
+  else if (ID.Kind == ValID::t_InlineAsm) {
     const PointerType *PTy = dyn_cast<PointerType>(Ty);
     const FunctionType *FTy =
       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
@@ -2008,16 +2157,14 @@ bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
   V = 0;
   ValID ID;
-  if (ParseValID(ID) ||
-      ConvertValIDToValue(Ty, ID, V, PFS))
-    return true;
-  return false;
+  return ParseValID(ID) ||
+         ConvertValIDToValue(Ty, ID, V, PFS);
 }
 
 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
   PATypeHolder T(Type::VoidTy);
-  if (ParseType(T)) return true;
-  return ParseValue(T, V, PFS);
+  return ParseType(T) ||
+         ParseValue(T, V, PFS);
 }
 
 /// FunctionHeader
@@ -2036,7 +2183,7 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
       ParseOptionalVisibility(Visibility) ||
       ParseOptionalCallingConv(CC) ||
       ParseOptionalAttrs(RetAttrs, 1) ||
-      ParseType(RetType, RetTypeLoc))
+      ParseType(RetType, RetTypeLoc, true /*void allowed*/))
     return true;
 
   // Verify that the linkage is ok.
@@ -2048,9 +2195,13 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
     if (isDefine)
       return Error(LinkageLoc, "invalid linkage for function definition");
     break;
+  case GlobalValue::PrivateLinkage:
   case GlobalValue::InternalLinkage:
-  case GlobalValue::LinkOnceLinkage:
-  case GlobalValue::WeakLinkage:
+  case GlobalValue::AvailableExternallyLinkage:
+  case GlobalValue::LinkOnceAnyLinkage:
+  case GlobalValue::LinkOnceODRLinkage:
+  case GlobalValue::WeakAnyLinkage:
+  case GlobalValue::WeakODRLinkage:
   case GlobalValue::DLLExportLinkage:
     if (!isDefine)
       return Error(LinkageLoc, "invalid linkage for function declaration");
@@ -2061,36 +2212,45 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
     return Error(LinkageLoc, "invalid function linkage type");
   }
   
-  if (!FunctionType::isValidReturnType(RetType))
+  if (!FunctionType::isValidReturnType(RetType) ||
+      isa<OpaqueType>(RetType))
     return Error(RetTypeLoc, "invalid function return type");
   
-  if (Lex.getKind() != lltok::GlobalVar)
+  LocTy NameLoc = Lex.getLoc();
+
+  std::string FunctionName;
+  if (Lex.getKind() == lltok::GlobalVar) {
+    FunctionName = Lex.getStrVal();
+  } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
+    unsigned NameID = Lex.getUIntVal();
+
+    if (NameID != NumberedVals.size())
+      return TokError("function expected to be numbered '%" +
+                      utostr(NumberedVals.size()) + "'");
+  } else {
     return TokError("expected function name");
+  }
   
-  LocTy NameLoc = Lex.getLoc();
-  std::string FunctionName = Lex.getStrVal();
+  Lex.Lex();
   
-  if (Lex.Lex() != lltok::lparen)
+  if (Lex.getKind() != lltok::lparen)
     return TokError("expected '(' in function argument list");
   
   std::vector<ArgInfo> ArgList;
   bool isVarArg;
-  if (ParseArgumentList(ArgList, isVarArg)) return true;
-
   unsigned FuncAttrs;
-  if (ParseOptionalAttrs(FuncAttrs, 2)) return true;
-  
-  // Section string.
   std::string Section;
-  if (Lex.getKind() == lltok::kw_section) {
-    if (Lex.Lex() != lltok::StringConstant)
-      return TokError("expected section name");
-    Section = Lex.getStrVal();
-    Lex.Lex();
-  }
-
   unsigned Alignment;
-  if (ParseOptionalAlignment(Alignment)) return true;
+  std::string GC;
+
+  if (ParseArgumentList(ArgList, isVarArg, false) ||
+      ParseOptionalAttrs(FuncAttrs, 2) ||
+      (EatIfPresent(lltok::kw_section) &&
+       ParseStringConstant(Section)) ||
+      ParseOptionalAlignment(Alignment) ||
+      (EatIfPresent(lltok::kw_gc) &&
+       ParseStringConstant(GC)))
+    return true;
 
   // If the alignment was parsed as an attribute, move to the alignment field.
   if (FuncAttrs & Attribute::Alignment) {
@@ -2098,15 +2258,6 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
     FuncAttrs &= ~Attribute::Alignment;
   }
   
-  // Optional GC setting.
-  std::string GC;
-  if (Lex.getKind() == lltok::kw_gc) {
-    if (Lex.Lex() != lltok::StringConstant)
-      return TokError("expected gc name");
-    GC = Lex.getStrVal();
-    Lex.Lex();
-  }
-  
   // Okay, if we got here, the function is syntactically valid.  Convert types
   // and do semantic checks.
   std::vector<const Type*> ParamTypeList;
@@ -2133,8 +2284,13 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
 
   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
   
-  const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
-  const PointerType *PFT = PointerType::getUnqual(FT);
+  if (PAL.paramHasAttr(1, Attribute::StructRet) &&
+      RetType != Type::VoidTy)
+    return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 
+  
+  const FunctionType *FT =
+    Context.getFunctionType(RetType, ParamTypeList, isVarArg);
+  const PointerType *PFT = Context.getPointerTypeUnqual(FT);
 
   Fn = 0;
   if (!FunctionName.empty()) {
@@ -2294,6 +2450,7 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
   if (Token == lltok::Eof)
     return TokError("found end of file when expecting more instructions");
   LocTy Loc = Lex.getLoc();
+  unsigned KeywordVal = Lex.getUIntVal();
   Lex.Lex();  // Eat the keyword.
   
   switch (Token) {
@@ -2309,22 +2466,28 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
   case lltok::kw_add:
   case lltok::kw_sub:
   case lltok::kw_mul:
+    // API compatibility: Accept either integer or floating-point types.
+    return ParseArithmetic(Inst, PFS, KeywordVal, 0);
+  case lltok::kw_fadd:
+  case lltok::kw_fsub:
+  case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
+
   case lltok::kw_udiv:
   case lltok::kw_sdiv:
-  case lltok::kw_fdiv:
   case lltok::kw_urem:
-  case lltok::kw_srem:
-  case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, Lex.getUIntVal());
+  case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
+  case lltok::kw_fdiv:
+  case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
   case lltok::kw_shl:
   case lltok::kw_lshr:
   case lltok::kw_ashr:
   case lltok::kw_and:
   case lltok::kw_or:
-  case lltok::kw_xor:    return ParseLogical(Inst, PFS, Lex.getUIntVal());
+  case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
   case lltok::kw_icmp:
   case lltok::kw_fcmp:
   case lltok::kw_vicmp:
-  case lltok::kw_vfcmp:  return ParseCompare(Inst, PFS, Lex.getUIntVal());
+  case lltok::kw_vfcmp:  return ParseCompare(Inst, PFS, KeywordVal);
   // Casts.
   case lltok::kw_trunc:
   case lltok::kw_zext:
@@ -2337,10 +2500,10 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
   case lltok::kw_fptoui:
   case lltok::kw_fptosi: 
   case lltok::kw_inttoptr:
-  case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, Lex.getUIntVal());
+  case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
   // Other.
   case lltok::kw_select:         return ParseSelect(Inst, PFS);
-  case lltok::kw_va_arg:         return ParseVAArg(Inst, PFS);
+  case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
@@ -2349,20 +2512,17 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
   // Memory.
   case lltok::kw_alloca:
-  case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, Lex.getUIntVal());
+  case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
   case lltok::kw_free:           return ParseFree(Inst, PFS);
   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
   case lltok::kw_volatile:
-    if (Lex.getKind() == lltok::kw_load) {
-      Lex.Lex();
+    if (EatIfPresent(lltok::kw_load))
       return ParseLoad(Inst, PFS, true);
-    } else if (Lex.getKind() == lltok::kw_store) {
-      Lex.Lex();
+    else if (EatIfPresent(lltok::kw_store))
       return ParseStore(Inst, PFS, true);
-    } else {
+    else
       return TokError("expected 'load' or 'store'");
-    }
   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
@@ -2423,7 +2583,7 @@ bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
                         PerFunctionState &PFS) {
   PATypeHolder Ty(Type::VoidTy);
-  if (ParseType(Ty)) return true;
+  if (ParseType(Ty, true /*void allowed*/)) return true;
   
   if (Ty == Type::VoidTy) {
     Inst = ReturnInst::Create();
@@ -2440,13 +2600,12 @@ bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
     SmallVector<Value*, 8> RVs;
     RVs.push_back(RV);
     
-    while (Lex.getKind() == lltok::comma) {
-      Lex.Lex(); // Eat the comma.
+    while (EatIfPresent(lltok::comma)) {
       if (ParseTypeAndValue(RV, PFS)) return true;
       RVs.push_back(RV);
     }
 
-    RV = UndefValue::get(PFS.getFunction().getReturnType());
+    RV = Context.getUndef(PFS.getFunction().getReturnType());
     for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
       Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
       BB->getInstList().push_back(I);
@@ -2482,7 +2641,6 @@ bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
   
   if (!isa<BasicBlock>(Op1))
     return Error(Loc, "true destination of branch must be a basic block");
-    
   if (!isa<BasicBlock>(Op2))
     return Error(Loc2, "true destination of branch must be a basic block");
     
@@ -2555,7 +2713,7 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
   Value *NormalBB, *UnwindBB;
   if (ParseOptionalCallingConv(CC) ||
       ParseOptionalAttrs(RetAttrs, 1) ||
-      ParseType(RetType, RetTypeLoc) ||
+      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
       ParseValID(CalleeID) ||
       ParseParameterList(ArgList, PFS) ||
       ParseOptionalAttrs(FnAttrs, 2) ||
@@ -2585,8 +2743,8 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
     if (!FunctionType::isValidReturnType(RetType))
       return Error(RetTypeLoc, "Invalid result type for LLVM function");
     
-    Ty = FunctionType::get(RetType, ParamTypes, false);
-    PFTy = PointerType::getUnqual(Ty);
+    Ty = Context.getFunctionType(RetType, ParamTypes, false);
+    PFTy = Context.getPointerTypeUnqual(Ty);
   }
   
   // Look up the callee.
@@ -2653,18 +2811,31 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
 //===----------------------------------------------------------------------===//
 
 /// ParseArithmetic
-///  ::= ArithmeticOps TypeAndValue ',' Value {
+///  ::= ArithmeticOps TypeAndValue ',' Value
+///
+/// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
+/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
-                               unsigned Opc) {
+                               unsigned Opc, unsigned OperandType) {
   LocTy Loc; Value *LHS, *RHS;
   if (ParseTypeAndValue(LHS, Loc, PFS) ||
       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
       ParseValue(LHS->getType(), RHS, PFS))
     return true;
 
-  if (!isa<IntegerType>(LHS->getType()) && !LHS->getType()->isFloatingPoint() &&
-      !isa<VectorType>(LHS->getType()))
-    return Error(Loc, "instruction requires integer, fp, or vector operands");
+  bool Valid;
+  switch (OperandType) {
+  default: assert(0 && "Unknown operand type!");
+  case 0: // int or FP.
+    Valid = LHS->getType()->isIntOrIntVector() ||
+            LHS->getType()->isFPOrFPVector();
+    break;
+  case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
+  case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
+  }
+  
+  if (!Valid)
+    return Error(Loc, "invalid operand type for instruction");
   
   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
   return false;
@@ -2715,8 +2886,12 @@ bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
       return Error(Loc, "icmp requires integer operands");
     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
   } else if (Opc == Instruction::VFCmp) {
+    if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
+      return Error(Loc, "vfcmp requires vector floating point operands");
     Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
   } else if (Opc == Instruction::VICmp) {
+    if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
+      return Error(Loc, "vicmp requires vector floating point operands");
     Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
   }
   return false;
@@ -2738,10 +2913,12 @@ bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
       ParseType(DestTy))
     return true;
   
-  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
+  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
+    CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
     return Error(Loc, "invalid cast opcode for cast from '" +
                  Op->getType()->getDescription() + "' to '" +
                  DestTy->getDescription() + "'");
+  }
   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
   return false;
 }
@@ -2765,15 +2942,19 @@ bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
   return false;
 }
 
-/// ParseVAArg
-///   ::= 'vaarg' TypeAndValue ',' Type
-bool LLParser::ParseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
+/// ParseVA_Arg
+///   ::= 'va_arg' TypeAndValue ',' Type
+bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
   Value *Op;
   PATypeHolder EltTy(Type::VoidTy);
+  LocTy TypeLoc;
   if (ParseTypeAndValue(Op, PFS) ||
       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
-      ParseType(EltTy))
+      ParseType(EltTy, TypeLoc))
     return true;
+  
+  if (!EltTy->isFirstClassType())
+    return Error(TypeLoc, "va_arg requires operand with first class type");
 
   Inst = new VAArgInst(Op, EltTy);
   return false;
@@ -2853,11 +3034,10 @@ bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
   while (1) {
     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
     
-    if (Lex.getKind() != lltok::comma)
+    if (!EatIfPresent(lltok::comma))
       break;
 
-    if (ParseToken(lltok::comma, 0) ||
-        ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
+    if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
         ParseValue(Ty, Op0, PFS) ||
         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
         ParseValue(Type::LabelTy, Op1, PFS) ||
@@ -2891,7 +3071,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
       ParseOptionalCallingConv(CC) ||
       ParseOptionalAttrs(RetAttrs, 1) ||
-      ParseType(RetType, RetTypeLoc) ||
+      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
       ParseValID(CalleeID) ||
       ParseParameterList(ArgList, PFS) ||
       ParseOptionalAttrs(FnAttrs, 2))
@@ -2912,23 +3092,14 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
     if (!FunctionType::isValidReturnType(RetType))
       return Error(RetTypeLoc, "Invalid result type for LLVM function");
     
-    Ty = FunctionType::get(RetType, ParamTypes, false);
-    PFTy = PointerType::getUnqual(Ty);
+    Ty = Context.getFunctionType(RetType, ParamTypes, false);
+    PFTy = Context.getPointerTypeUnqual(Ty);
   }
   
   // Look up the callee.
   Value *Callee;
   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
   
-  // Check for call to invalid intrinsic to avoid crashing later.
-  if (Function *F = dyn_cast<Function>(Callee)) {
-    if (F->hasName() && F->getNameLen() >= 5 &&
-        !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
-        !F->getIntrinsicID(true))
-      return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
-                   F->getNameStr() + "'");
-  }
-  
   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
   // function attributes.
   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
@@ -2992,20 +3163,16 @@ bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
                           unsigned Opc) {
   PATypeHolder Ty(Type::VoidTy);
   Value *Size = 0;
-  LocTy SizeLoc = 0;
+  LocTy SizeLoc;
   unsigned Alignment = 0;
-  bool HasComma;
-  if (ParseType(Ty) ||
-      ParseOptionalToken(lltok::comma, HasComma))
-    return true;
+  if (ParseType(Ty)) return true;
 
-  if (HasComma) {
+  if (EatIfPresent(lltok::comma)) {
     if (Lex.getKind() == lltok::kw_align) {
       if (ParseOptionalAlignment(Alignment)) return true;
-    } else {
-      if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
-      if (ParseOptionalCommaAlignment(Alignment))
-        return true;
+    } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
+               ParseOptionalCommaAlignment(Alignment)) {
+      return true;
     }
   }
 
@@ -3031,7 +3198,7 @@ bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
 }
 
 /// ParseLoad
-///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
+///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
                          bool isVolatile) {
   Value *Val; LocTy Loc;
@@ -3049,7 +3216,7 @@ bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
 }
 
 /// ParseStore
-///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
+///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
                           bool isVolatile) {
   Value *Val, *Ptr; LocTy Loc, PtrLoc;
@@ -3072,14 +3239,14 @@ bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
 }
 
 /// ParseGetResult
-///   ::= 'getresult' TypeAndValue ',' uint
+///   ::= 'getresult' TypeAndValue ',' i32
 /// FIXME: Remove support for getresult in LLVM 3.0
 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
   Value *Val; LocTy ValLoc, EltLoc;
   unsigned Element;
   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
-      ParseUnsigned(Element, EltLoc))
+      ParseUInt32(Element, EltLoc))
     return true;
   
   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
@@ -3094,17 +3261,14 @@ bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
 ///   ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
   Value *Ptr, *Val; LocTy Loc, EltLoc;
-  if (ParseTypeAndValue(Ptr, Loc, PFS))
-    return true;
+  if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
   
   if (!isa<PointerType>(Ptr->getType()))
     return Error(Loc, "base of getelementptr must be a pointer");
   
   SmallVector<Value*, 16> Indices;
-  while (Lex.getKind() == lltok::comma) {
-    Lex.Lex();
-    if (ParseTypeAndValue(Val, EltLoc, PFS))
-      return true;
+  while (EatIfPresent(lltok::comma)) {
+    if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
     if (!isa<IntegerType>(Val->getType()))
       return Error(EltLoc, "getelementptr index must be an integer");
     Indices.push_back(Val);
@@ -3156,3 +3320,30 @@ bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
   return false;
 }
+
+//===----------------------------------------------------------------------===//
+// Embedded metadata.
+//===----------------------------------------------------------------------===//
+
+/// ParseMDNodeVector
+///   ::= Element (',' Element)*
+/// Element
+///   ::= 'null' | TypeAndValue
+bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
+  assert(Lex.getKind() == lltok::lbrace);
+  Lex.Lex();
+  do {
+    Value *V;
+    if (Lex.getKind() == lltok::kw_null) {
+      Lex.Lex();
+      V = 0;
+    } else {
+      Constant *C;
+      if (ParseGlobalTypeAndValue(C)) return true;
+      V = C;
+    }
+    Elts.push_back(V);
+  } while (EatIfPresent(lltok::comma));
+
+  return false;
+}