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