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