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