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