5c4450244c188fb2666eeaf91ffe47430aeae7f5
[oota-llvm.git] / lib / AsmParser / LLParser.cpp
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLParser.h"
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/MDNode.h"
22 #include "llvm/Module.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 namespace llvm {
30   /// ValID - Represents a reference of a definition of some sort with no type.
31   /// There are several cases where we have to parse the value but where the
32   /// type can depend on later context.  This may either be a numeric reference
33   /// or a symbolic (%var) reference.  This is just a discriminated union.
34   struct ValID {
35     enum {
36       t_LocalID, t_GlobalID,      // ID in UIntVal.
37       t_LocalName, t_GlobalName,  // Name in StrVal.
38       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
39       t_Null, t_Undef, t_Zero,    // No value.
40       t_EmptyArray,               // No value:  []
41       t_Constant,                 // Value in ConstantVal.
42       t_InlineAsm                 // Value in StrVal/StrVal2/UIntVal.
43     } Kind;
44     
45     LLParser::LocTy Loc;
46     unsigned UIntVal;
47     std::string StrVal, StrVal2;
48     APSInt APSIntVal;
49     APFloat APFloatVal;
50     Constant *ConstantVal;
51     ValID() : APFloatVal(0.0) {}
52   };
53 }
54
55 /// Run: module ::= toplevelentity*
56 bool LLParser::Run() {
57   // Prime the lexer.
58   Lex.Lex();
59
60   return ParseTopLevelEntities() ||
61          ValidateEndOfModule();
62 }
63
64 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65 /// module.
66 bool LLParser::ValidateEndOfModule() {
67   if (!ForwardRefTypes.empty())
68     return Error(ForwardRefTypes.begin()->second.second,
69                  "use of undefined type named '" +
70                  ForwardRefTypes.begin()->first + "'");
71   if (!ForwardRefTypeIDs.empty())
72     return Error(ForwardRefTypeIDs.begin()->second.second,
73                  "use of undefined type '%" +
74                  utostr(ForwardRefTypeIDs.begin()->first) + "'");
75   
76   if (!ForwardRefVals.empty())
77     return Error(ForwardRefVals.begin()->second.second,
78                  "use of undefined value '@" + ForwardRefVals.begin()->first +
79                  "'");
80   
81   if (!ForwardRefValIDs.empty())
82     return Error(ForwardRefValIDs.begin()->second.second,
83                  "use of undefined value '@" +
84                  utostr(ForwardRefValIDs.begin()->first) + "'");
85   
86   // Look for intrinsic functions and CallInst that need to be upgraded
87   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
88     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
89   
90   return false;
91 }
92
93 //===----------------------------------------------------------------------===//
94 // Top-Level Entities
95 //===----------------------------------------------------------------------===//
96
97 bool LLParser::ParseTopLevelEntities() {
98   while (1) {
99     switch (Lex.getKind()) {
100     default:         return TokError("expected top-level entity");
101     case lltok::Eof: return false;
102     //case lltok::kw_define:
103     case lltok::kw_declare: if (ParseDeclare()) return true; break;
104     case lltok::kw_define:  if (ParseDefine()) return true; break;
105     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
106     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
107     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
108     case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
109     case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
110     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
111     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
112
113     // The Global variable production with no name can have many different
114     // optional leading prefixes, the production is:
115     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
116     //               OptionalAddrSpace ('constant'|'global') ...
117     case lltok::kw_private:       // OptionalLinkage
118     case lltok::kw_internal:      // OptionalLinkage
119     case lltok::kw_weak:          // OptionalLinkage
120     case lltok::kw_weak_odr:      // OptionalLinkage
121     case lltok::kw_linkonce:      // OptionalLinkage
122     case lltok::kw_linkonce_odr:  // OptionalLinkage
123     case lltok::kw_appending:     // OptionalLinkage
124     case lltok::kw_dllexport:     // OptionalLinkage
125     case lltok::kw_common:        // OptionalLinkage
126     case lltok::kw_dllimport:     // OptionalLinkage
127     case lltok::kw_extern_weak:   // OptionalLinkage
128     case lltok::kw_external: {    // OptionalLinkage
129       unsigned Linkage, Visibility;
130       if (ParseOptionalLinkage(Linkage) ||
131           ParseOptionalVisibility(Visibility) ||
132           ParseGlobal("", 0, Linkage, true, Visibility))
133         return true;
134       break;
135     }
136     case lltok::kw_default:       // OptionalVisibility
137     case lltok::kw_hidden:        // OptionalVisibility
138     case lltok::kw_protected: {   // OptionalVisibility
139       unsigned Visibility;
140       if (ParseOptionalVisibility(Visibility) ||
141           ParseGlobal("", 0, 0, false, Visibility))
142         return true;
143       break;
144     }
145         
146     case lltok::kw_thread_local:  // OptionalThreadLocal
147     case lltok::kw_addrspace:     // OptionalAddrSpace
148     case lltok::kw_constant:      // GlobalType
149     case lltok::kw_global:        // GlobalType
150       if (ParseGlobal("", 0, 0, false, 0)) return true;
151       break;
152     }
153   }
154 }
155
156
157 /// toplevelentity
158 ///   ::= 'module' 'asm' STRINGCONSTANT
159 bool LLParser::ParseModuleAsm() {
160   assert(Lex.getKind() == lltok::kw_module);
161   Lex.Lex();
162   
163   std::string AsmStr; 
164   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
165       ParseStringConstant(AsmStr)) return true;
166   
167   const std::string &AsmSoFar = M->getModuleInlineAsm();
168   if (AsmSoFar.empty())
169     M->setModuleInlineAsm(AsmStr);
170   else
171     M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
172   return false;
173 }
174
175 /// toplevelentity
176 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
177 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
178 bool LLParser::ParseTargetDefinition() {
179   assert(Lex.getKind() == lltok::kw_target);
180   std::string Str;
181   switch (Lex.Lex()) {
182   default: return TokError("unknown target property");
183   case lltok::kw_triple:
184     Lex.Lex();
185     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
186         ParseStringConstant(Str))
187       return true;
188     M->setTargetTriple(Str);
189     return false;
190   case lltok::kw_datalayout:
191     Lex.Lex();
192     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
193         ParseStringConstant(Str))
194       return true;
195     M->setDataLayout(Str);
196     return false;
197   }
198 }
199
200 /// toplevelentity
201 ///   ::= 'deplibs' '=' '[' ']'
202 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
203 bool LLParser::ParseDepLibs() {
204   assert(Lex.getKind() == lltok::kw_deplibs);
205   Lex.Lex();
206   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
207       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
208     return true;
209
210   if (EatIfPresent(lltok::rsquare))
211     return false;
212   
213   std::string Str;
214   if (ParseStringConstant(Str)) return true;
215   M->addLibrary(Str);
216
217   while (EatIfPresent(lltok::comma)) {
218     if (ParseStringConstant(Str)) return true;
219     M->addLibrary(Str);
220   }
221
222   return ParseToken(lltok::rsquare, "expected ']' at end of list");
223 }
224
225 /// toplevelentity
226 ///   ::= 'type' type
227 bool LLParser::ParseUnnamedType() {
228   assert(Lex.getKind() == lltok::kw_type);
229   LocTy TypeLoc = Lex.getLoc();
230   Lex.Lex(); // eat kw_type
231
232   PATypeHolder Ty(Type::VoidTy);
233   if (ParseType(Ty)) return true;
234  
235   unsigned TypeID = NumberedTypes.size();
236   
237   // See if this type was previously referenced.
238   std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
239     FI = ForwardRefTypeIDs.find(TypeID);
240   if (FI != ForwardRefTypeIDs.end()) {
241     if (FI->second.first.get() == Ty)
242       return Error(TypeLoc, "self referential type is invalid");
243     
244     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
245     Ty = FI->second.first.get();
246     ForwardRefTypeIDs.erase(FI);
247   }
248   
249   NumberedTypes.push_back(Ty);
250   
251   return false;
252 }
253
254 /// toplevelentity
255 ///   ::= LocalVar '=' 'type' type
256 bool LLParser::ParseNamedType() {
257   std::string Name = Lex.getStrVal();
258   LocTy NameLoc = Lex.getLoc();
259   Lex.Lex();  // eat LocalVar.
260   
261   PATypeHolder Ty(Type::VoidTy);
262   
263   if (ParseToken(lltok::equal, "expected '=' after name") ||
264       ParseToken(lltok::kw_type, "expected 'type' after name") ||
265       ParseType(Ty))
266     return true;
267   
268   // Set the type name, checking for conflicts as we do so.
269   bool AlreadyExists = M->addTypeName(Name, Ty);
270   if (!AlreadyExists) return false;
271
272   // See if this type is a forward reference.  We need to eagerly resolve
273   // types to allow recursive type redefinitions below.
274   std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
275   FI = ForwardRefTypes.find(Name);
276   if (FI != ForwardRefTypes.end()) {
277     if (FI->second.first.get() == Ty)
278       return Error(NameLoc, "self referential type is invalid");
279
280     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
281     Ty = FI->second.first.get();
282     ForwardRefTypes.erase(FI);
283   }
284   
285   // Inserting a name that is already defined, get the existing name.
286   const Type *Existing = M->getTypeByName(Name);
287   assert(Existing && "Conflict but no matching type?!");
288     
289   // Otherwise, this is an attempt to redefine a type. That's okay if
290   // the redefinition is identical to the original.
291   // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
292   if (Existing == Ty) return false;
293   
294   // Any other kind of (non-equivalent) redefinition is an error.
295   return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
296                Ty->getDescription() + "'");
297 }
298
299
300 /// toplevelentity
301 ///   ::= 'declare' FunctionHeader
302 bool LLParser::ParseDeclare() {
303   assert(Lex.getKind() == lltok::kw_declare);
304   Lex.Lex();
305   
306   Function *F;
307   return ParseFunctionHeader(F, false);
308 }
309
310 /// toplevelentity
311 ///   ::= 'define' FunctionHeader '{' ...
312 bool LLParser::ParseDefine() {
313   assert(Lex.getKind() == lltok::kw_define);
314   Lex.Lex();
315   
316   Function *F;
317   return ParseFunctionHeader(F, true) ||
318          ParseFunctionBody(*F);
319 }
320
321 /// ParseGlobalType
322 ///   ::= 'constant'
323 ///   ::= 'global'
324 bool LLParser::ParseGlobalType(bool &IsConstant) {
325   if (Lex.getKind() == lltok::kw_constant)
326     IsConstant = true;
327   else if (Lex.getKind() == lltok::kw_global)
328     IsConstant = false;
329   else {
330     IsConstant = false;
331     return TokError("expected 'global' or 'constant'");
332   }
333   Lex.Lex();
334   return false;
335 }
336
337 /// ParseNamedGlobal:
338 ///   GlobalVar '=' OptionalVisibility ALIAS ...
339 ///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
340 bool LLParser::ParseNamedGlobal() {
341   assert(Lex.getKind() == lltok::GlobalVar);
342   LocTy NameLoc = Lex.getLoc();
343   std::string Name = Lex.getStrVal();
344   Lex.Lex();
345   
346   bool HasLinkage;
347   unsigned Linkage, Visibility;
348   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
349       ParseOptionalLinkage(Linkage, HasLinkage) ||
350       ParseOptionalVisibility(Visibility))
351     return true;
352   
353   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
354     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
355   return ParseAlias(Name, NameLoc, Visibility);
356 }
357
358 /// ParseAlias:
359 ///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
360 /// Aliasee
361 ///   ::= TypeAndValue
362 ///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
363 ///   ::= 'getelementptr' '(' ... ')'
364 ///
365 /// Everything through visibility has already been parsed.
366 ///
367 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
368                           unsigned Visibility) {
369   assert(Lex.getKind() == lltok::kw_alias);
370   Lex.Lex();
371   unsigned Linkage;
372   LocTy LinkageLoc = Lex.getLoc();
373   if (ParseOptionalLinkage(Linkage))
374     return true;
375
376   if (Linkage != GlobalValue::ExternalLinkage &&
377       Linkage != GlobalValue::WeakAnyLinkage &&
378       Linkage != GlobalValue::WeakODRLinkage &&
379       Linkage != GlobalValue::InternalLinkage &&
380       Linkage != GlobalValue::PrivateLinkage)
381     return Error(LinkageLoc, "invalid linkage type for alias");
382   
383   Constant *Aliasee;
384   LocTy AliaseeLoc = Lex.getLoc();
385   if (Lex.getKind() != lltok::kw_bitcast &&
386       Lex.getKind() != lltok::kw_getelementptr) {
387     if (ParseGlobalTypeAndValue(Aliasee)) return true;
388   } else {
389     // The bitcast dest type is not present, it is implied by the dest type.
390     ValID ID;
391     if (ParseValID(ID)) return true;
392     if (ID.Kind != ValID::t_Constant)
393       return Error(AliaseeLoc, "invalid aliasee");
394     Aliasee = ID.ConstantVal;
395   }
396   
397   if (!isa<PointerType>(Aliasee->getType()))
398     return Error(AliaseeLoc, "alias must have pointer type");
399
400   // Okay, create the alias but do not insert it into the module yet.
401   GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
402                                     (GlobalValue::LinkageTypes)Linkage, Name,
403                                     Aliasee);
404   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
405   
406   // See if this value already exists in the symbol table.  If so, it is either
407   // a redefinition or a definition of a forward reference.
408   if (GlobalValue *Val =
409         cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
410     // See if this was a redefinition.  If so, there is no entry in
411     // ForwardRefVals.
412     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
413       I = ForwardRefVals.find(Name);
414     if (I == ForwardRefVals.end())
415       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
416
417     // Otherwise, this was a definition of forward ref.  Verify that types
418     // agree.
419     if (Val->getType() != GA->getType())
420       return Error(NameLoc,
421               "forward reference and definition of alias have different types");
422     
423     // If they agree, just RAUW the old value with the alias and remove the
424     // forward ref info.
425     Val->replaceAllUsesWith(GA);
426     Val->eraseFromParent();
427     ForwardRefVals.erase(I);
428   }
429   
430   // Insert into the module, we know its name won't collide now.
431   M->getAliasList().push_back(GA);
432   assert(GA->getNameStr() == Name && "Should not be a name conflict!");
433   
434   return false;
435 }
436
437 /// ParseGlobal
438 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
439 ///       OptionalAddrSpace GlobalType Type Const
440 ///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
441 ///       OptionalAddrSpace GlobalType Type Const
442 ///
443 /// Everything through visibility has been parsed already.
444 ///
445 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
446                            unsigned Linkage, bool HasLinkage,
447                            unsigned Visibility) {
448   unsigned AddrSpace;
449   bool ThreadLocal, IsConstant;
450   LocTy TyLoc;
451     
452   PATypeHolder Ty(Type::VoidTy);
453   if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
454       ParseOptionalAddrSpace(AddrSpace) ||
455       ParseGlobalType(IsConstant) ||
456       ParseType(Ty, TyLoc))
457     return true;
458   
459   // If the linkage is specified and is external, then no initializer is
460   // present.
461   Constant *Init = 0;
462   if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
463                       Linkage != GlobalValue::ExternalWeakLinkage &&
464                       Linkage != GlobalValue::ExternalLinkage)) {
465     if (ParseGlobalValue(Ty, Init))
466       return true;
467   }
468
469   if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
470     return Error(TyLoc, "invalid type for global variable");
471   
472   GlobalVariable *GV = 0;
473
474   // See if the global was forward referenced, if so, use the global.
475   if (!Name.empty()) {
476     if ((GV = M->getGlobalVariable(Name, true)) &&
477         !ForwardRefVals.erase(Name))
478       return Error(NameLoc, "redefinition of global '@" + Name + "'");
479   } else {
480     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
481       I = ForwardRefValIDs.find(NumberedVals.size());
482     if (I != ForwardRefValIDs.end()) {
483       GV = cast<GlobalVariable>(I->second.first);
484       ForwardRefValIDs.erase(I);
485     }
486   }
487
488   if (GV == 0) {
489     GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
490                             M, false, AddrSpace);
491   } else {
492     if (GV->getType()->getElementType() != Ty)
493       return Error(TyLoc,
494             "forward reference and definition of global have different types");
495     
496     // Move the forward-reference to the correct spot in the module.
497     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
498   }
499
500   if (Name.empty())
501     NumberedVals.push_back(GV);
502   
503   // Set the parsed properties on the global.
504   if (Init)
505     GV->setInitializer(Init);
506   GV->setConstant(IsConstant);
507   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
508   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
509   GV->setThreadLocal(ThreadLocal);
510   
511   // Parse attributes on the global.
512   while (Lex.getKind() == lltok::comma) {
513     Lex.Lex();
514     
515     if (Lex.getKind() == lltok::kw_section) {
516       Lex.Lex();
517       GV->setSection(Lex.getStrVal());
518       if (ParseToken(lltok::StringConstant, "expected global section string"))
519         return true;
520     } else if (Lex.getKind() == lltok::kw_align) {
521       unsigned Alignment;
522       if (ParseOptionalAlignment(Alignment)) return true;
523       GV->setAlignment(Alignment);
524     } else {
525       TokError("unknown global variable property!");
526     }
527   }
528   
529   return false;
530 }
531
532
533 //===----------------------------------------------------------------------===//
534 // GlobalValue Reference/Resolution Routines.
535 //===----------------------------------------------------------------------===//
536
537 /// GetGlobalVal - Get a value with the specified name or ID, creating a
538 /// forward reference record if needed.  This can return null if the value
539 /// exists but does not have the right type.
540 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
541                                     LocTy Loc) {
542   const PointerType *PTy = dyn_cast<PointerType>(Ty);
543   if (PTy == 0) {
544     Error(Loc, "global variable reference must have pointer type");
545     return 0;
546   }
547   
548   // Look this name up in the normal function symbol table.
549   GlobalValue *Val =
550     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
551   
552   // If this is a forward reference for the value, see if we already created a
553   // forward ref record.
554   if (Val == 0) {
555     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
556       I = ForwardRefVals.find(Name);
557     if (I != ForwardRefVals.end())
558       Val = I->second.first;
559   }
560   
561   // If we have the value in the symbol table or fwd-ref table, return it.
562   if (Val) {
563     if (Val->getType() == Ty) return Val;
564     Error(Loc, "'@" + Name + "' defined with type '" +
565           Val->getType()->getDescription() + "'");
566     return 0;
567   }
568   
569   // Otherwise, create a new forward reference for this value and remember it.
570   GlobalValue *FwdVal;
571   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
572     // Function types can return opaque but functions can't.
573     if (isa<OpaqueType>(FT->getReturnType())) {
574       Error(Loc, "function may not return opaque type");
575       return 0;
576     }
577     
578     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
579   } else {
580     FwdVal = new GlobalVariable(PTy->getElementType(), false,
581                                 GlobalValue::ExternalWeakLinkage, 0, Name, M);
582   }
583   
584   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
585   return FwdVal;
586 }
587
588 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
589   const PointerType *PTy = dyn_cast<PointerType>(Ty);
590   if (PTy == 0) {
591     Error(Loc, "global variable reference must have pointer type");
592     return 0;
593   }
594   
595   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
596   
597   // If this is a forward reference for the value, see if we already created a
598   // forward ref record.
599   if (Val == 0) {
600     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
601       I = ForwardRefValIDs.find(ID);
602     if (I != ForwardRefValIDs.end())
603       Val = I->second.first;
604   }
605   
606   // If we have the value in the symbol table or fwd-ref table, return it.
607   if (Val) {
608     if (Val->getType() == Ty) return Val;
609     Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
610           Val->getType()->getDescription() + "'");
611     return 0;
612   }
613   
614   // Otherwise, create a new forward reference for this value and remember it.
615   GlobalValue *FwdVal;
616   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
617     // Function types can return opaque but functions can't.
618     if (isa<OpaqueType>(FT->getReturnType())) {
619       Error(Loc, "function may not return opaque type");
620       return 0;
621     }
622     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
623   } else {
624     FwdVal = new GlobalVariable(PTy->getElementType(), false,
625                                 GlobalValue::ExternalWeakLinkage, 0, "", M);
626   }
627   
628   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
629   return FwdVal;
630 }
631
632
633 //===----------------------------------------------------------------------===//
634 // Helper Routines.
635 //===----------------------------------------------------------------------===//
636
637 /// ParseToken - If the current token has the specified kind, eat it and return
638 /// success.  Otherwise, emit the specified error and return failure.
639 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
640   if (Lex.getKind() != T)
641     return TokError(ErrMsg);
642   Lex.Lex();
643   return false;
644 }
645
646 /// ParseStringConstant
647 ///   ::= StringConstant
648 bool LLParser::ParseStringConstant(std::string &Result) {
649   if (Lex.getKind() != lltok::StringConstant)
650     return TokError("expected string constant");
651   Result = Lex.getStrVal();
652   Lex.Lex();
653   return false;
654 }
655
656 /// ParseUInt32
657 ///   ::= uint32
658 bool LLParser::ParseUInt32(unsigned &Val) {
659   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
660     return TokError("expected integer");
661   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
662   if (Val64 != unsigned(Val64))
663     return TokError("expected 32-bit integer (too large)");
664   Val = Val64;
665   Lex.Lex();
666   return false;
667 }
668
669
670 /// ParseOptionalAddrSpace
671 ///   := /*empty*/
672 ///   := 'addrspace' '(' uint32 ')'
673 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
674   AddrSpace = 0;
675   if (!EatIfPresent(lltok::kw_addrspace))
676     return false;
677   return ParseToken(lltok::lparen, "expected '(' in address space") ||
678          ParseUInt32(AddrSpace) ||
679          ParseToken(lltok::rparen, "expected ')' in address space");
680 }  
681
682 /// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
683 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
684 /// 2: function attr.
685 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
686 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
687   Attrs = Attribute::None;
688   LocTy AttrLoc = Lex.getLoc();
689   
690   while (1) {
691     switch (Lex.getKind()) {
692     case lltok::kw_sext:
693     case lltok::kw_zext:
694       // Treat these as signext/zeroext if they occur in the argument list after
695       // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
696       // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
697       // expr.
698       // FIXME: REMOVE THIS IN LLVM 3.0
699       if (AttrKind == 3) {
700         if (Lex.getKind() == lltok::kw_sext)
701           Attrs |= Attribute::SExt;
702         else
703           Attrs |= Attribute::ZExt;
704         break;
705       }
706       // FALL THROUGH.
707     default:  // End of attributes.
708       if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
709         return Error(AttrLoc, "invalid use of function-only attribute");
710         
711       if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
712         return Error(AttrLoc, "invalid use of parameter-only attribute");
713         
714       return false;
715     case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
716     case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
717     case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
718     case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
719     case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
720     case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
721     case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
722     case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
723
724     case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
725     case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
726     case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
727     case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
728     case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
729     case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
730     case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
731     case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
732     case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
733     case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
734     case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
735         
736     case lltok::kw_align: {
737       unsigned Alignment;
738       if (ParseOptionalAlignment(Alignment))
739         return true;
740       Attrs |= Attribute::constructAlignmentFromInt(Alignment);
741       continue;
742     }
743     }
744     Lex.Lex();
745   }
746 }
747
748 /// ParseOptionalLinkage
749 ///   ::= /*empty*/
750 ///   ::= 'private'
751 ///   ::= 'internal'
752 ///   ::= 'weak'
753 ///   ::= 'weak_odr'
754 ///   ::= 'linkonce'
755 ///   ::= 'linkonce_odr'
756 ///   ::= 'appending'
757 ///   ::= 'dllexport'
758 ///   ::= 'common'
759 ///   ::= 'dllimport'
760 ///   ::= 'extern_weak'
761 ///   ::= 'external'
762 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
763   HasLinkage = false;
764   switch (Lex.getKind()) {
765   default:                     Res = GlobalValue::ExternalLinkage; return false;
766   case lltok::kw_private:      Res = GlobalValue::PrivateLinkage; break;
767   case lltok::kw_internal:     Res = GlobalValue::InternalLinkage; break;
768   case lltok::kw_weak:         Res = GlobalValue::WeakAnyLinkage; break;
769   case lltok::kw_weak_odr:     Res = GlobalValue::WeakODRLinkage; break;
770   case lltok::kw_linkonce:     Res = GlobalValue::LinkOnceAnyLinkage; break;
771   case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
772   case lltok::kw_available_externally:
773     Res = GlobalValue::AvailableExternallyLinkage;
774     break;
775   case lltok::kw_appending:    Res = GlobalValue::AppendingLinkage; break;
776   case lltok::kw_dllexport:    Res = GlobalValue::DLLExportLinkage; break;
777   case lltok::kw_common:       Res = GlobalValue::CommonLinkage; break;
778   case lltok::kw_dllimport:    Res = GlobalValue::DLLImportLinkage; break;
779   case lltok::kw_extern_weak:  Res = GlobalValue::ExternalWeakLinkage; break;
780   case lltok::kw_external:     Res = GlobalValue::ExternalLinkage; break;
781   }
782   Lex.Lex();
783   HasLinkage = true;
784   return false;
785 }
786
787 /// ParseOptionalVisibility
788 ///   ::= /*empty*/
789 ///   ::= 'default'
790 ///   ::= 'hidden'
791 ///   ::= 'protected'
792 /// 
793 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
794   switch (Lex.getKind()) {
795   default:                  Res = GlobalValue::DefaultVisibility; return false;
796   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
797   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
798   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
799   }
800   Lex.Lex();
801   return false;
802 }
803
804 /// ParseOptionalCallingConv
805 ///   ::= /*empty*/
806 ///   ::= 'ccc'
807 ///   ::= 'fastcc'
808 ///   ::= 'coldcc'
809 ///   ::= 'x86_stdcallcc'
810 ///   ::= 'x86_fastcallcc'
811 ///   ::= 'cc' UINT
812 /// 
813 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
814   switch (Lex.getKind()) {
815   default:                       CC = CallingConv::C; return false;
816   case lltok::kw_ccc:            CC = CallingConv::C; break;
817   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
818   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
819   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
820   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
821   case lltok::kw_cc:             Lex.Lex(); return ParseUInt32(CC);
822   }
823   Lex.Lex();
824   return false;
825 }
826
827 /// ParseOptionalAlignment
828 ///   ::= /* empty */
829 ///   ::= 'align' 4
830 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
831   Alignment = 0;
832   if (!EatIfPresent(lltok::kw_align))
833     return false;
834   LocTy AlignLoc = Lex.getLoc();
835   if (ParseUInt32(Alignment)) return true;
836   if (!isPowerOf2_32(Alignment))
837     return Error(AlignLoc, "alignment is not a power of two");
838   return false;
839 }
840
841 /// ParseOptionalCommaAlignment
842 ///   ::= /* empty */
843 ///   ::= ',' 'align' 4
844 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
845   Alignment = 0;
846   if (!EatIfPresent(lltok::comma))
847     return false;
848   return ParseToken(lltok::kw_align, "expected 'align'") ||
849          ParseUInt32(Alignment);
850 }
851
852 /// ParseIndexList
853 ///    ::=  (',' uint32)+
854 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
855   if (Lex.getKind() != lltok::comma)
856     return TokError("expected ',' as start of index list");
857   
858   while (EatIfPresent(lltok::comma)) {
859     unsigned Idx;
860     if (ParseUInt32(Idx)) return true;
861     Indices.push_back(Idx);
862   }
863   
864   return false;
865 }
866
867 //===----------------------------------------------------------------------===//
868 // Type Parsing.
869 //===----------------------------------------------------------------------===//
870
871 /// ParseType - Parse and resolve a full type.
872 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
873   LocTy TypeLoc = Lex.getLoc();
874   if (ParseTypeRec(Result)) return true;
875   
876   // Verify no unresolved uprefs.
877   if (!UpRefs.empty())
878     return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
879   
880   if (!AllowVoid && Result.get() == Type::VoidTy)
881     return Error(TypeLoc, "void type only allowed for function results");
882   
883   return false;
884 }
885
886 /// HandleUpRefs - Every time we finish a new layer of types, this function is
887 /// called.  It loops through the UpRefs vector, which is a list of the
888 /// currently active types.  For each type, if the up-reference is contained in
889 /// the newly completed type, we decrement the level count.  When the level
890 /// count reaches zero, the up-referenced type is the type that is passed in:
891 /// thus we can complete the cycle.
892 ///
893 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
894   // If Ty isn't abstract, or if there are no up-references in it, then there is
895   // nothing to resolve here.
896   if (!ty->isAbstract() || UpRefs.empty()) return ty;
897   
898   PATypeHolder Ty(ty);
899 #if 0
900   errs() << "Type '" << Ty->getDescription()
901          << "' newly formed.  Resolving upreferences.\n"
902          << UpRefs.size() << " upreferences active!\n";
903 #endif
904   
905   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
906   // to zero), we resolve them all together before we resolve them to Ty.  At
907   // the end of the loop, if there is anything to resolve to Ty, it will be in
908   // this variable.
909   OpaqueType *TypeToResolve = 0;
910   
911   for (unsigned i = 0; i != UpRefs.size(); ++i) {
912     // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
913     bool ContainsType =
914       std::find(Ty->subtype_begin(), Ty->subtype_end(),
915                 UpRefs[i].LastContainedTy) != Ty->subtype_end();
916     
917 #if 0
918     errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
919            << UpRefs[i].LastContainedTy->getDescription() << ") = "
920            << (ContainsType ? "true" : "false")
921            << " level=" << UpRefs[i].NestingLevel << "\n";
922 #endif
923     if (!ContainsType)
924       continue;
925     
926     // Decrement level of upreference
927     unsigned Level = --UpRefs[i].NestingLevel;
928     UpRefs[i].LastContainedTy = Ty;
929     
930     // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
931     if (Level != 0)
932       continue;
933     
934 #if 0
935     errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
936 #endif
937     if (!TypeToResolve)
938       TypeToResolve = UpRefs[i].UpRefTy;
939     else
940       UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
941     UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
942     --i;                                // Do not skip the next element.
943   }
944   
945   if (TypeToResolve)
946     TypeToResolve->refineAbstractTypeTo(Ty);
947   
948   return Ty;
949 }
950
951
952 /// ParseTypeRec - The recursive function used to process the internal
953 /// implementation details of types.
954 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
955   switch (Lex.getKind()) {
956   default:
957     return TokError("expected type");
958   case lltok::Type:
959     // TypeRec ::= 'float' | 'void' (etc)
960     Result = Lex.getTyVal();
961     Lex.Lex(); 
962     break;
963   case lltok::kw_opaque:
964     // TypeRec ::= 'opaque'
965     Result = OpaqueType::get();
966     Lex.Lex();
967     break;
968   case lltok::lbrace:
969     // TypeRec ::= '{' ... '}'
970     if (ParseStructType(Result, false))
971       return true;
972     break;
973   case lltok::lsquare:
974     // TypeRec ::= '[' ... ']'
975     Lex.Lex(); // eat the lsquare.
976     if (ParseArrayVectorType(Result, false))
977       return true;
978     break;
979   case lltok::less: // Either vector or packed struct.
980     // TypeRec ::= '<' ... '>'
981     Lex.Lex();
982     if (Lex.getKind() == lltok::lbrace) {
983       if (ParseStructType(Result, true) ||
984           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
985         return true;
986     } else if (ParseArrayVectorType(Result, true))
987       return true;
988     break;
989   case lltok::LocalVar:
990   case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
991     // TypeRec ::= %foo
992     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
993       Result = T;
994     } else {
995       Result = OpaqueType::get();
996       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
997                                             std::make_pair(Result,
998                                                            Lex.getLoc())));
999       M->addTypeName(Lex.getStrVal(), Result.get());
1000     }
1001     Lex.Lex();
1002     break;
1003       
1004   case lltok::LocalVarID:
1005     // TypeRec ::= %4
1006     if (Lex.getUIntVal() < NumberedTypes.size())
1007       Result = NumberedTypes[Lex.getUIntVal()];
1008     else {
1009       std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1010         I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1011       if (I != ForwardRefTypeIDs.end())
1012         Result = I->second.first;
1013       else {
1014         Result = OpaqueType::get();
1015         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1016                                                 std::make_pair(Result,
1017                                                                Lex.getLoc())));
1018       }
1019     }
1020     Lex.Lex();
1021     break;
1022   case lltok::backslash: {
1023     // TypeRec ::= '\' 4
1024     Lex.Lex();
1025     unsigned Val;
1026     if (ParseUInt32(Val)) return true;
1027     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder.
1028     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1029     Result = OT;
1030     break;
1031   }
1032   }
1033   
1034   // Parse the type suffixes. 
1035   while (1) {
1036     switch (Lex.getKind()) {
1037     // End of type.
1038     default: return false;    
1039
1040     // TypeRec ::= TypeRec '*'
1041     case lltok::star:
1042       if (Result.get() == Type::LabelTy)
1043         return TokError("basic block pointers are invalid");
1044       if (Result.get() == Type::VoidTy)
1045         return TokError("pointers to void are invalid; use i8* instead");
1046       Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1047       Lex.Lex();
1048       break;
1049
1050     // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1051     case lltok::kw_addrspace: {
1052       if (Result.get() == Type::LabelTy)
1053         return TokError("basic block pointers are invalid");
1054       if (Result.get() == Type::VoidTy)
1055         return TokError("pointers to void are invalid; use i8* instead");
1056       unsigned AddrSpace;
1057       if (ParseOptionalAddrSpace(AddrSpace) ||
1058           ParseToken(lltok::star, "expected '*' in address space"))
1059         return true;
1060
1061       Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1062       break;
1063     }
1064         
1065     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1066     case lltok::lparen:
1067       if (ParseFunctionType(Result))
1068         return true;
1069       break;
1070     }
1071   }
1072 }
1073
1074 /// ParseParameterList
1075 ///    ::= '(' ')'
1076 ///    ::= '(' Arg (',' Arg)* ')'
1077 ///  Arg
1078 ///    ::= Type OptionalAttributes Value OptionalAttributes
1079 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1080                                   PerFunctionState &PFS) {
1081   if (ParseToken(lltok::lparen, "expected '(' in call"))
1082     return true;
1083   
1084   while (Lex.getKind() != lltok::rparen) {
1085     // If this isn't the first argument, we need a comma.
1086     if (!ArgList.empty() &&
1087         ParseToken(lltok::comma, "expected ',' in argument list"))
1088       return true;
1089     
1090     // Parse the argument.
1091     LocTy ArgLoc;
1092     PATypeHolder ArgTy(Type::VoidTy);
1093     unsigned ArgAttrs1, ArgAttrs2;
1094     Value *V;
1095     if (ParseType(ArgTy, ArgLoc) ||
1096         ParseOptionalAttrs(ArgAttrs1, 0) ||
1097         ParseValue(ArgTy, V, PFS) ||
1098         // FIXME: Should not allow attributes after the argument, remove this in
1099         // LLVM 3.0.
1100         ParseOptionalAttrs(ArgAttrs2, 3))
1101       return true;
1102     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1103   }
1104
1105   Lex.Lex();  // Lex the ')'.
1106   return false;
1107 }
1108
1109
1110
1111 /// ParseArgumentList - Parse the argument list for a function type or function
1112 /// prototype.  If 'inType' is true then we are parsing a FunctionType.
1113 ///   ::= '(' ArgTypeListI ')'
1114 /// ArgTypeListI
1115 ///   ::= /*empty*/
1116 ///   ::= '...'
1117 ///   ::= ArgTypeList ',' '...'
1118 ///   ::= ArgType (',' ArgType)*
1119 ///
1120 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1121                                  bool &isVarArg, bool inType) {
1122   isVarArg = false;
1123   assert(Lex.getKind() == lltok::lparen);
1124   Lex.Lex(); // eat the (.
1125   
1126   if (Lex.getKind() == lltok::rparen) {
1127     // empty
1128   } else if (Lex.getKind() == lltok::dotdotdot) {
1129     isVarArg = true;
1130     Lex.Lex();
1131   } else {
1132     LocTy TypeLoc = Lex.getLoc();
1133     PATypeHolder ArgTy(Type::VoidTy);
1134     unsigned Attrs;
1135     std::string Name;
1136     
1137     // If we're parsing a type, use ParseTypeRec, because we allow recursive
1138     // types (such as a function returning a pointer to itself).  If parsing a
1139     // function prototype, we require fully resolved types.
1140     if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1141         ParseOptionalAttrs(Attrs, 0)) return true;
1142     
1143     if (ArgTy == Type::VoidTy)
1144       return Error(TypeLoc, "argument can not have void type");
1145     
1146     if (Lex.getKind() == lltok::LocalVar ||
1147         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1148       Name = Lex.getStrVal();
1149       Lex.Lex();
1150     }
1151
1152     if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1153       return Error(TypeLoc, "invalid type for function argument");
1154     
1155     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1156     
1157     while (EatIfPresent(lltok::comma)) {
1158       // Handle ... at end of arg list.
1159       if (EatIfPresent(lltok::dotdotdot)) {
1160         isVarArg = true;
1161         break;
1162       }
1163       
1164       // Otherwise must be an argument type.
1165       TypeLoc = Lex.getLoc();
1166       if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1167           ParseOptionalAttrs(Attrs, 0)) return true;
1168
1169       if (ArgTy == Type::VoidTy)
1170         return Error(TypeLoc, "argument can not have void type");
1171
1172       if (Lex.getKind() == lltok::LocalVar ||
1173           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1174         Name = Lex.getStrVal();
1175         Lex.Lex();
1176       } else {
1177         Name = "";
1178       }
1179
1180       if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1181         return Error(TypeLoc, "invalid type for function argument");
1182       
1183       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1184     }
1185   }
1186   
1187   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1188 }
1189   
1190 /// ParseFunctionType
1191 ///  ::= Type ArgumentList OptionalAttrs
1192 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1193   assert(Lex.getKind() == lltok::lparen);
1194
1195   if (!FunctionType::isValidReturnType(Result))
1196     return TokError("invalid function return type");
1197   
1198   std::vector<ArgInfo> ArgList;
1199   bool isVarArg;
1200   unsigned Attrs;
1201   if (ParseArgumentList(ArgList, isVarArg, true) ||
1202       // FIXME: Allow, but ignore attributes on function types!
1203       // FIXME: Remove in LLVM 3.0
1204       ParseOptionalAttrs(Attrs, 2))
1205     return true;
1206   
1207   // Reject names on the arguments lists.
1208   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1209     if (!ArgList[i].Name.empty())
1210       return Error(ArgList[i].Loc, "argument name invalid in function type");
1211     if (!ArgList[i].Attrs != 0) {
1212       // Allow but ignore attributes on function types; this permits
1213       // auto-upgrade.
1214       // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1215     }
1216   }
1217   
1218   std::vector<const Type*> ArgListTy;
1219   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1220     ArgListTy.push_back(ArgList[i].Type);
1221     
1222   Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1223   return false;
1224 }
1225
1226 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1227 ///   TypeRec
1228 ///     ::= '{' '}'
1229 ///     ::= '{' TypeRec (',' TypeRec)* '}'
1230 ///     ::= '<' '{' '}' '>'
1231 ///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1232 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1233   assert(Lex.getKind() == lltok::lbrace);
1234   Lex.Lex(); // Consume the '{'
1235   
1236   if (EatIfPresent(lltok::rbrace)) {
1237     Result = StructType::get(std::vector<const Type*>(), Packed);
1238     return false;
1239   }
1240
1241   std::vector<PATypeHolder> ParamsList;
1242   LocTy EltTyLoc = Lex.getLoc();
1243   if (ParseTypeRec(Result)) return true;
1244   ParamsList.push_back(Result);
1245   
1246   if (Result == Type::VoidTy)
1247     return Error(EltTyLoc, "struct element can not have void type");
1248   
1249   while (EatIfPresent(lltok::comma)) {
1250     EltTyLoc = Lex.getLoc();
1251     if (ParseTypeRec(Result)) return true;
1252     
1253     if (Result == Type::VoidTy)
1254       return Error(EltTyLoc, "struct element can not have void type");
1255     
1256     ParamsList.push_back(Result);
1257   }
1258   
1259   if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1260     return true;
1261   
1262   std::vector<const Type*> ParamsListTy;
1263   for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1264     ParamsListTy.push_back(ParamsList[i].get());
1265   Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1266   return false;
1267 }
1268
1269 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1270 /// token has already been consumed.
1271 ///   TypeRec 
1272 ///     ::= '[' APSINTVAL 'x' Types ']'
1273 ///     ::= '<' APSINTVAL 'x' Types '>'
1274 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1275   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1276       Lex.getAPSIntVal().getBitWidth() > 64)
1277     return TokError("expected number in address space");
1278   
1279   LocTy SizeLoc = Lex.getLoc();
1280   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1281   Lex.Lex();
1282       
1283   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1284       return true;
1285
1286   LocTy TypeLoc = Lex.getLoc();
1287   PATypeHolder EltTy(Type::VoidTy);
1288   if (ParseTypeRec(EltTy)) return true;
1289   
1290   if (EltTy == Type::VoidTy)
1291     return Error(TypeLoc, "array and vector element type cannot be void");
1292
1293   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1294                  "expected end of sequential type"))
1295     return true;
1296   
1297   if (isVector) {
1298     if (Size == 0)
1299       return Error(SizeLoc, "zero element vector is illegal");
1300     if ((unsigned)Size != Size)
1301       return Error(SizeLoc, "size too large for vector");
1302     if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1303       return Error(TypeLoc, "vector element type must be fp or integer");
1304     Result = VectorType::get(EltTy, unsigned(Size));
1305   } else {
1306     if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1307       return Error(TypeLoc, "invalid array element type");
1308     Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1309   }
1310   return false;
1311 }
1312
1313 //===----------------------------------------------------------------------===//
1314 // Function Semantic Analysis.
1315 //===----------------------------------------------------------------------===//
1316
1317 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1318   : P(p), F(f) {
1319
1320   // Insert unnamed arguments into the NumberedVals list.
1321   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1322        AI != E; ++AI)
1323     if (!AI->hasName())
1324       NumberedVals.push_back(AI);
1325 }
1326
1327 LLParser::PerFunctionState::~PerFunctionState() {
1328   // If there were any forward referenced non-basicblock values, delete them.
1329   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1330        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1331     if (!isa<BasicBlock>(I->second.first)) {
1332       I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1333                                                           ->getType()));
1334       delete I->second.first;
1335       I->second.first = 0;
1336     }
1337   
1338   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1339        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1340     if (!isa<BasicBlock>(I->second.first)) {
1341       I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1342                                                           ->getType()));
1343       delete I->second.first;
1344       I->second.first = 0;
1345     }
1346 }
1347
1348 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1349   if (!ForwardRefVals.empty())
1350     return P.Error(ForwardRefVals.begin()->second.second,
1351                    "use of undefined value '%" + ForwardRefVals.begin()->first +
1352                    "'");
1353   if (!ForwardRefValIDs.empty())
1354     return P.Error(ForwardRefValIDs.begin()->second.second,
1355                    "use of undefined value '%" +
1356                    utostr(ForwardRefValIDs.begin()->first) + "'");
1357   return false;
1358 }
1359
1360
1361 /// GetVal - Get a value with the specified name or ID, creating a
1362 /// forward reference record if needed.  This can return null if the value
1363 /// exists but does not have the right type.
1364 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1365                                           const Type *Ty, LocTy Loc) {
1366   // Look this name up in the normal function symbol table.
1367   Value *Val = F.getValueSymbolTable().lookup(Name);
1368   
1369   // If this is a forward reference for the value, see if we already created a
1370   // forward ref record.
1371   if (Val == 0) {
1372     std::map<std::string, std::pair<Value*, LocTy> >::iterator
1373       I = ForwardRefVals.find(Name);
1374     if (I != ForwardRefVals.end())
1375       Val = I->second.first;
1376   }
1377     
1378   // If we have the value in the symbol table or fwd-ref table, return it.
1379   if (Val) {
1380     if (Val->getType() == Ty) return Val;
1381     if (Ty == Type::LabelTy)
1382       P.Error(Loc, "'%" + Name + "' is not a basic block");
1383     else
1384       P.Error(Loc, "'%" + Name + "' defined with type '" +
1385               Val->getType()->getDescription() + "'");
1386     return 0;
1387   }
1388   
1389   // Don't make placeholders with invalid type.
1390   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1391     P.Error(Loc, "invalid use of a non-first-class type");
1392     return 0;
1393   }
1394   
1395   // Otherwise, create a new forward reference for this value and remember it.
1396   Value *FwdVal;
1397   if (Ty == Type::LabelTy) 
1398     FwdVal = BasicBlock::Create(Name, &F);
1399   else
1400     FwdVal = new Argument(Ty, Name);
1401   
1402   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1403   return FwdVal;
1404 }
1405
1406 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1407                                           LocTy Loc) {
1408   // Look this name up in the normal function symbol table.
1409   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1410   
1411   // If this is a forward reference for the value, see if we already created a
1412   // forward ref record.
1413   if (Val == 0) {
1414     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1415       I = ForwardRefValIDs.find(ID);
1416     if (I != ForwardRefValIDs.end())
1417       Val = I->second.first;
1418   }
1419   
1420   // If we have the value in the symbol table or fwd-ref table, return it.
1421   if (Val) {
1422     if (Val->getType() == Ty) return Val;
1423     if (Ty == Type::LabelTy)
1424       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1425     else
1426       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1427               Val->getType()->getDescription() + "'");
1428     return 0;
1429   }
1430   
1431   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1432     P.Error(Loc, "invalid use of a non-first-class type");
1433     return 0;
1434   }
1435   
1436   // Otherwise, create a new forward reference for this value and remember it.
1437   Value *FwdVal;
1438   if (Ty == Type::LabelTy) 
1439     FwdVal = BasicBlock::Create("", &F);
1440   else
1441     FwdVal = new Argument(Ty);
1442   
1443   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1444   return FwdVal;
1445 }
1446
1447 /// SetInstName - After an instruction is parsed and inserted into its
1448 /// basic block, this installs its name.
1449 bool LLParser::PerFunctionState::SetInstName(int NameID,
1450                                              const std::string &NameStr,
1451                                              LocTy NameLoc, Instruction *Inst) {
1452   // If this instruction has void type, it cannot have a name or ID specified.
1453   if (Inst->getType() == Type::VoidTy) {
1454     if (NameID != -1 || !NameStr.empty())
1455       return P.Error(NameLoc, "instructions returning void cannot have a name");
1456     return false;
1457   }
1458   
1459   // If this was a numbered instruction, verify that the instruction is the
1460   // expected value and resolve any forward references.
1461   if (NameStr.empty()) {
1462     // If neither a name nor an ID was specified, just use the next ID.
1463     if (NameID == -1)
1464       NameID = NumberedVals.size();
1465     
1466     if (unsigned(NameID) != NumberedVals.size())
1467       return P.Error(NameLoc, "instruction expected to be numbered '%" +
1468                      utostr(NumberedVals.size()) + "'");
1469     
1470     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1471       ForwardRefValIDs.find(NameID);
1472     if (FI != ForwardRefValIDs.end()) {
1473       if (FI->second.first->getType() != Inst->getType())
1474         return P.Error(NameLoc, "instruction forward referenced with type '" + 
1475                        FI->second.first->getType()->getDescription() + "'");
1476       FI->second.first->replaceAllUsesWith(Inst);
1477       ForwardRefValIDs.erase(FI);
1478     }
1479
1480     NumberedVals.push_back(Inst);
1481     return false;
1482   }
1483
1484   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1485   std::map<std::string, std::pair<Value*, LocTy> >::iterator
1486     FI = ForwardRefVals.find(NameStr);
1487   if (FI != ForwardRefVals.end()) {
1488     if (FI->second.first->getType() != Inst->getType())
1489       return P.Error(NameLoc, "instruction forward referenced with type '" + 
1490                      FI->second.first->getType()->getDescription() + "'");
1491     FI->second.first->replaceAllUsesWith(Inst);
1492     ForwardRefVals.erase(FI);
1493   }
1494   
1495   // Set the name on the instruction.
1496   Inst->setName(NameStr);
1497   
1498   if (Inst->getNameStr() != NameStr)
1499     return P.Error(NameLoc, "multiple definition of local value named '" + 
1500                    NameStr + "'");
1501   return false;
1502 }
1503
1504 /// GetBB - Get a basic block with the specified name or ID, creating a
1505 /// forward reference record if needed.
1506 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1507                                               LocTy Loc) {
1508   return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1509 }
1510
1511 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1512   return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1513 }
1514
1515 /// DefineBB - Define the specified basic block, which is either named or
1516 /// unnamed.  If there is an error, this returns null otherwise it returns
1517 /// the block being defined.
1518 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1519                                                  LocTy Loc) {
1520   BasicBlock *BB;
1521   if (Name.empty())
1522     BB = GetBB(NumberedVals.size(), Loc);
1523   else
1524     BB = GetBB(Name, Loc);
1525   if (BB == 0) return 0; // Already diagnosed error.
1526   
1527   // Move the block to the end of the function.  Forward ref'd blocks are
1528   // inserted wherever they happen to be referenced.
1529   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1530   
1531   // Remove the block from forward ref sets.
1532   if (Name.empty()) {
1533     ForwardRefValIDs.erase(NumberedVals.size());
1534     NumberedVals.push_back(BB);
1535   } else {
1536     // BB forward references are already in the function symbol table.
1537     ForwardRefVals.erase(Name);
1538   }
1539   
1540   return BB;
1541 }
1542
1543 //===----------------------------------------------------------------------===//
1544 // Constants.
1545 //===----------------------------------------------------------------------===//
1546
1547 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1548 /// type implied.  For example, if we parse "4" we don't know what integer type
1549 /// it has.  The value will later be combined with its type and checked for
1550 /// sanity.
1551 bool LLParser::ParseValID(ValID &ID) {
1552   ID.Loc = Lex.getLoc();
1553   switch (Lex.getKind()) {
1554   default: return TokError("expected value token");
1555   case lltok::GlobalID:  // @42
1556     ID.UIntVal = Lex.getUIntVal();
1557     ID.Kind = ValID::t_GlobalID;
1558     break;
1559   case lltok::GlobalVar:  // @foo
1560     ID.StrVal = Lex.getStrVal();
1561     ID.Kind = ValID::t_GlobalName;
1562     break;
1563   case lltok::LocalVarID:  // %42
1564     ID.UIntVal = Lex.getUIntVal();
1565     ID.Kind = ValID::t_LocalID;
1566     break;
1567   case lltok::LocalVar:  // %foo
1568   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1569     ID.StrVal = Lex.getStrVal();
1570     ID.Kind = ValID::t_LocalName;
1571     break;
1572   case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1573     ID.Kind = ValID::t_Constant;
1574     Lex.Lex();
1575     if (Lex.getKind() == lltok::lbrace) {
1576       SmallVector<Value*, 16> Elts;
1577       if (ParseMDNodeVector(Elts) ||
1578           ParseToken(lltok::rbrace, "expected end of metadata node"))
1579         return true;
1580
1581       ID.ConstantVal = MDNode::get(Elts.data(), Elts.size());
1582       return false;
1583     }
1584
1585     // MDString:
1586     //   ::= '!' STRINGCONSTANT
1587     std::string Str;
1588     if (ParseStringConstant(Str)) return true;
1589
1590     ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1591     return false;
1592   }
1593   case lltok::APSInt:
1594     ID.APSIntVal = Lex.getAPSIntVal(); 
1595     ID.Kind = ValID::t_APSInt;
1596     break;
1597   case lltok::APFloat:
1598     ID.APFloatVal = Lex.getAPFloatVal();
1599     ID.Kind = ValID::t_APFloat;
1600     break;
1601   case lltok::kw_true:
1602     ID.ConstantVal = ConstantInt::getTrue();
1603     ID.Kind = ValID::t_Constant;
1604     break;
1605   case lltok::kw_false:
1606     ID.ConstantVal = ConstantInt::getFalse();
1607     ID.Kind = ValID::t_Constant;
1608     break;
1609   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1610   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1611   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1612       
1613   case lltok::lbrace: {
1614     // ValID ::= '{' ConstVector '}'
1615     Lex.Lex();
1616     SmallVector<Constant*, 16> Elts;
1617     if (ParseGlobalValueVector(Elts) ||
1618         ParseToken(lltok::rbrace, "expected end of struct constant"))
1619       return true;
1620     
1621     ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
1622     ID.Kind = ValID::t_Constant;
1623     return false;
1624   }
1625   case lltok::less: {
1626     // ValID ::= '<' ConstVector '>'         --> Vector.
1627     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1628     Lex.Lex();
1629     bool isPackedStruct = EatIfPresent(lltok::lbrace);
1630     
1631     SmallVector<Constant*, 16> Elts;
1632     LocTy FirstEltLoc = Lex.getLoc();
1633     if (ParseGlobalValueVector(Elts) ||
1634         (isPackedStruct &&
1635          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1636         ParseToken(lltok::greater, "expected end of constant"))
1637       return true;
1638     
1639     if (isPackedStruct) {
1640       ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), true);
1641       ID.Kind = ValID::t_Constant;
1642       return false;
1643     }
1644     
1645     if (Elts.empty())
1646       return Error(ID.Loc, "constant vector must not be empty");
1647
1648     if (!Elts[0]->getType()->isInteger() &&
1649         !Elts[0]->getType()->isFloatingPoint())
1650       return Error(FirstEltLoc,
1651                    "vector elements must have integer or floating point type");
1652     
1653     // Verify that all the vector elements have the same type.
1654     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1655       if (Elts[i]->getType() != Elts[0]->getType())
1656         return Error(FirstEltLoc,
1657                      "vector element #" + utostr(i) +
1658                     " is not of type '" + Elts[0]->getType()->getDescription());
1659     
1660     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1661     ID.Kind = ValID::t_Constant;
1662     return false;
1663   }
1664   case lltok::lsquare: {   // Array Constant
1665     Lex.Lex();
1666     SmallVector<Constant*, 16> Elts;
1667     LocTy FirstEltLoc = Lex.getLoc();
1668     if (ParseGlobalValueVector(Elts) ||
1669         ParseToken(lltok::rsquare, "expected end of array constant"))
1670       return true;
1671
1672     // Handle empty element.
1673     if (Elts.empty()) {
1674       // Use undef instead of an array because it's inconvenient to determine
1675       // the element type at this point, there being no elements to examine.
1676       ID.Kind = ValID::t_EmptyArray;
1677       return false;
1678     }
1679     
1680     if (!Elts[0]->getType()->isFirstClassType())
1681       return Error(FirstEltLoc, "invalid array element type: " + 
1682                    Elts[0]->getType()->getDescription());
1683           
1684     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1685     
1686     // Verify all elements are correct type!
1687     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1688       if (Elts[i]->getType() != Elts[0]->getType())
1689         return Error(FirstEltLoc,
1690                      "array element #" + utostr(i) +
1691                      " is not of type '" +Elts[0]->getType()->getDescription());
1692     }
1693     
1694     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1695     ID.Kind = ValID::t_Constant;
1696     return false;
1697   }
1698   case lltok::kw_c:  // c "foo"
1699     Lex.Lex();
1700     ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1701     if (ParseToken(lltok::StringConstant, "expected string")) return true;
1702     ID.Kind = ValID::t_Constant;
1703     return false;
1704
1705   case lltok::kw_asm: {
1706     // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1707     bool HasSideEffect;
1708     Lex.Lex();
1709     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1710         ParseStringConstant(ID.StrVal) ||
1711         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1712         ParseToken(lltok::StringConstant, "expected constraint string"))
1713       return true;
1714     ID.StrVal2 = Lex.getStrVal();
1715     ID.UIntVal = HasSideEffect;
1716     ID.Kind = ValID::t_InlineAsm;
1717     return false;
1718   }
1719       
1720   case lltok::kw_trunc:
1721   case lltok::kw_zext:
1722   case lltok::kw_sext:
1723   case lltok::kw_fptrunc:
1724   case lltok::kw_fpext:
1725   case lltok::kw_bitcast:
1726   case lltok::kw_uitofp:
1727   case lltok::kw_sitofp:
1728   case lltok::kw_fptoui:
1729   case lltok::kw_fptosi: 
1730   case lltok::kw_inttoptr:
1731   case lltok::kw_ptrtoint: { 
1732     unsigned Opc = Lex.getUIntVal();
1733     PATypeHolder DestTy(Type::VoidTy);
1734     Constant *SrcVal;
1735     Lex.Lex();
1736     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1737         ParseGlobalTypeAndValue(SrcVal) ||
1738         ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1739         ParseType(DestTy) ||
1740         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1741       return true;
1742     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1743       return Error(ID.Loc, "invalid cast opcode for cast from '" +
1744                    SrcVal->getType()->getDescription() + "' to '" +
1745                    DestTy->getDescription() + "'");
1746     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1747                                            DestTy);
1748     ID.Kind = ValID::t_Constant;
1749     return false;
1750   }
1751   case lltok::kw_extractvalue: {
1752     Lex.Lex();
1753     Constant *Val;
1754     SmallVector<unsigned, 4> Indices;
1755     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1756         ParseGlobalTypeAndValue(Val) ||
1757         ParseIndexList(Indices) ||
1758         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1759       return true;
1760     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1761       return Error(ID.Loc, "extractvalue operand must be array or struct");
1762     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1763                                           Indices.end()))
1764       return Error(ID.Loc, "invalid indices for extractvalue");
1765     ID.ConstantVal =
1766       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
1767     ID.Kind = ValID::t_Constant;
1768     return false;
1769   }
1770   case lltok::kw_insertvalue: {
1771     Lex.Lex();
1772     Constant *Val0, *Val1;
1773     SmallVector<unsigned, 4> Indices;
1774     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1775         ParseGlobalTypeAndValue(Val0) ||
1776         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1777         ParseGlobalTypeAndValue(Val1) ||
1778         ParseIndexList(Indices) ||
1779         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1780       return true;
1781     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1782       return Error(ID.Loc, "extractvalue operand must be array or struct");
1783     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1784                                           Indices.end()))
1785       return Error(ID.Loc, "invalid indices for insertvalue");
1786     ID.ConstantVal =
1787       ConstantExpr::getInsertValue(Val0, Val1, Indices.data(), Indices.size());
1788     ID.Kind = ValID::t_Constant;
1789     return false;
1790   }
1791   case lltok::kw_icmp:
1792   case lltok::kw_fcmp:
1793   case lltok::kw_vicmp:
1794   case lltok::kw_vfcmp: {
1795     unsigned PredVal, Opc = Lex.getUIntVal();
1796     Constant *Val0, *Val1;
1797     Lex.Lex();
1798     if (ParseCmpPredicate(PredVal, Opc) ||
1799         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1800         ParseGlobalTypeAndValue(Val0) ||
1801         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1802         ParseGlobalTypeAndValue(Val1) ||
1803         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1804       return true;
1805     
1806     if (Val0->getType() != Val1->getType())
1807       return Error(ID.Loc, "compare operands must have the same type");
1808     
1809     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1810     
1811     if (Opc == Instruction::FCmp) {
1812       if (!Val0->getType()->isFPOrFPVector())
1813         return Error(ID.Loc, "fcmp requires floating point operands");
1814       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1815     } else if (Opc == Instruction::ICmp) {
1816       if (!Val0->getType()->isIntOrIntVector() &&
1817           !isa<PointerType>(Val0->getType()))
1818         return Error(ID.Loc, "icmp requires pointer or integer operands");
1819       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1820     } else if (Opc == Instruction::VFCmp) {
1821       // FIXME: REMOVE VFCMP Support
1822       if (!Val0->getType()->isFPOrFPVector() ||
1823           !isa<VectorType>(Val0->getType()))
1824         return Error(ID.Loc, "vfcmp requires vector floating point operands");
1825       ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1826     } else if (Opc == Instruction::VICmp) {
1827       // FIXME: REMOVE VICMP Support
1828       if (!Val0->getType()->isIntOrIntVector() ||
1829           !isa<VectorType>(Val0->getType()))
1830         return Error(ID.Loc, "vicmp requires vector floating point operands");
1831       ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1832     }
1833     ID.Kind = ValID::t_Constant;
1834     return false;
1835   }
1836       
1837   // Binary Operators.
1838   case lltok::kw_add:
1839   case lltok::kw_fadd:
1840   case lltok::kw_sub:
1841   case lltok::kw_fsub:
1842   case lltok::kw_mul:
1843   case lltok::kw_fmul:
1844   case lltok::kw_udiv:
1845   case lltok::kw_sdiv:
1846   case lltok::kw_fdiv:
1847   case lltok::kw_urem:
1848   case lltok::kw_srem:
1849   case lltok::kw_frem: {
1850     unsigned Opc = Lex.getUIntVal();
1851     Constant *Val0, *Val1;
1852     Lex.Lex();
1853     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1854         ParseGlobalTypeAndValue(Val0) ||
1855         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1856         ParseGlobalTypeAndValue(Val1) ||
1857         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1858       return true;
1859     if (Val0->getType() != Val1->getType())
1860       return Error(ID.Loc, "operands of constexpr must have same type");
1861     if (!Val0->getType()->isIntOrIntVector() &&
1862         !Val0->getType()->isFPOrFPVector())
1863       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1864     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1865     ID.Kind = ValID::t_Constant;
1866     return false;
1867   }
1868       
1869   // Logical Operations
1870   case lltok::kw_shl:
1871   case lltok::kw_lshr:
1872   case lltok::kw_ashr:
1873   case lltok::kw_and:
1874   case lltok::kw_or:
1875   case lltok::kw_xor: {
1876     unsigned Opc = Lex.getUIntVal();
1877     Constant *Val0, *Val1;
1878     Lex.Lex();
1879     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1880         ParseGlobalTypeAndValue(Val0) ||
1881         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1882         ParseGlobalTypeAndValue(Val1) ||
1883         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1884       return true;
1885     if (Val0->getType() != Val1->getType())
1886       return Error(ID.Loc, "operands of constexpr must have same type");
1887     if (!Val0->getType()->isIntOrIntVector())
1888       return Error(ID.Loc,
1889                    "constexpr requires integer or integer vector operands");
1890     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1891     ID.Kind = ValID::t_Constant;
1892     return false;
1893   }  
1894       
1895   case lltok::kw_getelementptr:
1896   case lltok::kw_shufflevector:
1897   case lltok::kw_insertelement:
1898   case lltok::kw_extractelement:
1899   case lltok::kw_select: {
1900     unsigned Opc = Lex.getUIntVal();
1901     SmallVector<Constant*, 16> Elts;
1902     Lex.Lex();
1903     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1904         ParseGlobalValueVector(Elts) ||
1905         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1906       return true;
1907     
1908     if (Opc == Instruction::GetElementPtr) {
1909       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1910         return Error(ID.Loc, "getelementptr requires pointer operand");
1911       
1912       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1913                                              (Value**)&Elts[1], Elts.size()-1))
1914         return Error(ID.Loc, "invalid indices for getelementptr");
1915       ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1916                                                       &Elts[1], Elts.size()-1);
1917     } else if (Opc == Instruction::Select) {
1918       if (Elts.size() != 3)
1919         return Error(ID.Loc, "expected three operands to select");
1920       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1921                                                               Elts[2]))
1922         return Error(ID.Loc, Reason);
1923       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1924     } else if (Opc == Instruction::ShuffleVector) {
1925       if (Elts.size() != 3)
1926         return Error(ID.Loc, "expected three operands to shufflevector");
1927       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1928         return Error(ID.Loc, "invalid operands to shufflevector");
1929       ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1930     } else if (Opc == Instruction::ExtractElement) {
1931       if (Elts.size() != 2)
1932         return Error(ID.Loc, "expected two operands to extractelement");
1933       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1934         return Error(ID.Loc, "invalid extractelement operands");
1935       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1936     } else {
1937       assert(Opc == Instruction::InsertElement && "Unknown opcode");
1938       if (Elts.size() != 3)
1939       return Error(ID.Loc, "expected three operands to insertelement");
1940       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1941         return Error(ID.Loc, "invalid insertelement operands");
1942       ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1943     }
1944     
1945     ID.Kind = ValID::t_Constant;
1946     return false;
1947   }
1948   }
1949   
1950   Lex.Lex();
1951   return false;
1952 }
1953
1954 /// ParseGlobalValue - Parse a global value with the specified type.
1955 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1956   V = 0;
1957   ValID ID;
1958   return ParseValID(ID) ||
1959          ConvertGlobalValIDToValue(Ty, ID, V);
1960 }
1961
1962 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1963 /// constant.
1964 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1965                                          Constant *&V) {
1966   if (isa<FunctionType>(Ty))
1967     return Error(ID.Loc, "functions are not values, refer to them as pointers");
1968   
1969   switch (ID.Kind) {
1970   default: assert(0 && "Unknown ValID!");
1971   case ValID::t_LocalID:
1972   case ValID::t_LocalName:
1973     return Error(ID.Loc, "invalid use of function-local name");
1974   case ValID::t_InlineAsm:
1975     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1976   case ValID::t_GlobalName:
1977     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1978     return V == 0;
1979   case ValID::t_GlobalID:
1980     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1981     return V == 0;
1982   case ValID::t_APSInt:
1983     if (!isa<IntegerType>(Ty))
1984       return Error(ID.Loc, "integer constant must have integer type");
1985     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1986     V = ConstantInt::get(ID.APSIntVal);
1987     return false;
1988   case ValID::t_APFloat:
1989     if (!Ty->isFloatingPoint() ||
1990         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1991       return Error(ID.Loc, "floating point constant invalid for type");
1992       
1993     // The lexer has no type info, so builds all float and double FP constants
1994     // as double.  Fix this here.  Long double does not need this.
1995     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1996         Ty == Type::FloatTy) {
1997       bool Ignored;
1998       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1999                             &Ignored);
2000     }
2001     V = ConstantFP::get(ID.APFloatVal);
2002       
2003     if (V->getType() != Ty)
2004       return Error(ID.Loc, "floating point constant does not have type '" +
2005                    Ty->getDescription() + "'");
2006       
2007     return false;
2008   case ValID::t_Null:
2009     if (!isa<PointerType>(Ty))
2010       return Error(ID.Loc, "null must be a pointer type");
2011     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2012     return false;
2013   case ValID::t_Undef:
2014     // FIXME: LabelTy should not be a first-class type.
2015     if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2016         !isa<OpaqueType>(Ty))
2017       return Error(ID.Loc, "invalid type for undef constant");
2018     V = UndefValue::get(Ty);
2019     return false;
2020   case ValID::t_EmptyArray:
2021     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2022       return Error(ID.Loc, "invalid empty array initializer");
2023     V = UndefValue::get(Ty);
2024     return false;
2025   case ValID::t_Zero:
2026     // FIXME: LabelTy should not be a first-class type.
2027     if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2028       return Error(ID.Loc, "invalid type for null constant");
2029     V = Constant::getNullValue(Ty);
2030     return false;
2031   case ValID::t_Constant:
2032     if (ID.ConstantVal->getType() != Ty)
2033       return Error(ID.Loc, "constant expression type mismatch");
2034     V = ID.ConstantVal;
2035     return false;
2036   }
2037 }
2038   
2039 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2040   PATypeHolder Type(Type::VoidTy);
2041   return ParseType(Type) ||
2042          ParseGlobalValue(Type, V);
2043 }    
2044
2045 /// ParseGlobalValueVector
2046 ///   ::= /*empty*/
2047 ///   ::= TypeAndValue (',' TypeAndValue)*
2048 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2049   // Empty list.
2050   if (Lex.getKind() == lltok::rbrace ||
2051       Lex.getKind() == lltok::rsquare ||
2052       Lex.getKind() == lltok::greater ||
2053       Lex.getKind() == lltok::rparen)
2054     return false;
2055   
2056   Constant *C;
2057   if (ParseGlobalTypeAndValue(C)) return true;
2058   Elts.push_back(C);
2059   
2060   while (EatIfPresent(lltok::comma)) {
2061     if (ParseGlobalTypeAndValue(C)) return true;
2062     Elts.push_back(C);
2063   }
2064   
2065   return false;
2066 }
2067
2068
2069 //===----------------------------------------------------------------------===//
2070 // Function Parsing.
2071 //===----------------------------------------------------------------------===//
2072
2073 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2074                                    PerFunctionState &PFS) {
2075   if (ID.Kind == ValID::t_LocalID)
2076     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2077   else if (ID.Kind == ValID::t_LocalName)
2078     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2079   else if (ID.Kind == ValID::t_InlineAsm) {
2080     const PointerType *PTy = dyn_cast<PointerType>(Ty);
2081     const FunctionType *FTy =
2082       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2083     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2084       return Error(ID.Loc, "invalid type for inline asm constraint string");
2085     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2086     return false;
2087   } else {
2088     Constant *C;
2089     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2090     V = C;
2091     return false;
2092   }
2093
2094   return V == 0;
2095 }
2096
2097 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2098   V = 0;
2099   ValID ID;
2100   return ParseValID(ID) ||
2101          ConvertValIDToValue(Ty, ID, V, PFS);
2102 }
2103
2104 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2105   PATypeHolder T(Type::VoidTy);
2106   return ParseType(T) ||
2107          ParseValue(T, V, PFS);
2108 }
2109
2110 /// FunctionHeader
2111 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2112 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2113 ///       OptionalAlign OptGC
2114 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2115   // Parse the linkage.
2116   LocTy LinkageLoc = Lex.getLoc();
2117   unsigned Linkage;
2118   
2119   unsigned Visibility, CC, RetAttrs;
2120   PATypeHolder RetType(Type::VoidTy);
2121   LocTy RetTypeLoc = Lex.getLoc();
2122   if (ParseOptionalLinkage(Linkage) ||
2123       ParseOptionalVisibility(Visibility) ||
2124       ParseOptionalCallingConv(CC) ||
2125       ParseOptionalAttrs(RetAttrs, 1) ||
2126       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2127     return true;
2128
2129   // Verify that the linkage is ok.
2130   switch ((GlobalValue::LinkageTypes)Linkage) {
2131   case GlobalValue::ExternalLinkage:
2132     break; // always ok.
2133   case GlobalValue::DLLImportLinkage:
2134   case GlobalValue::ExternalWeakLinkage:
2135     if (isDefine)
2136       return Error(LinkageLoc, "invalid linkage for function definition");
2137     break;
2138   case GlobalValue::PrivateLinkage:
2139   case GlobalValue::InternalLinkage:
2140   case GlobalValue::AvailableExternallyLinkage:
2141   case GlobalValue::LinkOnceAnyLinkage:
2142   case GlobalValue::LinkOnceODRLinkage:
2143   case GlobalValue::WeakAnyLinkage:
2144   case GlobalValue::WeakODRLinkage:
2145   case GlobalValue::DLLExportLinkage:
2146     if (!isDefine)
2147       return Error(LinkageLoc, "invalid linkage for function declaration");
2148     break;
2149   case GlobalValue::AppendingLinkage:
2150   case GlobalValue::GhostLinkage:
2151   case GlobalValue::CommonLinkage:
2152     return Error(LinkageLoc, "invalid function linkage type");
2153   }
2154   
2155   if (!FunctionType::isValidReturnType(RetType) ||
2156       isa<OpaqueType>(RetType))
2157     return Error(RetTypeLoc, "invalid function return type");
2158   
2159   LocTy NameLoc = Lex.getLoc();
2160
2161   std::string FunctionName;
2162   if (Lex.getKind() == lltok::GlobalVar) {
2163     FunctionName = Lex.getStrVal();
2164   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2165     unsigned NameID = Lex.getUIntVal();
2166
2167     if (NameID != NumberedVals.size())
2168       return TokError("function expected to be numbered '%" +
2169                       utostr(NumberedVals.size()) + "'");
2170   } else {
2171     return TokError("expected function name");
2172   }
2173   
2174   Lex.Lex();
2175   
2176   if (Lex.getKind() != lltok::lparen)
2177     return TokError("expected '(' in function argument list");
2178   
2179   std::vector<ArgInfo> ArgList;
2180   bool isVarArg;
2181   unsigned FuncAttrs;
2182   std::string Section;
2183   unsigned Alignment;
2184   std::string GC;
2185
2186   if (ParseArgumentList(ArgList, isVarArg, false) ||
2187       ParseOptionalAttrs(FuncAttrs, 2) ||
2188       (EatIfPresent(lltok::kw_section) &&
2189        ParseStringConstant(Section)) ||
2190       ParseOptionalAlignment(Alignment) ||
2191       (EatIfPresent(lltok::kw_gc) &&
2192        ParseStringConstant(GC)))
2193     return true;
2194
2195   // If the alignment was parsed as an attribute, move to the alignment field.
2196   if (FuncAttrs & Attribute::Alignment) {
2197     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2198     FuncAttrs &= ~Attribute::Alignment;
2199   }
2200   
2201   // Okay, if we got here, the function is syntactically valid.  Convert types
2202   // and do semantic checks.
2203   std::vector<const Type*> ParamTypeList;
2204   SmallVector<AttributeWithIndex, 8> Attrs;
2205   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
2206   // attributes.
2207   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2208   if (FuncAttrs & ObsoleteFuncAttrs) {
2209     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2210     FuncAttrs &= ~ObsoleteFuncAttrs;
2211   }
2212   
2213   if (RetAttrs != Attribute::None)
2214     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2215   
2216   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2217     ParamTypeList.push_back(ArgList[i].Type);
2218     if (ArgList[i].Attrs != Attribute::None)
2219       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2220   }
2221
2222   if (FuncAttrs != Attribute::None)
2223     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2224
2225   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2226   
2227   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2228       RetType != Type::VoidTy)
2229     return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 
2230   
2231   const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2232   const PointerType *PFT = PointerType::getUnqual(FT);
2233
2234   Fn = 0;
2235   if (!FunctionName.empty()) {
2236     // If this was a definition of a forward reference, remove the definition
2237     // from the forward reference table and fill in the forward ref.
2238     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2239       ForwardRefVals.find(FunctionName);
2240     if (FRVI != ForwardRefVals.end()) {
2241       Fn = M->getFunction(FunctionName);
2242       ForwardRefVals.erase(FRVI);
2243     } else if ((Fn = M->getFunction(FunctionName))) {
2244       // If this function already exists in the symbol table, then it is
2245       // multiply defined.  We accept a few cases for old backwards compat.
2246       // FIXME: Remove this stuff for LLVM 3.0.
2247       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2248           (!Fn->isDeclaration() && isDefine)) {
2249         // If the redefinition has different type or different attributes,
2250         // reject it.  If both have bodies, reject it.
2251         return Error(NameLoc, "invalid redefinition of function '" +
2252                      FunctionName + "'");
2253       } else if (Fn->isDeclaration()) {
2254         // Make sure to strip off any argument names so we can't get conflicts.
2255         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2256              AI != AE; ++AI)
2257           AI->setName("");
2258       }
2259     }
2260     
2261   } else if (FunctionName.empty()) {
2262     // If this is a definition of a forward referenced function, make sure the
2263     // types agree.
2264     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2265       = ForwardRefValIDs.find(NumberedVals.size());
2266     if (I != ForwardRefValIDs.end()) {
2267       Fn = cast<Function>(I->second.first);
2268       if (Fn->getType() != PFT)
2269         return Error(NameLoc, "type of definition and forward reference of '@" +
2270                      utostr(NumberedVals.size()) +"' disagree");
2271       ForwardRefValIDs.erase(I);
2272     }
2273   }
2274
2275   if (Fn == 0)
2276     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2277   else // Move the forward-reference to the correct spot in the module.
2278     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2279
2280   if (FunctionName.empty())
2281     NumberedVals.push_back(Fn);
2282   
2283   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2284   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2285   Fn->setCallingConv(CC);
2286   Fn->setAttributes(PAL);
2287   Fn->setAlignment(Alignment);
2288   Fn->setSection(Section);
2289   if (!GC.empty()) Fn->setGC(GC.c_str());
2290     
2291   // Add all of the arguments we parsed to the function.
2292   Function::arg_iterator ArgIt = Fn->arg_begin();
2293   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2294     // If the argument has a name, insert it into the argument symbol table.
2295     if (ArgList[i].Name.empty()) continue;
2296     
2297     // Set the name, if it conflicted, it will be auto-renamed.
2298     ArgIt->setName(ArgList[i].Name);
2299     
2300     if (ArgIt->getNameStr() != ArgList[i].Name)
2301       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2302                    ArgList[i].Name + "'");
2303   }
2304   
2305   return false;
2306 }
2307
2308
2309 /// ParseFunctionBody
2310 ///   ::= '{' BasicBlock+ '}'
2311 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2312 ///
2313 bool LLParser::ParseFunctionBody(Function &Fn) {
2314   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2315     return TokError("expected '{' in function body");
2316   Lex.Lex();  // eat the {.
2317   
2318   PerFunctionState PFS(*this, Fn);
2319   
2320   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2321     if (ParseBasicBlock(PFS)) return true;
2322   
2323   // Eat the }.
2324   Lex.Lex();
2325   
2326   // Verify function is ok.
2327   return PFS.VerifyFunctionComplete();
2328 }
2329
2330 /// ParseBasicBlock
2331 ///   ::= LabelStr? Instruction*
2332 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2333   // If this basic block starts out with a name, remember it.
2334   std::string Name;
2335   LocTy NameLoc = Lex.getLoc();
2336   if (Lex.getKind() == lltok::LabelStr) {
2337     Name = Lex.getStrVal();
2338     Lex.Lex();
2339   }
2340   
2341   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2342   if (BB == 0) return true;
2343   
2344   std::string NameStr;
2345   
2346   // Parse the instructions in this block until we get a terminator.
2347   Instruction *Inst;
2348   do {
2349     // This instruction may have three possibilities for a name: a) none
2350     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2351     LocTy NameLoc = Lex.getLoc();
2352     int NameID = -1;
2353     NameStr = "";
2354     
2355     if (Lex.getKind() == lltok::LocalVarID) {
2356       NameID = Lex.getUIntVal();
2357       Lex.Lex();
2358       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2359         return true;
2360     } else if (Lex.getKind() == lltok::LocalVar ||
2361                // FIXME: REMOVE IN LLVM 3.0
2362                Lex.getKind() == lltok::StringConstant) {
2363       NameStr = Lex.getStrVal();
2364       Lex.Lex();
2365       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2366         return true;
2367     }
2368     
2369     if (ParseInstruction(Inst, BB, PFS)) return true;
2370     
2371     BB->getInstList().push_back(Inst);
2372
2373     // Set the name on the instruction.
2374     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2375   } while (!isa<TerminatorInst>(Inst));
2376   
2377   return false;
2378 }
2379
2380 //===----------------------------------------------------------------------===//
2381 // Instruction Parsing.
2382 //===----------------------------------------------------------------------===//
2383
2384 /// ParseInstruction - Parse one of the many different instructions.
2385 ///
2386 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2387                                 PerFunctionState &PFS) {
2388   lltok::Kind Token = Lex.getKind();
2389   if (Token == lltok::Eof)
2390     return TokError("found end of file when expecting more instructions");
2391   LocTy Loc = Lex.getLoc();
2392   unsigned KeywordVal = Lex.getUIntVal();
2393   Lex.Lex();  // Eat the keyword.
2394   
2395   switch (Token) {
2396   default:                    return Error(Loc, "expected instruction opcode");
2397   // Terminator Instructions.
2398   case lltok::kw_unwind:      Inst = new UnwindInst(); return false;
2399   case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2400   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2401   case lltok::kw_br:          return ParseBr(Inst, PFS);
2402   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2403   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2404   // Binary Operators.
2405   case lltok::kw_add:
2406   case lltok::kw_sub:
2407   case lltok::kw_mul:
2408     // API compatibility: Accept either integer or floating-point types.
2409     return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2410   case lltok::kw_fadd:
2411   case lltok::kw_fsub:
2412   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2413
2414   case lltok::kw_udiv:
2415   case lltok::kw_sdiv:
2416   case lltok::kw_urem:
2417   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2418   case lltok::kw_fdiv:
2419   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2420   case lltok::kw_shl:
2421   case lltok::kw_lshr:
2422   case lltok::kw_ashr:
2423   case lltok::kw_and:
2424   case lltok::kw_or:
2425   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2426   case lltok::kw_icmp:
2427   case lltok::kw_fcmp:
2428   case lltok::kw_vicmp:
2429   case lltok::kw_vfcmp:  return ParseCompare(Inst, PFS, KeywordVal);
2430   // Casts.
2431   case lltok::kw_trunc:
2432   case lltok::kw_zext:
2433   case lltok::kw_sext:
2434   case lltok::kw_fptrunc:
2435   case lltok::kw_fpext:
2436   case lltok::kw_bitcast:
2437   case lltok::kw_uitofp:
2438   case lltok::kw_sitofp:
2439   case lltok::kw_fptoui:
2440   case lltok::kw_fptosi: 
2441   case lltok::kw_inttoptr:
2442   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2443   // Other.
2444   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2445   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2446   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2447   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2448   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2449   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2450   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2451   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2452   // Memory.
2453   case lltok::kw_alloca:
2454   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
2455   case lltok::kw_free:           return ParseFree(Inst, PFS);
2456   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2457   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2458   case lltok::kw_volatile:
2459     if (EatIfPresent(lltok::kw_load))
2460       return ParseLoad(Inst, PFS, true);
2461     else if (EatIfPresent(lltok::kw_store))
2462       return ParseStore(Inst, PFS, true);
2463     else
2464       return TokError("expected 'load' or 'store'");
2465   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2466   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2467   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2468   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2469   }
2470 }
2471
2472 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2473 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2474   // FIXME: REMOVE vicmp/vfcmp!
2475   if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2476     switch (Lex.getKind()) {
2477     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2478     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2479     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2480     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2481     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2482     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2483     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2484     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2485     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2486     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2487     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2488     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2489     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2490     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2491     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2492     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2493     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2494     }
2495   } else {
2496     switch (Lex.getKind()) {
2497     default: TokError("expected icmp predicate (e.g. 'eq')");
2498     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2499     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2500     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2501     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2502     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2503     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2504     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2505     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2506     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2507     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2508     }
2509   }
2510   Lex.Lex();
2511   return false;
2512 }
2513
2514 //===----------------------------------------------------------------------===//
2515 // Terminator Instructions.
2516 //===----------------------------------------------------------------------===//
2517
2518 /// ParseRet - Parse a return instruction.
2519 ///   ::= 'ret' void
2520 ///   ::= 'ret' TypeAndValue
2521 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  [[obsolete: LLVM 3.0]]
2522 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2523                         PerFunctionState &PFS) {
2524   PATypeHolder Ty(Type::VoidTy);
2525   if (ParseType(Ty, true /*void allowed*/)) return true;
2526   
2527   if (Ty == Type::VoidTy) {
2528     Inst = ReturnInst::Create();
2529     return false;
2530   }
2531   
2532   Value *RV;
2533   if (ParseValue(Ty, RV, PFS)) return true;
2534   
2535   // The normal case is one return value.
2536   if (Lex.getKind() == lltok::comma) {
2537     // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2538     // of 'ret {i32,i32} {i32 1, i32 2}'
2539     SmallVector<Value*, 8> RVs;
2540     RVs.push_back(RV);
2541     
2542     while (EatIfPresent(lltok::comma)) {
2543       if (ParseTypeAndValue(RV, PFS)) return true;
2544       RVs.push_back(RV);
2545     }
2546
2547     RV = UndefValue::get(PFS.getFunction().getReturnType());
2548     for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2549       Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2550       BB->getInstList().push_back(I);
2551       RV = I;
2552     }
2553   }
2554   Inst = ReturnInst::Create(RV);
2555   return false;
2556 }
2557
2558
2559 /// ParseBr
2560 ///   ::= 'br' TypeAndValue
2561 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2562 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2563   LocTy Loc, Loc2;
2564   Value *Op0, *Op1, *Op2;
2565   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2566   
2567   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2568     Inst = BranchInst::Create(BB);
2569     return false;
2570   }
2571   
2572   if (Op0->getType() != Type::Int1Ty)
2573     return Error(Loc, "branch condition must have 'i1' type");
2574     
2575   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2576       ParseTypeAndValue(Op1, Loc, PFS) ||
2577       ParseToken(lltok::comma, "expected ',' after true destination") ||
2578       ParseTypeAndValue(Op2, Loc2, PFS))
2579     return true;
2580   
2581   if (!isa<BasicBlock>(Op1))
2582     return Error(Loc, "true destination of branch must be a basic block");
2583   if (!isa<BasicBlock>(Op2))
2584     return Error(Loc2, "true destination of branch must be a basic block");
2585     
2586   Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2587   return false;
2588 }
2589
2590 /// ParseSwitch
2591 ///  Instruction
2592 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2593 ///  JumpTable
2594 ///    ::= (TypeAndValue ',' TypeAndValue)*
2595 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2596   LocTy CondLoc, BBLoc;
2597   Value *Cond, *DefaultBB;
2598   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2599       ParseToken(lltok::comma, "expected ',' after switch condition") ||
2600       ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2601       ParseToken(lltok::lsquare, "expected '[' with switch table"))
2602     return true;
2603
2604   if (!isa<IntegerType>(Cond->getType()))
2605     return Error(CondLoc, "switch condition must have integer type");
2606   if (!isa<BasicBlock>(DefaultBB))
2607     return Error(BBLoc, "default destination must be a basic block");
2608   
2609   // Parse the jump table pairs.
2610   SmallPtrSet<Value*, 32> SeenCases;
2611   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2612   while (Lex.getKind() != lltok::rsquare) {
2613     Value *Constant, *DestBB;
2614     
2615     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2616         ParseToken(lltok::comma, "expected ',' after case value") ||
2617         ParseTypeAndValue(DestBB, BBLoc, PFS))
2618       return true;
2619
2620     if (!SeenCases.insert(Constant))
2621       return Error(CondLoc, "duplicate case value in switch");
2622     if (!isa<ConstantInt>(Constant))
2623       return Error(CondLoc, "case value is not a constant integer");
2624     if (!isa<BasicBlock>(DestBB))
2625       return Error(BBLoc, "case destination is not a basic block");
2626     
2627     Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2628                                    cast<BasicBlock>(DestBB)));
2629   }
2630   
2631   Lex.Lex();  // Eat the ']'.
2632   
2633   SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2634                                       Table.size());
2635   for (unsigned i = 0, e = Table.size(); i != e; ++i)
2636     SI->addCase(Table[i].first, Table[i].second);
2637   Inst = SI;
2638   return false;
2639 }
2640
2641 /// ParseInvoke
2642 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2643 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2644 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2645   LocTy CallLoc = Lex.getLoc();
2646   unsigned CC, RetAttrs, FnAttrs;
2647   PATypeHolder RetType(Type::VoidTy);
2648   LocTy RetTypeLoc;
2649   ValID CalleeID;
2650   SmallVector<ParamInfo, 16> ArgList;
2651
2652   Value *NormalBB, *UnwindBB;
2653   if (ParseOptionalCallingConv(CC) ||
2654       ParseOptionalAttrs(RetAttrs, 1) ||
2655       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2656       ParseValID(CalleeID) ||
2657       ParseParameterList(ArgList, PFS) ||
2658       ParseOptionalAttrs(FnAttrs, 2) ||
2659       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2660       ParseTypeAndValue(NormalBB, PFS) ||
2661       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2662       ParseTypeAndValue(UnwindBB, PFS))
2663     return true;
2664   
2665   if (!isa<BasicBlock>(NormalBB))
2666     return Error(CallLoc, "normal destination is not a basic block");
2667   if (!isa<BasicBlock>(UnwindBB))
2668     return Error(CallLoc, "unwind destination is not a basic block");
2669   
2670   // If RetType is a non-function pointer type, then this is the short syntax
2671   // for the call, which means that RetType is just the return type.  Infer the
2672   // rest of the function argument types from the arguments that are present.
2673   const PointerType *PFTy = 0;
2674   const FunctionType *Ty = 0;
2675   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2676       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2677     // Pull out the types of all of the arguments...
2678     std::vector<const Type*> ParamTypes;
2679     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2680       ParamTypes.push_back(ArgList[i].V->getType());
2681     
2682     if (!FunctionType::isValidReturnType(RetType))
2683       return Error(RetTypeLoc, "Invalid result type for LLVM function");
2684     
2685     Ty = FunctionType::get(RetType, ParamTypes, false);
2686     PFTy = PointerType::getUnqual(Ty);
2687   }
2688   
2689   // Look up the callee.
2690   Value *Callee;
2691   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2692   
2693   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2694   // function attributes.
2695   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2696   if (FnAttrs & ObsoleteFuncAttrs) {
2697     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2698     FnAttrs &= ~ObsoleteFuncAttrs;
2699   }
2700   
2701   // Set up the Attributes for the function.
2702   SmallVector<AttributeWithIndex, 8> Attrs;
2703   if (RetAttrs != Attribute::None)
2704     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2705   
2706   SmallVector<Value*, 8> Args;
2707   
2708   // Loop through FunctionType's arguments and ensure they are specified
2709   // correctly.  Also, gather any parameter attributes.
2710   FunctionType::param_iterator I = Ty->param_begin();
2711   FunctionType::param_iterator E = Ty->param_end();
2712   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2713     const Type *ExpectedTy = 0;
2714     if (I != E) {
2715       ExpectedTy = *I++;
2716     } else if (!Ty->isVarArg()) {
2717       return Error(ArgList[i].Loc, "too many arguments specified");
2718     }
2719     
2720     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2721       return Error(ArgList[i].Loc, "argument is not of expected type '" +
2722                    ExpectedTy->getDescription() + "'");
2723     Args.push_back(ArgList[i].V);
2724     if (ArgList[i].Attrs != Attribute::None)
2725       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2726   }
2727   
2728   if (I != E)
2729     return Error(CallLoc, "not enough parameters specified for call");
2730   
2731   if (FnAttrs != Attribute::None)
2732     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2733   
2734   // Finish off the Attributes and check them
2735   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2736   
2737   InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2738                                       cast<BasicBlock>(UnwindBB),
2739                                       Args.begin(), Args.end());
2740   II->setCallingConv(CC);
2741   II->setAttributes(PAL);
2742   Inst = II;
2743   return false;
2744 }
2745
2746
2747
2748 //===----------------------------------------------------------------------===//
2749 // Binary Operators.
2750 //===----------------------------------------------------------------------===//
2751
2752 /// ParseArithmetic
2753 ///  ::= ArithmeticOps TypeAndValue ',' Value
2754 ///
2755 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
2756 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2757 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2758                                unsigned Opc, unsigned OperandType) {
2759   LocTy Loc; Value *LHS, *RHS;
2760   if (ParseTypeAndValue(LHS, Loc, PFS) ||
2761       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2762       ParseValue(LHS->getType(), RHS, PFS))
2763     return true;
2764
2765   bool Valid;
2766   switch (OperandType) {
2767   default: assert(0 && "Unknown operand type!");
2768   case 0: // int or FP.
2769     Valid = LHS->getType()->isIntOrIntVector() ||
2770             LHS->getType()->isFPOrFPVector();
2771     break;
2772   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2773   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2774   }
2775   
2776   if (!Valid)
2777     return Error(Loc, "invalid operand type for instruction");
2778   
2779   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2780   return false;
2781 }
2782
2783 /// ParseLogical
2784 ///  ::= ArithmeticOps TypeAndValue ',' Value {
2785 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2786                             unsigned Opc) {
2787   LocTy Loc; Value *LHS, *RHS;
2788   if (ParseTypeAndValue(LHS, Loc, PFS) ||
2789       ParseToken(lltok::comma, "expected ',' in logical operation") ||
2790       ParseValue(LHS->getType(), RHS, PFS))
2791     return true;
2792
2793   if (!LHS->getType()->isIntOrIntVector())
2794     return Error(Loc,"instruction requires integer or integer vector operands");
2795
2796   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2797   return false;
2798 }
2799
2800
2801 /// ParseCompare
2802 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
2803 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
2804 ///  ::= 'vicmp' IPredicates TypeAndValue ',' Value
2805 ///  ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2806 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2807                             unsigned Opc) {
2808   // Parse the integer/fp comparison predicate.
2809   LocTy Loc;
2810   unsigned Pred;
2811   Value *LHS, *RHS;
2812   if (ParseCmpPredicate(Pred, Opc) ||
2813       ParseTypeAndValue(LHS, Loc, PFS) ||
2814       ParseToken(lltok::comma, "expected ',' after compare value") ||
2815       ParseValue(LHS->getType(), RHS, PFS))
2816     return true;
2817   
2818   if (Opc == Instruction::FCmp) {
2819     if (!LHS->getType()->isFPOrFPVector())
2820       return Error(Loc, "fcmp requires floating point operands");
2821     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2822   } else if (Opc == Instruction::ICmp) {
2823     if (!LHS->getType()->isIntOrIntVector() &&
2824         !isa<PointerType>(LHS->getType()))
2825       return Error(Loc, "icmp requires integer operands");
2826     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2827   } else if (Opc == Instruction::VFCmp) {
2828     if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2829       return Error(Loc, "vfcmp requires vector floating point operands");
2830     Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2831   } else if (Opc == Instruction::VICmp) {
2832     if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2833       return Error(Loc, "vicmp requires vector floating point operands");
2834     Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2835   }
2836   return false;
2837 }
2838
2839 //===----------------------------------------------------------------------===//
2840 // Other Instructions.
2841 //===----------------------------------------------------------------------===//
2842
2843
2844 /// ParseCast
2845 ///   ::= CastOpc TypeAndValue 'to' Type
2846 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2847                          unsigned Opc) {
2848   LocTy Loc;  Value *Op;
2849   PATypeHolder DestTy(Type::VoidTy);
2850   if (ParseTypeAndValue(Op, Loc, PFS) ||
2851       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2852       ParseType(DestTy))
2853     return true;
2854   
2855   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2856     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2857     return Error(Loc, "invalid cast opcode for cast from '" +
2858                  Op->getType()->getDescription() + "' to '" +
2859                  DestTy->getDescription() + "'");
2860   }
2861   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2862   return false;
2863 }
2864
2865 /// ParseSelect
2866 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2867 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2868   LocTy Loc;
2869   Value *Op0, *Op1, *Op2;
2870   if (ParseTypeAndValue(Op0, Loc, PFS) ||
2871       ParseToken(lltok::comma, "expected ',' after select condition") ||
2872       ParseTypeAndValue(Op1, PFS) ||
2873       ParseToken(lltok::comma, "expected ',' after select value") ||
2874       ParseTypeAndValue(Op2, PFS))
2875     return true;
2876   
2877   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2878     return Error(Loc, Reason);
2879   
2880   Inst = SelectInst::Create(Op0, Op1, Op2);
2881   return false;
2882 }
2883
2884 /// ParseVA_Arg
2885 ///   ::= 'va_arg' TypeAndValue ',' Type
2886 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2887   Value *Op;
2888   PATypeHolder EltTy(Type::VoidTy);
2889   LocTy TypeLoc;
2890   if (ParseTypeAndValue(Op, PFS) ||
2891       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2892       ParseType(EltTy, TypeLoc))
2893     return true;
2894   
2895   if (!EltTy->isFirstClassType())
2896     return Error(TypeLoc, "va_arg requires operand with first class type");
2897
2898   Inst = new VAArgInst(Op, EltTy);
2899   return false;
2900 }
2901
2902 /// ParseExtractElement
2903 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
2904 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2905   LocTy Loc;
2906   Value *Op0, *Op1;
2907   if (ParseTypeAndValue(Op0, Loc, PFS) ||
2908       ParseToken(lltok::comma, "expected ',' after extract value") ||
2909       ParseTypeAndValue(Op1, PFS))
2910     return true;
2911   
2912   if (!ExtractElementInst::isValidOperands(Op0, Op1))
2913     return Error(Loc, "invalid extractelement operands");
2914   
2915   Inst = new ExtractElementInst(Op0, Op1);
2916   return false;
2917 }
2918
2919 /// ParseInsertElement
2920 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2921 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2922   LocTy Loc;
2923   Value *Op0, *Op1, *Op2;
2924   if (ParseTypeAndValue(Op0, Loc, PFS) ||
2925       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2926       ParseTypeAndValue(Op1, PFS) ||
2927       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2928       ParseTypeAndValue(Op2, PFS))
2929     return true;
2930   
2931   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2932     return Error(Loc, "invalid extractelement operands");
2933   
2934   Inst = InsertElementInst::Create(Op0, Op1, Op2);
2935   return false;
2936 }
2937
2938 /// ParseShuffleVector
2939 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2940 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2941   LocTy Loc;
2942   Value *Op0, *Op1, *Op2;
2943   if (ParseTypeAndValue(Op0, Loc, PFS) ||
2944       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2945       ParseTypeAndValue(Op1, PFS) ||
2946       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2947       ParseTypeAndValue(Op2, PFS))
2948     return true;
2949   
2950   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2951     return Error(Loc, "invalid extractelement operands");
2952   
2953   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2954   return false;
2955 }
2956
2957 /// ParsePHI
2958 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2959 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2960   PATypeHolder Ty(Type::VoidTy);
2961   Value *Op0, *Op1;
2962   LocTy TypeLoc = Lex.getLoc();
2963   
2964   if (ParseType(Ty) ||
2965       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2966       ParseValue(Ty, Op0, PFS) ||
2967       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2968       ParseValue(Type::LabelTy, Op1, PFS) ||
2969       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2970     return true;
2971  
2972   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2973   while (1) {
2974     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2975     
2976     if (!EatIfPresent(lltok::comma))
2977       break;
2978
2979     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2980         ParseValue(Ty, Op0, PFS) ||
2981         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2982         ParseValue(Type::LabelTy, Op1, PFS) ||
2983         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2984       return true;
2985   }
2986   
2987   if (!Ty->isFirstClassType())
2988     return Error(TypeLoc, "phi node must have first class type");
2989
2990   PHINode *PN = PHINode::Create(Ty);
2991   PN->reserveOperandSpace(PHIVals.size());
2992   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2993     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2994   Inst = PN;
2995   return false;
2996 }
2997
2998 /// ParseCall
2999 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3000 ///       ParameterList OptionalAttrs
3001 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3002                          bool isTail) {
3003   unsigned CC, RetAttrs, FnAttrs;
3004   PATypeHolder RetType(Type::VoidTy);
3005   LocTy RetTypeLoc;
3006   ValID CalleeID;
3007   SmallVector<ParamInfo, 16> ArgList;
3008   LocTy CallLoc = Lex.getLoc();
3009   
3010   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3011       ParseOptionalCallingConv(CC) ||
3012       ParseOptionalAttrs(RetAttrs, 1) ||
3013       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3014       ParseValID(CalleeID) ||
3015       ParseParameterList(ArgList, PFS) ||
3016       ParseOptionalAttrs(FnAttrs, 2))
3017     return true;
3018   
3019   // If RetType is a non-function pointer type, then this is the short syntax
3020   // for the call, which means that RetType is just the return type.  Infer the
3021   // rest of the function argument types from the arguments that are present.
3022   const PointerType *PFTy = 0;
3023   const FunctionType *Ty = 0;
3024   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3025       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3026     // Pull out the types of all of the arguments...
3027     std::vector<const Type*> ParamTypes;
3028     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3029       ParamTypes.push_back(ArgList[i].V->getType());
3030     
3031     if (!FunctionType::isValidReturnType(RetType))
3032       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3033     
3034     Ty = FunctionType::get(RetType, ParamTypes, false);
3035     PFTy = PointerType::getUnqual(Ty);
3036   }
3037   
3038   // Look up the callee.
3039   Value *Callee;
3040   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3041   
3042   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3043   // function attributes.
3044   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3045   if (FnAttrs & ObsoleteFuncAttrs) {
3046     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3047     FnAttrs &= ~ObsoleteFuncAttrs;
3048   }
3049
3050   // Set up the Attributes for the function.
3051   SmallVector<AttributeWithIndex, 8> Attrs;
3052   if (RetAttrs != Attribute::None)
3053     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3054   
3055   SmallVector<Value*, 8> Args;
3056   
3057   // Loop through FunctionType's arguments and ensure they are specified
3058   // correctly.  Also, gather any parameter attributes.
3059   FunctionType::param_iterator I = Ty->param_begin();
3060   FunctionType::param_iterator E = Ty->param_end();
3061   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3062     const Type *ExpectedTy = 0;
3063     if (I != E) {
3064       ExpectedTy = *I++;
3065     } else if (!Ty->isVarArg()) {
3066       return Error(ArgList[i].Loc, "too many arguments specified");
3067     }
3068     
3069     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3070       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3071                    ExpectedTy->getDescription() + "'");
3072     Args.push_back(ArgList[i].V);
3073     if (ArgList[i].Attrs != Attribute::None)
3074       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3075   }
3076   
3077   if (I != E)
3078     return Error(CallLoc, "not enough parameters specified for call");
3079
3080   if (FnAttrs != Attribute::None)
3081     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3082
3083   // Finish off the Attributes and check them
3084   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3085   
3086   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3087   CI->setTailCall(isTail);
3088   CI->setCallingConv(CC);
3089   CI->setAttributes(PAL);
3090   Inst = CI;
3091   return false;
3092 }
3093
3094 //===----------------------------------------------------------------------===//
3095 // Memory Instructions.
3096 //===----------------------------------------------------------------------===//
3097
3098 /// ParseAlloc
3099 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3100 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3101 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3102                           unsigned Opc) {
3103   PATypeHolder Ty(Type::VoidTy);
3104   Value *Size = 0;
3105   LocTy SizeLoc = 0;
3106   unsigned Alignment = 0;
3107   if (ParseType(Ty)) return true;
3108
3109   if (EatIfPresent(lltok::comma)) {
3110     if (Lex.getKind() == lltok::kw_align) {
3111       if (ParseOptionalAlignment(Alignment)) return true;
3112     } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3113                ParseOptionalCommaAlignment(Alignment)) {
3114       return true;
3115     }
3116   }
3117
3118   if (Size && Size->getType() != Type::Int32Ty)
3119     return Error(SizeLoc, "element count must be i32");
3120
3121   if (Opc == Instruction::Malloc)
3122     Inst = new MallocInst(Ty, Size, Alignment);
3123   else
3124     Inst = new AllocaInst(Ty, Size, Alignment);
3125   return false;
3126 }
3127
3128 /// ParseFree
3129 ///   ::= 'free' TypeAndValue
3130 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3131   Value *Val; LocTy Loc;
3132   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3133   if (!isa<PointerType>(Val->getType()))
3134     return Error(Loc, "operand to free must be a pointer");
3135   Inst = new FreeInst(Val);
3136   return false;
3137 }
3138
3139 /// ParseLoad
3140 ///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3141 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3142                          bool isVolatile) {
3143   Value *Val; LocTy Loc;
3144   unsigned Alignment;
3145   if (ParseTypeAndValue(Val, Loc, PFS) ||
3146       ParseOptionalCommaAlignment(Alignment))
3147     return true;
3148
3149   if (!isa<PointerType>(Val->getType()) ||
3150       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3151     return Error(Loc, "load operand must be a pointer to a first class type");
3152   
3153   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3154   return false;
3155 }
3156
3157 /// ParseStore
3158 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3159 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3160                           bool isVolatile) {
3161   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3162   unsigned Alignment;
3163   if (ParseTypeAndValue(Val, Loc, PFS) ||
3164       ParseToken(lltok::comma, "expected ',' after store operand") ||
3165       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3166       ParseOptionalCommaAlignment(Alignment))
3167     return true;
3168   
3169   if (!isa<PointerType>(Ptr->getType()))
3170     return Error(PtrLoc, "store operand must be a pointer");
3171   if (!Val->getType()->isFirstClassType())
3172     return Error(Loc, "store operand must be a first class value");
3173   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3174     return Error(Loc, "stored value and pointer type do not match");
3175   
3176   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3177   return false;
3178 }
3179
3180 /// ParseGetResult
3181 ///   ::= 'getresult' TypeAndValue ',' uint
3182 /// FIXME: Remove support for getresult in LLVM 3.0
3183 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3184   Value *Val; LocTy ValLoc, EltLoc;
3185   unsigned Element;
3186   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3187       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3188       ParseUInt32(Element, EltLoc))
3189     return true;
3190   
3191   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3192     return Error(ValLoc, "getresult inst requires an aggregate operand");
3193   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3194     return Error(EltLoc, "invalid getresult index for value");
3195   Inst = ExtractValueInst::Create(Val, Element);
3196   return false;
3197 }
3198
3199 /// ParseGetElementPtr
3200 ///   ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3201 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3202   Value *Ptr, *Val; LocTy Loc, EltLoc;
3203   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3204   
3205   if (!isa<PointerType>(Ptr->getType()))
3206     return Error(Loc, "base of getelementptr must be a pointer");
3207   
3208   SmallVector<Value*, 16> Indices;
3209   while (EatIfPresent(lltok::comma)) {
3210     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3211     if (!isa<IntegerType>(Val->getType()))
3212       return Error(EltLoc, "getelementptr index must be an integer");
3213     Indices.push_back(Val);
3214   }
3215   
3216   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3217                                          Indices.begin(), Indices.end()))
3218     return Error(Loc, "invalid getelementptr indices");
3219   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3220   return false;
3221 }
3222
3223 /// ParseExtractValue
3224 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3225 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3226   Value *Val; LocTy Loc;
3227   SmallVector<unsigned, 4> Indices;
3228   if (ParseTypeAndValue(Val, Loc, PFS) ||
3229       ParseIndexList(Indices))
3230     return true;
3231
3232   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3233     return Error(Loc, "extractvalue operand must be array or struct");
3234
3235   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3236                                         Indices.end()))
3237     return Error(Loc, "invalid indices for extractvalue");
3238   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3239   return false;
3240 }
3241
3242 /// ParseInsertValue
3243 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3244 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3245   Value *Val0, *Val1; LocTy Loc0, Loc1;
3246   SmallVector<unsigned, 4> Indices;
3247   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3248       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3249       ParseTypeAndValue(Val1, Loc1, PFS) ||
3250       ParseIndexList(Indices))
3251     return true;
3252   
3253   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3254     return Error(Loc0, "extractvalue operand must be array or struct");
3255   
3256   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3257                                         Indices.end()))
3258     return Error(Loc0, "invalid indices for insertvalue");
3259   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3260   return false;
3261 }
3262
3263 //===----------------------------------------------------------------------===//
3264 // Embedded metadata.
3265 //===----------------------------------------------------------------------===//
3266
3267 /// ParseMDNodeVector
3268 ///   ::= Element (',' Element)*
3269 /// Element
3270 ///   ::= 'null' | TypeAndValue
3271 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3272   assert(Lex.getKind() == lltok::lbrace);
3273   Lex.Lex();
3274   do {
3275     Value *V;
3276     if (Lex.getKind() == lltok::kw_null) {
3277       Lex.Lex();
3278       V = 0;
3279     } else {
3280       Constant *C;
3281       if (ParseGlobalTypeAndValue(C)) return true;
3282       V = C;
3283     }
3284     Elts.push_back(V);
3285   } while (EatIfPresent(lltok::comma));
3286
3287   return false;
3288 }