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