f1d5e4ffbb7f383ee691d8c66e11b7b054273894
[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   if (Lex.getKind() != lltok::NamedOrCustomMD)
1055     return false;
1056
1057   std::string Name = Lex.getStrVal();
1058   Lex.Lex();
1059
1060   if (Lex.getKind() != lltok::Metadata)
1061     return TokError("Expected '!' here");
1062   Lex.Lex();
1063
1064   MetadataBase *Node;
1065   if (ParseMDNode(Node)) return true;
1066
1067   MetadataContext &TheMetadata = M->getContext().getMetadata();
1068   unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1069   if (!MDK)
1070     MDK = TheMetadata.registerMDKind(Name.c_str());
1071   MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
1072
1073   return false;
1074 }
1075
1076 /// ParseOptionalAlignment
1077 ///   ::= /* empty */
1078 ///   ::= 'align' 4
1079 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1080   Alignment = 0;
1081   if (!EatIfPresent(lltok::kw_align))
1082     return false;
1083   LocTy AlignLoc = Lex.getLoc();
1084   if (ParseUInt32(Alignment)) return true;
1085   if (!isPowerOf2_32(Alignment))
1086     return Error(AlignLoc, "alignment is not a power of two");
1087   return false;
1088 }
1089
1090 /// ParseOptionalInfo
1091 ///   ::= OptionalInfo (',' OptionalInfo)+
1092 bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1093
1094   // FIXME: Handle customized metadata info attached with an instruction.
1095   do {
1096       if (Lex.getKind() == lltok::NamedOrCustomMD) {
1097       if (ParseOptionalCustomMetadata()) return true;
1098     } else if (Lex.getKind() == lltok::kw_align) {
1099       if (ParseOptionalAlignment(Alignment)) return true;
1100     } else
1101       return true;
1102   } while (EatIfPresent(lltok::comma));
1103
1104   return false;
1105 }
1106
1107
1108 /// ParseIndexList
1109 ///    ::=  (',' uint32)+
1110 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1111   if (Lex.getKind() != lltok::comma)
1112     return TokError("expected ',' as start of index list");
1113
1114   while (EatIfPresent(lltok::comma)) {
1115     unsigned Idx;
1116     if (ParseUInt32(Idx)) return true;
1117     Indices.push_back(Idx);
1118   }
1119
1120   return false;
1121 }
1122
1123 //===----------------------------------------------------------------------===//
1124 // Type Parsing.
1125 //===----------------------------------------------------------------------===//
1126
1127 /// ParseType - Parse and resolve a full type.
1128 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1129   LocTy TypeLoc = Lex.getLoc();
1130   if (ParseTypeRec(Result)) return true;
1131
1132   // Verify no unresolved uprefs.
1133   if (!UpRefs.empty())
1134     return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1135
1136   if (!AllowVoid && Result.get()->isVoidTy())
1137     return Error(TypeLoc, "void type only allowed for function results");
1138
1139   return false;
1140 }
1141
1142 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1143 /// called.  It loops through the UpRefs vector, which is a list of the
1144 /// currently active types.  For each type, if the up-reference is contained in
1145 /// the newly completed type, we decrement the level count.  When the level
1146 /// count reaches zero, the up-referenced type is the type that is passed in:
1147 /// thus we can complete the cycle.
1148 ///
1149 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1150   // If Ty isn't abstract, or if there are no up-references in it, then there is
1151   // nothing to resolve here.
1152   if (!ty->isAbstract() || UpRefs.empty()) return ty;
1153
1154   PATypeHolder Ty(ty);
1155 #if 0
1156   errs() << "Type '" << Ty->getDescription()
1157          << "' newly formed.  Resolving upreferences.\n"
1158          << UpRefs.size() << " upreferences active!\n";
1159 #endif
1160
1161   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1162   // to zero), we resolve them all together before we resolve them to Ty.  At
1163   // the end of the loop, if there is anything to resolve to Ty, it will be in
1164   // this variable.
1165   OpaqueType *TypeToResolve = 0;
1166
1167   for (unsigned i = 0; i != UpRefs.size(); ++i) {
1168     // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1169     bool ContainsType =
1170       std::find(Ty->subtype_begin(), Ty->subtype_end(),
1171                 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1172
1173 #if 0
1174     errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1175            << UpRefs[i].LastContainedTy->getDescription() << ") = "
1176            << (ContainsType ? "true" : "false")
1177            << " level=" << UpRefs[i].NestingLevel << "\n";
1178 #endif
1179     if (!ContainsType)
1180       continue;
1181
1182     // Decrement level of upreference
1183     unsigned Level = --UpRefs[i].NestingLevel;
1184     UpRefs[i].LastContainedTy = Ty;
1185
1186     // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1187     if (Level != 0)
1188       continue;
1189
1190 #if 0
1191     errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1192 #endif
1193     if (!TypeToResolve)
1194       TypeToResolve = UpRefs[i].UpRefTy;
1195     else
1196       UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1197     UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1198     --i;                                // Do not skip the next element.
1199   }
1200
1201   if (TypeToResolve)
1202     TypeToResolve->refineAbstractTypeTo(Ty);
1203
1204   return Ty;
1205 }
1206
1207
1208 /// ParseTypeRec - The recursive function used to process the internal
1209 /// implementation details of types.
1210 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1211   switch (Lex.getKind()) {
1212   default:
1213     return TokError("expected type");
1214   case lltok::Type:
1215     // TypeRec ::= 'float' | 'void' (etc)
1216     Result = Lex.getTyVal();
1217     Lex.Lex();
1218     break;
1219   case lltok::kw_opaque:
1220     // TypeRec ::= 'opaque'
1221     Result = OpaqueType::get(Context);
1222     Lex.Lex();
1223     break;
1224   case lltok::lbrace:
1225     // TypeRec ::= '{' ... '}'
1226     if (ParseStructType(Result, false))
1227       return true;
1228     break;
1229   case lltok::lsquare:
1230     // TypeRec ::= '[' ... ']'
1231     Lex.Lex(); // eat the lsquare.
1232     if (ParseArrayVectorType(Result, false))
1233       return true;
1234     break;
1235   case lltok::less: // Either vector or packed struct.
1236     // TypeRec ::= '<' ... '>'
1237     Lex.Lex();
1238     if (Lex.getKind() == lltok::lbrace) {
1239       if (ParseStructType(Result, true) ||
1240           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1241         return true;
1242     } else if (ParseArrayVectorType(Result, true))
1243       return true;
1244     break;
1245   case lltok::LocalVar:
1246   case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1247     // TypeRec ::= %foo
1248     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1249       Result = T;
1250     } else {
1251       Result = OpaqueType::get(Context);
1252       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1253                                             std::make_pair(Result,
1254                                                            Lex.getLoc())));
1255       M->addTypeName(Lex.getStrVal(), Result.get());
1256     }
1257     Lex.Lex();
1258     break;
1259
1260   case lltok::LocalVarID:
1261     // TypeRec ::= %4
1262     if (Lex.getUIntVal() < NumberedTypes.size())
1263       Result = NumberedTypes[Lex.getUIntVal()];
1264     else {
1265       std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1266         I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1267       if (I != ForwardRefTypeIDs.end())
1268         Result = I->second.first;
1269       else {
1270         Result = OpaqueType::get(Context);
1271         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1272                                                 std::make_pair(Result,
1273                                                                Lex.getLoc())));
1274       }
1275     }
1276     Lex.Lex();
1277     break;
1278   case lltok::backslash: {
1279     // TypeRec ::= '\' 4
1280     Lex.Lex();
1281     unsigned Val;
1282     if (ParseUInt32(Val)) return true;
1283     OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1284     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1285     Result = OT;
1286     break;
1287   }
1288   }
1289
1290   // Parse the type suffixes.
1291   while (1) {
1292     switch (Lex.getKind()) {
1293     // End of type.
1294     default: return false;
1295
1296     // TypeRec ::= TypeRec '*'
1297     case lltok::star:
1298       if (Result.get()->isLabelTy())
1299         return TokError("basic block pointers are invalid");
1300       if (Result.get()->isVoidTy())
1301         return TokError("pointers to void are invalid; use i8* instead");
1302       if (!PointerType::isValidElementType(Result.get()))
1303         return TokError("pointer to this type is invalid");
1304       Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1305       Lex.Lex();
1306       break;
1307
1308     // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1309     case lltok::kw_addrspace: {
1310       if (Result.get()->isLabelTy())
1311         return TokError("basic block pointers are invalid");
1312       if (Result.get()->isVoidTy())
1313         return TokError("pointers to void are invalid; use i8* instead");
1314       if (!PointerType::isValidElementType(Result.get()))
1315         return TokError("pointer to this type is invalid");
1316       unsigned AddrSpace;
1317       if (ParseOptionalAddrSpace(AddrSpace) ||
1318           ParseToken(lltok::star, "expected '*' in address space"))
1319         return true;
1320
1321       Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1322       break;
1323     }
1324
1325     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1326     case lltok::lparen:
1327       if (ParseFunctionType(Result))
1328         return true;
1329       break;
1330     }
1331   }
1332 }
1333
1334 /// ParseParameterList
1335 ///    ::= '(' ')'
1336 ///    ::= '(' Arg (',' Arg)* ')'
1337 ///  Arg
1338 ///    ::= Type OptionalAttributes Value OptionalAttributes
1339 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1340                                   PerFunctionState &PFS) {
1341   if (ParseToken(lltok::lparen, "expected '(' in call"))
1342     return true;
1343
1344   while (Lex.getKind() != lltok::rparen) {
1345     // If this isn't the first argument, we need a comma.
1346     if (!ArgList.empty() &&
1347         ParseToken(lltok::comma, "expected ',' in argument list"))
1348       return true;
1349
1350     // Parse the argument.
1351     LocTy ArgLoc;
1352     PATypeHolder ArgTy(Type::getVoidTy(Context));
1353     unsigned ArgAttrs1, ArgAttrs2;
1354     Value *V;
1355     if (ParseType(ArgTy, ArgLoc) ||
1356         ParseOptionalAttrs(ArgAttrs1, 0) ||
1357         ParseValue(ArgTy, V, PFS) ||
1358         // FIXME: Should not allow attributes after the argument, remove this in
1359         // LLVM 3.0.
1360         ParseOptionalAttrs(ArgAttrs2, 3))
1361       return true;
1362     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1363   }
1364
1365   Lex.Lex();  // Lex the ')'.
1366   return false;
1367 }
1368
1369
1370
1371 /// ParseArgumentList - Parse the argument list for a function type or function
1372 /// prototype.  If 'inType' is true then we are parsing a FunctionType.
1373 ///   ::= '(' ArgTypeListI ')'
1374 /// ArgTypeListI
1375 ///   ::= /*empty*/
1376 ///   ::= '...'
1377 ///   ::= ArgTypeList ',' '...'
1378 ///   ::= ArgType (',' ArgType)*
1379 ///
1380 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1381                                  bool &isVarArg, bool inType) {
1382   isVarArg = false;
1383   assert(Lex.getKind() == lltok::lparen);
1384   Lex.Lex(); // eat the (.
1385
1386   if (Lex.getKind() == lltok::rparen) {
1387     // empty
1388   } else if (Lex.getKind() == lltok::dotdotdot) {
1389     isVarArg = true;
1390     Lex.Lex();
1391   } else {
1392     LocTy TypeLoc = Lex.getLoc();
1393     PATypeHolder ArgTy(Type::getVoidTy(Context));
1394     unsigned Attrs;
1395     std::string Name;
1396
1397     // If we're parsing a type, use ParseTypeRec, because we allow recursive
1398     // types (such as a function returning a pointer to itself).  If parsing a
1399     // function prototype, we require fully resolved types.
1400     if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1401         ParseOptionalAttrs(Attrs, 0)) return true;
1402
1403     if (ArgTy->isVoidTy())
1404       return Error(TypeLoc, "argument can not have void type");
1405
1406     if (Lex.getKind() == lltok::LocalVar ||
1407         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1408       Name = Lex.getStrVal();
1409       Lex.Lex();
1410     }
1411
1412     if (!FunctionType::isValidArgumentType(ArgTy))
1413       return Error(TypeLoc, "invalid type for function argument");
1414
1415     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1416
1417     while (EatIfPresent(lltok::comma)) {
1418       // Handle ... at end of arg list.
1419       if (EatIfPresent(lltok::dotdotdot)) {
1420         isVarArg = true;
1421         break;
1422       }
1423
1424       // Otherwise must be an argument type.
1425       TypeLoc = Lex.getLoc();
1426       if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1427           ParseOptionalAttrs(Attrs, 0)) return true;
1428
1429       if (ArgTy->isVoidTy())
1430         return Error(TypeLoc, "argument can not have void type");
1431
1432       if (Lex.getKind() == lltok::LocalVar ||
1433           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1434         Name = Lex.getStrVal();
1435         Lex.Lex();
1436       } else {
1437         Name = "";
1438       }
1439
1440       if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1441         return Error(TypeLoc, "invalid type for function argument");
1442
1443       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1444     }
1445   }
1446
1447   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1448 }
1449
1450 /// ParseFunctionType
1451 ///  ::= Type ArgumentList OptionalAttrs
1452 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1453   assert(Lex.getKind() == lltok::lparen);
1454
1455   if (!FunctionType::isValidReturnType(Result))
1456     return TokError("invalid function return type");
1457
1458   std::vector<ArgInfo> ArgList;
1459   bool isVarArg;
1460   unsigned Attrs;
1461   if (ParseArgumentList(ArgList, isVarArg, true) ||
1462       // FIXME: Allow, but ignore attributes on function types!
1463       // FIXME: Remove in LLVM 3.0
1464       ParseOptionalAttrs(Attrs, 2))
1465     return true;
1466
1467   // Reject names on the arguments lists.
1468   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1469     if (!ArgList[i].Name.empty())
1470       return Error(ArgList[i].Loc, "argument name invalid in function type");
1471     if (!ArgList[i].Attrs != 0) {
1472       // Allow but ignore attributes on function types; this permits
1473       // auto-upgrade.
1474       // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1475     }
1476   }
1477
1478   std::vector<const Type*> ArgListTy;
1479   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1480     ArgListTy.push_back(ArgList[i].Type);
1481
1482   Result = HandleUpRefs(FunctionType::get(Result.get(),
1483                                                 ArgListTy, isVarArg));
1484   return false;
1485 }
1486
1487 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1488 ///   TypeRec
1489 ///     ::= '{' '}'
1490 ///     ::= '{' TypeRec (',' TypeRec)* '}'
1491 ///     ::= '<' '{' '}' '>'
1492 ///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1493 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1494   assert(Lex.getKind() == lltok::lbrace);
1495   Lex.Lex(); // Consume the '{'
1496
1497   if (EatIfPresent(lltok::rbrace)) {
1498     Result = StructType::get(Context, Packed);
1499     return false;
1500   }
1501
1502   std::vector<PATypeHolder> ParamsList;
1503   LocTy EltTyLoc = Lex.getLoc();
1504   if (ParseTypeRec(Result)) return true;
1505   ParamsList.push_back(Result);
1506
1507   if (Result->isVoidTy())
1508     return Error(EltTyLoc, "struct element can not have void type");
1509   if (!StructType::isValidElementType(Result))
1510     return Error(EltTyLoc, "invalid element type for struct");
1511
1512   while (EatIfPresent(lltok::comma)) {
1513     EltTyLoc = Lex.getLoc();
1514     if (ParseTypeRec(Result)) return true;
1515
1516     if (Result->isVoidTy())
1517       return Error(EltTyLoc, "struct element can not have void type");
1518     if (!StructType::isValidElementType(Result))
1519       return Error(EltTyLoc, "invalid element type for struct");
1520
1521     ParamsList.push_back(Result);
1522   }
1523
1524   if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1525     return true;
1526
1527   std::vector<const Type*> ParamsListTy;
1528   for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1529     ParamsListTy.push_back(ParamsList[i].get());
1530   Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1531   return false;
1532 }
1533
1534 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1535 /// token has already been consumed.
1536 ///   TypeRec
1537 ///     ::= '[' APSINTVAL 'x' Types ']'
1538 ///     ::= '<' APSINTVAL 'x' Types '>'
1539 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1540   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1541       Lex.getAPSIntVal().getBitWidth() > 64)
1542     return TokError("expected number in address space");
1543
1544   LocTy SizeLoc = Lex.getLoc();
1545   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1546   Lex.Lex();
1547
1548   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1549       return true;
1550
1551   LocTy TypeLoc = Lex.getLoc();
1552   PATypeHolder EltTy(Type::getVoidTy(Context));
1553   if (ParseTypeRec(EltTy)) return true;
1554
1555   if (EltTy->isVoidTy())
1556     return Error(TypeLoc, "array and vector element type cannot be void");
1557
1558   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1559                  "expected end of sequential type"))
1560     return true;
1561
1562   if (isVector) {
1563     if (Size == 0)
1564       return Error(SizeLoc, "zero element vector is illegal");
1565     if ((unsigned)Size != Size)
1566       return Error(SizeLoc, "size too large for vector");
1567     if (!VectorType::isValidElementType(EltTy))
1568       return Error(TypeLoc, "vector element type must be fp or integer");
1569     Result = VectorType::get(EltTy, unsigned(Size));
1570   } else {
1571     if (!ArrayType::isValidElementType(EltTy))
1572       return Error(TypeLoc, "invalid array element type");
1573     Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1574   }
1575   return false;
1576 }
1577
1578 //===----------------------------------------------------------------------===//
1579 // Function Semantic Analysis.
1580 //===----------------------------------------------------------------------===//
1581
1582 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1583   : P(p), F(f) {
1584
1585   // Insert unnamed arguments into the NumberedVals list.
1586   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1587        AI != E; ++AI)
1588     if (!AI->hasName())
1589       NumberedVals.push_back(AI);
1590 }
1591
1592 LLParser::PerFunctionState::~PerFunctionState() {
1593   // If there were any forward referenced non-basicblock values, delete them.
1594   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1595        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1596     if (!isa<BasicBlock>(I->second.first)) {
1597       I->second.first->replaceAllUsesWith(
1598                            UndefValue::get(I->second.first->getType()));
1599       delete I->second.first;
1600       I->second.first = 0;
1601     }
1602
1603   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1604        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1605     if (!isa<BasicBlock>(I->second.first)) {
1606       I->second.first->replaceAllUsesWith(
1607                            UndefValue::get(I->second.first->getType()));
1608       delete I->second.first;
1609       I->second.first = 0;
1610     }
1611 }
1612
1613 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1614   if (!ForwardRefVals.empty())
1615     return P.Error(ForwardRefVals.begin()->second.second,
1616                    "use of undefined value '%" + ForwardRefVals.begin()->first +
1617                    "'");
1618   if (!ForwardRefValIDs.empty())
1619     return P.Error(ForwardRefValIDs.begin()->second.second,
1620                    "use of undefined value '%" +
1621                    utostr(ForwardRefValIDs.begin()->first) + "'");
1622   return false;
1623 }
1624
1625
1626 /// GetVal - Get a value with the specified name or ID, creating a
1627 /// forward reference record if needed.  This can return null if the value
1628 /// exists but does not have the right type.
1629 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1630                                           const Type *Ty, LocTy Loc) {
1631   // Look this name up in the normal function symbol table.
1632   Value *Val = F.getValueSymbolTable().lookup(Name);
1633
1634   // If this is a forward reference for the value, see if we already created a
1635   // forward ref record.
1636   if (Val == 0) {
1637     std::map<std::string, std::pair<Value*, LocTy> >::iterator
1638       I = ForwardRefVals.find(Name);
1639     if (I != ForwardRefVals.end())
1640       Val = I->second.first;
1641   }
1642
1643   // If we have the value in the symbol table or fwd-ref table, return it.
1644   if (Val) {
1645     if (Val->getType() == Ty) return Val;
1646     if (Ty->isLabelTy())
1647       P.Error(Loc, "'%" + Name + "' is not a basic block");
1648     else
1649       P.Error(Loc, "'%" + Name + "' defined with type '" +
1650               Val->getType()->getDescription() + "'");
1651     return 0;
1652   }
1653
1654   // Don't make placeholders with invalid type.
1655   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1656       Ty != Type::getLabelTy(F.getContext())) {
1657     P.Error(Loc, "invalid use of a non-first-class type");
1658     return 0;
1659   }
1660
1661   // Otherwise, create a new forward reference for this value and remember it.
1662   Value *FwdVal;
1663   if (Ty->isLabelTy())
1664     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1665   else
1666     FwdVal = new Argument(Ty, Name);
1667
1668   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1669   return FwdVal;
1670 }
1671
1672 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1673                                           LocTy Loc) {
1674   // Look this name up in the normal function symbol table.
1675   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1676
1677   // If this is a forward reference for the value, see if we already created a
1678   // forward ref record.
1679   if (Val == 0) {
1680     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1681       I = ForwardRefValIDs.find(ID);
1682     if (I != ForwardRefValIDs.end())
1683       Val = I->second.first;
1684   }
1685
1686   // If we have the value in the symbol table or fwd-ref table, return it.
1687   if (Val) {
1688     if (Val->getType() == Ty) return Val;
1689     if (Ty->isLabelTy())
1690       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1691     else
1692       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1693               Val->getType()->getDescription() + "'");
1694     return 0;
1695   }
1696
1697   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1698       Ty != Type::getLabelTy(F.getContext())) {
1699     P.Error(Loc, "invalid use of a non-first-class type");
1700     return 0;
1701   }
1702
1703   // Otherwise, create a new forward reference for this value and remember it.
1704   Value *FwdVal;
1705   if (Ty->isLabelTy())
1706     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1707   else
1708     FwdVal = new Argument(Ty);
1709
1710   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1711   return FwdVal;
1712 }
1713
1714 /// SetInstName - After an instruction is parsed and inserted into its
1715 /// basic block, this installs its name.
1716 bool LLParser::PerFunctionState::SetInstName(int NameID,
1717                                              const std::string &NameStr,
1718                                              LocTy NameLoc, Instruction *Inst) {
1719   // If this instruction has void type, it cannot have a name or ID specified.
1720   if (Inst->getType()->isVoidTy()) {
1721     if (NameID != -1 || !NameStr.empty())
1722       return P.Error(NameLoc, "instructions returning void cannot have a name");
1723     return false;
1724   }
1725
1726   // If this was a numbered instruction, verify that the instruction is the
1727   // expected value and resolve any forward references.
1728   if (NameStr.empty()) {
1729     // If neither a name nor an ID was specified, just use the next ID.
1730     if (NameID == -1)
1731       NameID = NumberedVals.size();
1732
1733     if (unsigned(NameID) != NumberedVals.size())
1734       return P.Error(NameLoc, "instruction expected to be numbered '%" +
1735                      utostr(NumberedVals.size()) + "'");
1736
1737     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1738       ForwardRefValIDs.find(NameID);
1739     if (FI != ForwardRefValIDs.end()) {
1740       if (FI->second.first->getType() != Inst->getType())
1741         return P.Error(NameLoc, "instruction forward referenced with type '" +
1742                        FI->second.first->getType()->getDescription() + "'");
1743       FI->second.first->replaceAllUsesWith(Inst);
1744       delete FI->second.first;
1745       ForwardRefValIDs.erase(FI);
1746     }
1747
1748     NumberedVals.push_back(Inst);
1749     return false;
1750   }
1751
1752   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1753   std::map<std::string, std::pair<Value*, LocTy> >::iterator
1754     FI = ForwardRefVals.find(NameStr);
1755   if (FI != ForwardRefVals.end()) {
1756     if (FI->second.first->getType() != Inst->getType())
1757       return P.Error(NameLoc, "instruction forward referenced with type '" +
1758                      FI->second.first->getType()->getDescription() + "'");
1759     FI->second.first->replaceAllUsesWith(Inst);
1760     delete FI->second.first;
1761     ForwardRefVals.erase(FI);
1762   }
1763
1764   // Set the name on the instruction.
1765   Inst->setName(NameStr);
1766
1767   if (Inst->getNameStr() != NameStr)
1768     return P.Error(NameLoc, "multiple definition of local value named '" +
1769                    NameStr + "'");
1770   return false;
1771 }
1772
1773 /// GetBB - Get a basic block with the specified name or ID, creating a
1774 /// forward reference record if needed.
1775 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1776                                               LocTy Loc) {
1777   return cast_or_null<BasicBlock>(GetVal(Name,
1778                                         Type::getLabelTy(F.getContext()), Loc));
1779 }
1780
1781 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1782   return cast_or_null<BasicBlock>(GetVal(ID,
1783                                         Type::getLabelTy(F.getContext()), Loc));
1784 }
1785
1786 /// DefineBB - Define the specified basic block, which is either named or
1787 /// unnamed.  If there is an error, this returns null otherwise it returns
1788 /// the block being defined.
1789 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1790                                                  LocTy Loc) {
1791   BasicBlock *BB;
1792   if (Name.empty())
1793     BB = GetBB(NumberedVals.size(), Loc);
1794   else
1795     BB = GetBB(Name, Loc);
1796   if (BB == 0) return 0; // Already diagnosed error.
1797
1798   // Move the block to the end of the function.  Forward ref'd blocks are
1799   // inserted wherever they happen to be referenced.
1800   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1801
1802   // Remove the block from forward ref sets.
1803   if (Name.empty()) {
1804     ForwardRefValIDs.erase(NumberedVals.size());
1805     NumberedVals.push_back(BB);
1806   } else {
1807     // BB forward references are already in the function symbol table.
1808     ForwardRefVals.erase(Name);
1809   }
1810
1811   return BB;
1812 }
1813
1814 //===----------------------------------------------------------------------===//
1815 // Constants.
1816 //===----------------------------------------------------------------------===//
1817
1818 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1819 /// type implied.  For example, if we parse "4" we don't know what integer type
1820 /// it has.  The value will later be combined with its type and checked for
1821 /// sanity.
1822 bool LLParser::ParseValID(ValID &ID) {
1823   ID.Loc = Lex.getLoc();
1824   switch (Lex.getKind()) {
1825   default: return TokError("expected value token");
1826   case lltok::GlobalID:  // @42
1827     ID.UIntVal = Lex.getUIntVal();
1828     ID.Kind = ValID::t_GlobalID;
1829     break;
1830   case lltok::GlobalVar:  // @foo
1831     ID.StrVal = Lex.getStrVal();
1832     ID.Kind = ValID::t_GlobalName;
1833     break;
1834   case lltok::LocalVarID:  // %42
1835     ID.UIntVal = Lex.getUIntVal();
1836     ID.Kind = ValID::t_LocalID;
1837     break;
1838   case lltok::LocalVar:  // %foo
1839   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1840     ID.StrVal = Lex.getStrVal();
1841     ID.Kind = ValID::t_LocalName;
1842     break;
1843   case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1844     ID.Kind = ValID::t_Metadata;
1845     Lex.Lex();
1846     if (Lex.getKind() == lltok::lbrace) {
1847       SmallVector<Value*, 16> Elts;
1848       if (ParseMDNodeVector(Elts) ||
1849           ParseToken(lltok::rbrace, "expected end of metadata node"))
1850         return true;
1851
1852       ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1853       return false;
1854     }
1855
1856     // Standalone metadata reference
1857     // !{ ..., !42, ... }
1858     if (!ParseMDNode(ID.MetadataVal))
1859       return false;
1860
1861     // MDString:
1862     //   ::= '!' STRINGCONSTANT
1863     if (ParseMDString(ID.MetadataVal)) return true;
1864     ID.Kind = ValID::t_Metadata;
1865     return false;
1866   }
1867   case lltok::APSInt:
1868     ID.APSIntVal = Lex.getAPSIntVal();
1869     ID.Kind = ValID::t_APSInt;
1870     break;
1871   case lltok::APFloat:
1872     ID.APFloatVal = Lex.getAPFloatVal();
1873     ID.Kind = ValID::t_APFloat;
1874     break;
1875   case lltok::kw_true:
1876     ID.ConstantVal = ConstantInt::getTrue(Context);
1877     ID.Kind = ValID::t_Constant;
1878     break;
1879   case lltok::kw_false:
1880     ID.ConstantVal = ConstantInt::getFalse(Context);
1881     ID.Kind = ValID::t_Constant;
1882     break;
1883   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1884   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1885   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1886
1887   case lltok::lbrace: {
1888     // ValID ::= '{' ConstVector '}'
1889     Lex.Lex();
1890     SmallVector<Constant*, 16> Elts;
1891     if (ParseGlobalValueVector(Elts) ||
1892         ParseToken(lltok::rbrace, "expected end of struct constant"))
1893       return true;
1894
1895     ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1896                                          Elts.size(), false);
1897     ID.Kind = ValID::t_Constant;
1898     return false;
1899   }
1900   case lltok::less: {
1901     // ValID ::= '<' ConstVector '>'         --> Vector.
1902     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1903     Lex.Lex();
1904     bool isPackedStruct = EatIfPresent(lltok::lbrace);
1905
1906     SmallVector<Constant*, 16> Elts;
1907     LocTy FirstEltLoc = Lex.getLoc();
1908     if (ParseGlobalValueVector(Elts) ||
1909         (isPackedStruct &&
1910          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1911         ParseToken(lltok::greater, "expected end of constant"))
1912       return true;
1913
1914     if (isPackedStruct) {
1915       ID.ConstantVal =
1916         ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1917       ID.Kind = ValID::t_Constant;
1918       return false;
1919     }
1920
1921     if (Elts.empty())
1922       return Error(ID.Loc, "constant vector must not be empty");
1923
1924     if (!Elts[0]->getType()->isInteger() &&
1925         !Elts[0]->getType()->isFloatingPoint())
1926       return Error(FirstEltLoc,
1927                    "vector elements must have integer or floating point type");
1928
1929     // Verify that all the vector elements have the same type.
1930     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1931       if (Elts[i]->getType() != Elts[0]->getType())
1932         return Error(FirstEltLoc,
1933                      "vector element #" + utostr(i) +
1934                     " is not of type '" + Elts[0]->getType()->getDescription());
1935
1936     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1937     ID.Kind = ValID::t_Constant;
1938     return false;
1939   }
1940   case lltok::lsquare: {   // Array Constant
1941     Lex.Lex();
1942     SmallVector<Constant*, 16> Elts;
1943     LocTy FirstEltLoc = Lex.getLoc();
1944     if (ParseGlobalValueVector(Elts) ||
1945         ParseToken(lltok::rsquare, "expected end of array constant"))
1946       return true;
1947
1948     // Handle empty element.
1949     if (Elts.empty()) {
1950       // Use undef instead of an array because it's inconvenient to determine
1951       // the element type at this point, there being no elements to examine.
1952       ID.Kind = ValID::t_EmptyArray;
1953       return false;
1954     }
1955
1956     if (!Elts[0]->getType()->isFirstClassType())
1957       return Error(FirstEltLoc, "invalid array element type: " +
1958                    Elts[0]->getType()->getDescription());
1959
1960     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1961
1962     // Verify all elements are correct type!
1963     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1964       if (Elts[i]->getType() != Elts[0]->getType())
1965         return Error(FirstEltLoc,
1966                      "array element #" + utostr(i) +
1967                      " is not of type '" +Elts[0]->getType()->getDescription());
1968     }
1969
1970     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1971     ID.Kind = ValID::t_Constant;
1972     return false;
1973   }
1974   case lltok::kw_c:  // c "foo"
1975     Lex.Lex();
1976     ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
1977     if (ParseToken(lltok::StringConstant, "expected string")) return true;
1978     ID.Kind = ValID::t_Constant;
1979     return false;
1980
1981   case lltok::kw_asm: {
1982     // ValID ::= 'asm' SideEffect? MsAsm? STRINGCONSTANT ',' STRINGCONSTANT
1983     bool HasSideEffect, MsAsm;
1984     Lex.Lex();
1985     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1986         ParseOptionalToken(lltok::kw_msasm, MsAsm) ||
1987         ParseStringConstant(ID.StrVal) ||
1988         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1989         ParseToken(lltok::StringConstant, "expected constraint string"))
1990       return true;
1991     ID.StrVal2 = Lex.getStrVal();
1992     ID.UIntVal = HasSideEffect | ((unsigned)MsAsm<<1);
1993     ID.Kind = ValID::t_InlineAsm;
1994     return false;
1995   }
1996
1997   case lltok::kw_trunc:
1998   case lltok::kw_zext:
1999   case lltok::kw_sext:
2000   case lltok::kw_fptrunc:
2001   case lltok::kw_fpext:
2002   case lltok::kw_bitcast:
2003   case lltok::kw_uitofp:
2004   case lltok::kw_sitofp:
2005   case lltok::kw_fptoui:
2006   case lltok::kw_fptosi:
2007   case lltok::kw_inttoptr:
2008   case lltok::kw_ptrtoint: {
2009     unsigned Opc = Lex.getUIntVal();
2010     PATypeHolder DestTy(Type::getVoidTy(Context));
2011     Constant *SrcVal;
2012     Lex.Lex();
2013     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2014         ParseGlobalTypeAndValue(SrcVal) ||
2015         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2016         ParseType(DestTy) ||
2017         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2018       return true;
2019     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2020       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2021                    SrcVal->getType()->getDescription() + "' to '" +
2022                    DestTy->getDescription() + "'");
2023     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2024                                                  SrcVal, DestTy);
2025     ID.Kind = ValID::t_Constant;
2026     return false;
2027   }
2028   case lltok::kw_extractvalue: {
2029     Lex.Lex();
2030     Constant *Val;
2031     SmallVector<unsigned, 4> Indices;
2032     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2033         ParseGlobalTypeAndValue(Val) ||
2034         ParseIndexList(Indices) ||
2035         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2036       return true;
2037     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2038       return Error(ID.Loc, "extractvalue operand must be array or struct");
2039     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2040                                           Indices.end()))
2041       return Error(ID.Loc, "invalid indices for extractvalue");
2042     ID.ConstantVal =
2043       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2044     ID.Kind = ValID::t_Constant;
2045     return false;
2046   }
2047   case lltok::kw_insertvalue: {
2048     Lex.Lex();
2049     Constant *Val0, *Val1;
2050     SmallVector<unsigned, 4> Indices;
2051     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2052         ParseGlobalTypeAndValue(Val0) ||
2053         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2054         ParseGlobalTypeAndValue(Val1) ||
2055         ParseIndexList(Indices) ||
2056         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2057       return true;
2058     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2059       return Error(ID.Loc, "extractvalue operand must be array or struct");
2060     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2061                                           Indices.end()))
2062       return Error(ID.Loc, "invalid indices for insertvalue");
2063     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2064                        Indices.data(), Indices.size());
2065     ID.Kind = ValID::t_Constant;
2066     return false;
2067   }
2068   case lltok::kw_icmp:
2069   case lltok::kw_fcmp: {
2070     unsigned PredVal, Opc = Lex.getUIntVal();
2071     Constant *Val0, *Val1;
2072     Lex.Lex();
2073     if (ParseCmpPredicate(PredVal, Opc) ||
2074         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2075         ParseGlobalTypeAndValue(Val0) ||
2076         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2077         ParseGlobalTypeAndValue(Val1) ||
2078         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2079       return true;
2080
2081     if (Val0->getType() != Val1->getType())
2082       return Error(ID.Loc, "compare operands must have the same type");
2083
2084     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2085
2086     if (Opc == Instruction::FCmp) {
2087       if (!Val0->getType()->isFPOrFPVector())
2088         return Error(ID.Loc, "fcmp requires floating point operands");
2089       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2090     } else {
2091       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2092       if (!Val0->getType()->isIntOrIntVector() &&
2093           !isa<PointerType>(Val0->getType()))
2094         return Error(ID.Loc, "icmp requires pointer or integer operands");
2095       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2096     }
2097     ID.Kind = ValID::t_Constant;
2098     return false;
2099   }
2100
2101   // Binary Operators.
2102   case lltok::kw_add:
2103   case lltok::kw_fadd:
2104   case lltok::kw_sub:
2105   case lltok::kw_fsub:
2106   case lltok::kw_mul:
2107   case lltok::kw_fmul:
2108   case lltok::kw_udiv:
2109   case lltok::kw_sdiv:
2110   case lltok::kw_fdiv:
2111   case lltok::kw_urem:
2112   case lltok::kw_srem:
2113   case lltok::kw_frem: {
2114     bool NUW = false;
2115     bool NSW = false;
2116     bool Exact = false;
2117     unsigned Opc = Lex.getUIntVal();
2118     Constant *Val0, *Val1;
2119     Lex.Lex();
2120     LocTy ModifierLoc = Lex.getLoc();
2121     if (Opc == Instruction::Add ||
2122         Opc == Instruction::Sub ||
2123         Opc == Instruction::Mul) {
2124       if (EatIfPresent(lltok::kw_nuw))
2125         NUW = true;
2126       if (EatIfPresent(lltok::kw_nsw)) {
2127         NSW = true;
2128         if (EatIfPresent(lltok::kw_nuw))
2129           NUW = true;
2130       }
2131     } else if (Opc == Instruction::SDiv) {
2132       if (EatIfPresent(lltok::kw_exact))
2133         Exact = true;
2134     }
2135     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2136         ParseGlobalTypeAndValue(Val0) ||
2137         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2138         ParseGlobalTypeAndValue(Val1) ||
2139         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2140       return true;
2141     if (Val0->getType() != Val1->getType())
2142       return Error(ID.Loc, "operands of constexpr must have same type");
2143     if (!Val0->getType()->isIntOrIntVector()) {
2144       if (NUW)
2145         return Error(ModifierLoc, "nuw only applies to integer operations");
2146       if (NSW)
2147         return Error(ModifierLoc, "nsw only applies to integer operations");
2148     }
2149     // API compatibility: Accept either integer or floating-point types with
2150     // add, sub, and mul.
2151     if (!Val0->getType()->isIntOrIntVector() &&
2152         !Val0->getType()->isFPOrFPVector())
2153       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2154     unsigned Flags = 0;
2155     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2156     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2157     if (Exact) Flags |= SDivOperator::IsExact;
2158     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2159     ID.ConstantVal = C;
2160     ID.Kind = ValID::t_Constant;
2161     return false;
2162   }
2163
2164   // Logical Operations
2165   case lltok::kw_shl:
2166   case lltok::kw_lshr:
2167   case lltok::kw_ashr:
2168   case lltok::kw_and:
2169   case lltok::kw_or:
2170   case lltok::kw_xor: {
2171     unsigned Opc = Lex.getUIntVal();
2172     Constant *Val0, *Val1;
2173     Lex.Lex();
2174     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2175         ParseGlobalTypeAndValue(Val0) ||
2176         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2177         ParseGlobalTypeAndValue(Val1) ||
2178         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2179       return true;
2180     if (Val0->getType() != Val1->getType())
2181       return Error(ID.Loc, "operands of constexpr must have same type");
2182     if (!Val0->getType()->isIntOrIntVector())
2183       return Error(ID.Loc,
2184                    "constexpr requires integer or integer vector operands");
2185     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2186     ID.Kind = ValID::t_Constant;
2187     return false;
2188   }
2189
2190   case lltok::kw_getelementptr:
2191   case lltok::kw_shufflevector:
2192   case lltok::kw_insertelement:
2193   case lltok::kw_extractelement:
2194   case lltok::kw_select: {
2195     unsigned Opc = Lex.getUIntVal();
2196     SmallVector<Constant*, 16> Elts;
2197     bool InBounds = false;
2198     Lex.Lex();
2199     if (Opc == Instruction::GetElementPtr)
2200       InBounds = EatIfPresent(lltok::kw_inbounds);
2201     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2202         ParseGlobalValueVector(Elts) ||
2203         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2204       return true;
2205
2206     if (Opc == Instruction::GetElementPtr) {
2207       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2208         return Error(ID.Loc, "getelementptr requires pointer operand");
2209
2210       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2211                                              (Value**)(Elts.data() + 1),
2212                                              Elts.size() - 1))
2213         return Error(ID.Loc, "invalid indices for getelementptr");
2214       ID.ConstantVal = InBounds ?
2215         ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2216                                                Elts.data() + 1,
2217                                                Elts.size() - 1) :
2218         ConstantExpr::getGetElementPtr(Elts[0],
2219                                        Elts.data() + 1, Elts.size() - 1);
2220     } else if (Opc == Instruction::Select) {
2221       if (Elts.size() != 3)
2222         return Error(ID.Loc, "expected three operands to select");
2223       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2224                                                               Elts[2]))
2225         return Error(ID.Loc, Reason);
2226       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2227     } else if (Opc == Instruction::ShuffleVector) {
2228       if (Elts.size() != 3)
2229         return Error(ID.Loc, "expected three operands to shufflevector");
2230       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2231         return Error(ID.Loc, "invalid operands to shufflevector");
2232       ID.ConstantVal =
2233                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2234     } else if (Opc == Instruction::ExtractElement) {
2235       if (Elts.size() != 2)
2236         return Error(ID.Loc, "expected two operands to extractelement");
2237       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2238         return Error(ID.Loc, "invalid extractelement operands");
2239       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2240     } else {
2241       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2242       if (Elts.size() != 3)
2243       return Error(ID.Loc, "expected three operands to insertelement");
2244       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2245         return Error(ID.Loc, "invalid insertelement operands");
2246       ID.ConstantVal =
2247                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2248     }
2249
2250     ID.Kind = ValID::t_Constant;
2251     return false;
2252   }
2253   }
2254
2255   Lex.Lex();
2256   return false;
2257 }
2258
2259 /// ParseGlobalValue - Parse a global value with the specified type.
2260 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2261   V = 0;
2262   ValID ID;
2263   return ParseValID(ID) ||
2264          ConvertGlobalValIDToValue(Ty, ID, V);
2265 }
2266
2267 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2268 /// constant.
2269 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2270                                          Constant *&V) {
2271   if (isa<FunctionType>(Ty))
2272     return Error(ID.Loc, "functions are not values, refer to them as pointers");
2273
2274   switch (ID.Kind) {
2275   default: llvm_unreachable("Unknown ValID!");
2276   case ValID::t_Metadata:
2277     return Error(ID.Loc, "invalid use of metadata");
2278   case ValID::t_LocalID:
2279   case ValID::t_LocalName:
2280     return Error(ID.Loc, "invalid use of function-local name");
2281   case ValID::t_InlineAsm:
2282     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2283   case ValID::t_GlobalName:
2284     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2285     return V == 0;
2286   case ValID::t_GlobalID:
2287     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2288     return V == 0;
2289   case ValID::t_APSInt:
2290     if (!isa<IntegerType>(Ty))
2291       return Error(ID.Loc, "integer constant must have integer type");
2292     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2293     V = ConstantInt::get(Context, ID.APSIntVal);
2294     return false;
2295   case ValID::t_APFloat:
2296     if (!Ty->isFloatingPoint() ||
2297         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2298       return Error(ID.Loc, "floating point constant invalid for type");
2299
2300     // The lexer has no type info, so builds all float and double FP constants
2301     // as double.  Fix this here.  Long double does not need this.
2302     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2303         Ty->isFloatTy()) {
2304       bool Ignored;
2305       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2306                             &Ignored);
2307     }
2308     V = ConstantFP::get(Context, ID.APFloatVal);
2309
2310     if (V->getType() != Ty)
2311       return Error(ID.Loc, "floating point constant does not have type '" +
2312                    Ty->getDescription() + "'");
2313
2314     return false;
2315   case ValID::t_Null:
2316     if (!isa<PointerType>(Ty))
2317       return Error(ID.Loc, "null must be a pointer type");
2318     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2319     return false;
2320   case ValID::t_Undef:
2321     // FIXME: LabelTy should not be a first-class type.
2322     if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2323         !isa<OpaqueType>(Ty))
2324       return Error(ID.Loc, "invalid type for undef constant");
2325     V = UndefValue::get(Ty);
2326     return false;
2327   case ValID::t_EmptyArray:
2328     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2329       return Error(ID.Loc, "invalid empty array initializer");
2330     V = UndefValue::get(Ty);
2331     return false;
2332   case ValID::t_Zero:
2333     // FIXME: LabelTy should not be a first-class type.
2334     if (!Ty->isFirstClassType() || Ty->isLabelTy())
2335       return Error(ID.Loc, "invalid type for null constant");
2336     V = Constant::getNullValue(Ty);
2337     return false;
2338   case ValID::t_Constant:
2339     if (ID.ConstantVal->getType() != Ty)
2340       return Error(ID.Loc, "constant expression type mismatch");
2341     V = ID.ConstantVal;
2342     return false;
2343   }
2344 }
2345
2346 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2347   PATypeHolder Type(Type::getVoidTy(Context));
2348   return ParseType(Type) ||
2349          ParseGlobalValue(Type, V);
2350 }
2351
2352 /// ParseGlobalValueVector
2353 ///   ::= /*empty*/
2354 ///   ::= TypeAndValue (',' TypeAndValue)*
2355 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2356   // Empty list.
2357   if (Lex.getKind() == lltok::rbrace ||
2358       Lex.getKind() == lltok::rsquare ||
2359       Lex.getKind() == lltok::greater ||
2360       Lex.getKind() == lltok::rparen)
2361     return false;
2362
2363   Constant *C;
2364   if (ParseGlobalTypeAndValue(C)) return true;
2365   Elts.push_back(C);
2366
2367   while (EatIfPresent(lltok::comma)) {
2368     if (ParseGlobalTypeAndValue(C)) return true;
2369     Elts.push_back(C);
2370   }
2371
2372   return false;
2373 }
2374
2375
2376 //===----------------------------------------------------------------------===//
2377 // Function Parsing.
2378 //===----------------------------------------------------------------------===//
2379
2380 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2381                                    PerFunctionState &PFS) {
2382   if (ID.Kind == ValID::t_LocalID)
2383     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2384   else if (ID.Kind == ValID::t_LocalName)
2385     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2386   else if (ID.Kind == ValID::t_InlineAsm) {
2387     const PointerType *PTy = dyn_cast<PointerType>(Ty);
2388     const FunctionType *FTy =
2389       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2390     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2391       return Error(ID.Loc, "invalid type for inline asm constraint string");
2392     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2393     return false;
2394   } else if (ID.Kind == ValID::t_Metadata) {
2395     V = ID.MetadataVal;
2396   } else {
2397     Constant *C;
2398     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2399     V = C;
2400     return false;
2401   }
2402
2403   return V == 0;
2404 }
2405
2406 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2407   V = 0;
2408   ValID ID;
2409   return ParseValID(ID) ||
2410          ConvertValIDToValue(Ty, ID, V, PFS);
2411 }
2412
2413 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2414   PATypeHolder T(Type::getVoidTy(Context));
2415   return ParseType(T) ||
2416          ParseValue(T, V, PFS);
2417 }
2418
2419 /// FunctionHeader
2420 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2421 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2422 ///       OptionalAlign OptGC
2423 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2424   // Parse the linkage.
2425   LocTy LinkageLoc = Lex.getLoc();
2426   unsigned Linkage;
2427
2428   unsigned Visibility, RetAttrs;
2429   CallingConv::ID CC;
2430   PATypeHolder RetType(Type::getVoidTy(Context));
2431   LocTy RetTypeLoc = Lex.getLoc();
2432   if (ParseOptionalLinkage(Linkage) ||
2433       ParseOptionalVisibility(Visibility) ||
2434       ParseOptionalCallingConv(CC) ||
2435       ParseOptionalAttrs(RetAttrs, 1) ||
2436       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2437     return true;
2438
2439   // Verify that the linkage is ok.
2440   switch ((GlobalValue::LinkageTypes)Linkage) {
2441   case GlobalValue::ExternalLinkage:
2442     break; // always ok.
2443   case GlobalValue::DLLImportLinkage:
2444   case GlobalValue::ExternalWeakLinkage:
2445     if (isDefine)
2446       return Error(LinkageLoc, "invalid linkage for function definition");
2447     break;
2448   case GlobalValue::PrivateLinkage:
2449   case GlobalValue::LinkerPrivateLinkage:
2450   case GlobalValue::InternalLinkage:
2451   case GlobalValue::AvailableExternallyLinkage:
2452   case GlobalValue::LinkOnceAnyLinkage:
2453   case GlobalValue::LinkOnceODRLinkage:
2454   case GlobalValue::WeakAnyLinkage:
2455   case GlobalValue::WeakODRLinkage:
2456   case GlobalValue::DLLExportLinkage:
2457     if (!isDefine)
2458       return Error(LinkageLoc, "invalid linkage for function declaration");
2459     break;
2460   case GlobalValue::AppendingLinkage:
2461   case GlobalValue::GhostLinkage:
2462   case GlobalValue::CommonLinkage:
2463     return Error(LinkageLoc, "invalid function linkage type");
2464   }
2465
2466   if (!FunctionType::isValidReturnType(RetType) ||
2467       isa<OpaqueType>(RetType))
2468     return Error(RetTypeLoc, "invalid function return type");
2469
2470   LocTy NameLoc = Lex.getLoc();
2471
2472   std::string FunctionName;
2473   if (Lex.getKind() == lltok::GlobalVar) {
2474     FunctionName = Lex.getStrVal();
2475   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2476     unsigned NameID = Lex.getUIntVal();
2477
2478     if (NameID != NumberedVals.size())
2479       return TokError("function expected to be numbered '%" +
2480                       utostr(NumberedVals.size()) + "'");
2481   } else {
2482     return TokError("expected function name");
2483   }
2484
2485   Lex.Lex();
2486
2487   if (Lex.getKind() != lltok::lparen)
2488     return TokError("expected '(' in function argument list");
2489
2490   std::vector<ArgInfo> ArgList;
2491   bool isVarArg;
2492   unsigned FuncAttrs;
2493   std::string Section;
2494   unsigned Alignment;
2495   std::string GC;
2496
2497   if (ParseArgumentList(ArgList, isVarArg, false) ||
2498       ParseOptionalAttrs(FuncAttrs, 2) ||
2499       (EatIfPresent(lltok::kw_section) &&
2500        ParseStringConstant(Section)) ||
2501       ParseOptionalAlignment(Alignment) ||
2502       (EatIfPresent(lltok::kw_gc) &&
2503        ParseStringConstant(GC)))
2504     return true;
2505
2506   // If the alignment was parsed as an attribute, move to the alignment field.
2507   if (FuncAttrs & Attribute::Alignment) {
2508     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2509     FuncAttrs &= ~Attribute::Alignment;
2510   }
2511
2512   // Okay, if we got here, the function is syntactically valid.  Convert types
2513   // and do semantic checks.
2514   std::vector<const Type*> ParamTypeList;
2515   SmallVector<AttributeWithIndex, 8> Attrs;
2516   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2517   // attributes.
2518   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2519   if (FuncAttrs & ObsoleteFuncAttrs) {
2520     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2521     FuncAttrs &= ~ObsoleteFuncAttrs;
2522   }
2523
2524   if (RetAttrs != Attribute::None)
2525     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2526
2527   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2528     ParamTypeList.push_back(ArgList[i].Type);
2529     if (ArgList[i].Attrs != Attribute::None)
2530       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2531   }
2532
2533   if (FuncAttrs != Attribute::None)
2534     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2535
2536   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2537
2538   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2539       RetType != Type::getVoidTy(Context))
2540     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2541
2542   const FunctionType *FT =
2543     FunctionType::get(RetType, ParamTypeList, isVarArg);
2544   const PointerType *PFT = PointerType::getUnqual(FT);
2545
2546   Fn = 0;
2547   if (!FunctionName.empty()) {
2548     // If this was a definition of a forward reference, remove the definition
2549     // from the forward reference table and fill in the forward ref.
2550     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2551       ForwardRefVals.find(FunctionName);
2552     if (FRVI != ForwardRefVals.end()) {
2553       Fn = M->getFunction(FunctionName);
2554       ForwardRefVals.erase(FRVI);
2555     } else if ((Fn = M->getFunction(FunctionName))) {
2556       // If this function already exists in the symbol table, then it is
2557       // multiply defined.  We accept a few cases for old backwards compat.
2558       // FIXME: Remove this stuff for LLVM 3.0.
2559       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2560           (!Fn->isDeclaration() && isDefine)) {
2561         // If the redefinition has different type or different attributes,
2562         // reject it.  If both have bodies, reject it.
2563         return Error(NameLoc, "invalid redefinition of function '" +
2564                      FunctionName + "'");
2565       } else if (Fn->isDeclaration()) {
2566         // Make sure to strip off any argument names so we can't get conflicts.
2567         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2568              AI != AE; ++AI)
2569           AI->setName("");
2570       }
2571     }
2572
2573   } else {
2574     // If this is a definition of a forward referenced function, make sure the
2575     // types agree.
2576     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2577       = ForwardRefValIDs.find(NumberedVals.size());
2578     if (I != ForwardRefValIDs.end()) {
2579       Fn = cast<Function>(I->second.first);
2580       if (Fn->getType() != PFT)
2581         return Error(NameLoc, "type of definition and forward reference of '@" +
2582                      utostr(NumberedVals.size()) +"' disagree");
2583       ForwardRefValIDs.erase(I);
2584     }
2585   }
2586
2587   if (Fn == 0)
2588     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2589   else // Move the forward-reference to the correct spot in the module.
2590     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2591
2592   if (FunctionName.empty())
2593     NumberedVals.push_back(Fn);
2594
2595   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2596   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2597   Fn->setCallingConv(CC);
2598   Fn->setAttributes(PAL);
2599   Fn->setAlignment(Alignment);
2600   Fn->setSection(Section);
2601   if (!GC.empty()) Fn->setGC(GC.c_str());
2602
2603   // Add all of the arguments we parsed to the function.
2604   Function::arg_iterator ArgIt = Fn->arg_begin();
2605   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2606     // If the argument has a name, insert it into the argument symbol table.
2607     if (ArgList[i].Name.empty()) continue;
2608
2609     // Set the name, if it conflicted, it will be auto-renamed.
2610     ArgIt->setName(ArgList[i].Name);
2611
2612     if (ArgIt->getNameStr() != ArgList[i].Name)
2613       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2614                    ArgList[i].Name + "'");
2615   }
2616
2617   return false;
2618 }
2619
2620
2621 /// ParseFunctionBody
2622 ///   ::= '{' BasicBlock+ '}'
2623 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2624 ///
2625 bool LLParser::ParseFunctionBody(Function &Fn) {
2626   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2627     return TokError("expected '{' in function body");
2628   Lex.Lex();  // eat the {.
2629
2630   PerFunctionState PFS(*this, Fn);
2631
2632   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2633     if (ParseBasicBlock(PFS)) return true;
2634
2635   // Eat the }.
2636   Lex.Lex();
2637
2638   // Verify function is ok.
2639   return PFS.VerifyFunctionComplete();
2640 }
2641
2642 /// ParseBasicBlock
2643 ///   ::= LabelStr? Instruction*
2644 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2645   // If this basic block starts out with a name, remember it.
2646   std::string Name;
2647   LocTy NameLoc = Lex.getLoc();
2648   if (Lex.getKind() == lltok::LabelStr) {
2649     Name = Lex.getStrVal();
2650     Lex.Lex();
2651   }
2652
2653   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2654   if (BB == 0) return true;
2655
2656   std::string NameStr;
2657
2658   // Parse the instructions in this block until we get a terminator.
2659   Instruction *Inst;
2660   do {
2661     // This instruction may have three possibilities for a name: a) none
2662     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2663     LocTy NameLoc = Lex.getLoc();
2664     int NameID = -1;
2665     NameStr = "";
2666
2667     if (Lex.getKind() == lltok::LocalVarID) {
2668       NameID = Lex.getUIntVal();
2669       Lex.Lex();
2670       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2671         return true;
2672     } else if (Lex.getKind() == lltok::LocalVar ||
2673                // FIXME: REMOVE IN LLVM 3.0
2674                Lex.getKind() == lltok::StringConstant) {
2675       NameStr = Lex.getStrVal();
2676       Lex.Lex();
2677       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2678         return true;
2679     }
2680
2681     if (ParseInstruction(Inst, BB, PFS)) return true;
2682     if (EatIfPresent(lltok::comma))
2683       ParseOptionalCustomMetadata();
2684
2685     // Set metadata attached with this instruction.
2686     MetadataContext &TheMetadata = M->getContext().getMetadata();
2687     for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2688            MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2689       TheMetadata.addMD(MDI->first, MDI->second, Inst);
2690     MDsOnInst.clear();
2691
2692     BB->getInstList().push_back(Inst);
2693
2694     // Set the name on the instruction.
2695     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2696   } while (!isa<TerminatorInst>(Inst));
2697
2698   return false;
2699 }
2700
2701 //===----------------------------------------------------------------------===//
2702 // Instruction Parsing.
2703 //===----------------------------------------------------------------------===//
2704
2705 /// ParseInstruction - Parse one of the many different instructions.
2706 ///
2707 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2708                                 PerFunctionState &PFS) {
2709   lltok::Kind Token = Lex.getKind();
2710   if (Token == lltok::Eof)
2711     return TokError("found end of file when expecting more instructions");
2712   LocTy Loc = Lex.getLoc();
2713   unsigned KeywordVal = Lex.getUIntVal();
2714   Lex.Lex();  // Eat the keyword.
2715
2716   switch (Token) {
2717   default:                    return Error(Loc, "expected instruction opcode");
2718   // Terminator Instructions.
2719   case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
2720   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2721   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2722   case lltok::kw_br:          return ParseBr(Inst, PFS);
2723   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2724   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2725   // Binary Operators.
2726   case lltok::kw_add:
2727   case lltok::kw_sub:
2728   case lltok::kw_mul: {
2729     bool NUW = false;
2730     bool NSW = false;
2731     LocTy ModifierLoc = Lex.getLoc();
2732     if (EatIfPresent(lltok::kw_nuw))
2733       NUW = true;
2734     if (EatIfPresent(lltok::kw_nsw)) {
2735       NSW = true;
2736       if (EatIfPresent(lltok::kw_nuw))
2737         NUW = true;
2738     }
2739     // API compatibility: Accept either integer or floating-point types.
2740     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2741     if (!Result) {
2742       if (!Inst->getType()->isIntOrIntVector()) {
2743         if (NUW)
2744           return Error(ModifierLoc, "nuw only applies to integer operations");
2745         if (NSW)
2746           return Error(ModifierLoc, "nsw only applies to integer operations");
2747       }
2748       if (NUW)
2749         cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2750       if (NSW)
2751         cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2752     }
2753     return Result;
2754   }
2755   case lltok::kw_fadd:
2756   case lltok::kw_fsub:
2757   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2758
2759   case lltok::kw_sdiv: {
2760     bool Exact = false;
2761     if (EatIfPresent(lltok::kw_exact))
2762       Exact = true;
2763     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2764     if (!Result)
2765       if (Exact)
2766         cast<BinaryOperator>(Inst)->setIsExact(true);
2767     return Result;
2768   }
2769
2770   case lltok::kw_udiv:
2771   case lltok::kw_urem:
2772   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2773   case lltok::kw_fdiv:
2774   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2775   case lltok::kw_shl:
2776   case lltok::kw_lshr:
2777   case lltok::kw_ashr:
2778   case lltok::kw_and:
2779   case lltok::kw_or:
2780   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2781   case lltok::kw_icmp:
2782   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2783   // Casts.
2784   case lltok::kw_trunc:
2785   case lltok::kw_zext:
2786   case lltok::kw_sext:
2787   case lltok::kw_fptrunc:
2788   case lltok::kw_fpext:
2789   case lltok::kw_bitcast:
2790   case lltok::kw_uitofp:
2791   case lltok::kw_sitofp:
2792   case lltok::kw_fptoui:
2793   case lltok::kw_fptosi:
2794   case lltok::kw_inttoptr:
2795   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2796   // Other.
2797   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2798   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2799   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2800   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2801   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2802   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2803   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2804   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2805   // Memory.
2806   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
2807   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, BB, false);
2808   case lltok::kw_free:           return ParseFree(Inst, PFS);
2809   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2810   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2811   case lltok::kw_volatile:
2812     if (EatIfPresent(lltok::kw_load))
2813       return ParseLoad(Inst, PFS, true);
2814     else if (EatIfPresent(lltok::kw_store))
2815       return ParseStore(Inst, PFS, true);
2816     else
2817       return TokError("expected 'load' or 'store'");
2818   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2819   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2820   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2821   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2822   }
2823 }
2824
2825 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2826 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2827   if (Opc == Instruction::FCmp) {
2828     switch (Lex.getKind()) {
2829     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2830     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2831     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2832     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2833     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2834     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2835     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2836     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2837     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2838     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2839     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2840     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2841     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2842     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2843     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2844     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2845     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2846     }
2847   } else {
2848     switch (Lex.getKind()) {
2849     default: TokError("expected icmp predicate (e.g. 'eq')");
2850     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2851     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2852     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2853     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2854     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2855     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2856     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2857     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2858     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2859     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2860     }
2861   }
2862   Lex.Lex();
2863   return false;
2864 }
2865
2866 //===----------------------------------------------------------------------===//
2867 // Terminator Instructions.
2868 //===----------------------------------------------------------------------===//
2869
2870 /// ParseRet - Parse a return instruction.
2871 ///   ::= 'ret' void (',' !dbg, !1)
2872 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)
2873 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  (',' !dbg, !1)
2874 ///         [[obsolete: LLVM 3.0]]
2875 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2876                         PerFunctionState &PFS) {
2877   PATypeHolder Ty(Type::getVoidTy(Context));
2878   if (ParseType(Ty, true /*void allowed*/)) return true;
2879
2880   if (Ty->isVoidTy()) {
2881     Inst = ReturnInst::Create(Context);
2882     return false;
2883   }
2884
2885   Value *RV;
2886   if (ParseValue(Ty, RV, PFS)) return true;
2887
2888   if (EatIfPresent(lltok::comma)) {
2889     // Parse optional custom metadata, e.g. !dbg
2890     if (Lex.getKind() == lltok::NamedOrCustomMD) {
2891       if (ParseOptionalCustomMetadata()) return true;
2892     } else {
2893       // The normal case is one return value.
2894       // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2895       // of 'ret {i32,i32} {i32 1, i32 2}'
2896       SmallVector<Value*, 8> RVs;
2897       RVs.push_back(RV);
2898
2899       do {
2900         // If optional custom metadata, e.g. !dbg is seen then this is the 
2901         // end of MRV.
2902         if (Lex.getKind() == lltok::NamedOrCustomMD)
2903           break;
2904         if (ParseTypeAndValue(RV, PFS)) return true;
2905         RVs.push_back(RV);
2906       } while (EatIfPresent(lltok::comma));
2907
2908       RV = UndefValue::get(PFS.getFunction().getReturnType());
2909       for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2910         Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2911         BB->getInstList().push_back(I);
2912         RV = I;
2913       }
2914     }
2915   }
2916
2917   Inst = ReturnInst::Create(Context, RV);
2918   return false;
2919 }
2920
2921
2922 /// ParseBr
2923 ///   ::= 'br' TypeAndValue
2924 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2925 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2926   LocTy Loc, Loc2;
2927   Value *Op0, *Op1, *Op2;
2928   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2929
2930   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2931     Inst = BranchInst::Create(BB);
2932     return false;
2933   }
2934
2935   if (Op0->getType() != Type::getInt1Ty(Context))
2936     return Error(Loc, "branch condition must have 'i1' type");
2937
2938   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2939       ParseTypeAndValue(Op1, Loc, PFS) ||
2940       ParseToken(lltok::comma, "expected ',' after true destination") ||
2941       ParseTypeAndValue(Op2, Loc2, PFS))
2942     return true;
2943
2944   if (!isa<BasicBlock>(Op1))
2945     return Error(Loc, "true destination of branch must be a basic block");
2946   if (!isa<BasicBlock>(Op2))
2947     return Error(Loc2, "true destination of branch must be a basic block");
2948
2949   Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2950   return false;
2951 }
2952
2953 /// ParseSwitch
2954 ///  Instruction
2955 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2956 ///  JumpTable
2957 ///    ::= (TypeAndValue ',' TypeAndValue)*
2958 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2959   LocTy CondLoc, BBLoc;
2960   Value *Cond, *DefaultBB;
2961   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2962       ParseToken(lltok::comma, "expected ',' after switch condition") ||
2963       ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2964       ParseToken(lltok::lsquare, "expected '[' with switch table"))
2965     return true;
2966
2967   if (!isa<IntegerType>(Cond->getType()))
2968     return Error(CondLoc, "switch condition must have integer type");
2969   if (!isa<BasicBlock>(DefaultBB))
2970     return Error(BBLoc, "default destination must be a basic block");
2971
2972   // Parse the jump table pairs.
2973   SmallPtrSet<Value*, 32> SeenCases;
2974   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2975   while (Lex.getKind() != lltok::rsquare) {
2976     Value *Constant, *DestBB;
2977
2978     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2979         ParseToken(lltok::comma, "expected ',' after case value") ||
2980         ParseTypeAndValue(DestBB, BBLoc, PFS))
2981       return true;
2982
2983     if (!SeenCases.insert(Constant))
2984       return Error(CondLoc, "duplicate case value in switch");
2985     if (!isa<ConstantInt>(Constant))
2986       return Error(CondLoc, "case value is not a constant integer");
2987     if (!isa<BasicBlock>(DestBB))
2988       return Error(BBLoc, "case destination is not a basic block");
2989
2990     Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2991                                    cast<BasicBlock>(DestBB)));
2992   }
2993
2994   Lex.Lex();  // Eat the ']'.
2995
2996   SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2997                                       Table.size());
2998   for (unsigned i = 0, e = Table.size(); i != e; ++i)
2999     SI->addCase(Table[i].first, Table[i].second);
3000   Inst = SI;
3001   return false;
3002 }
3003
3004 /// ParseInvoke
3005 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3006 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3007 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3008   LocTy CallLoc = Lex.getLoc();
3009   unsigned RetAttrs, FnAttrs;
3010   CallingConv::ID CC;
3011   PATypeHolder RetType(Type::getVoidTy(Context));
3012   LocTy RetTypeLoc;
3013   ValID CalleeID;
3014   SmallVector<ParamInfo, 16> ArgList;
3015
3016   Value *NormalBB, *UnwindBB;
3017   if (ParseOptionalCallingConv(CC) ||
3018       ParseOptionalAttrs(RetAttrs, 1) ||
3019       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3020       ParseValID(CalleeID) ||
3021       ParseParameterList(ArgList, PFS) ||
3022       ParseOptionalAttrs(FnAttrs, 2) ||
3023       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3024       ParseTypeAndValue(NormalBB, PFS) ||
3025       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3026       ParseTypeAndValue(UnwindBB, PFS))
3027     return true;
3028
3029   if (!isa<BasicBlock>(NormalBB))
3030     return Error(CallLoc, "normal destination is not a basic block");
3031   if (!isa<BasicBlock>(UnwindBB))
3032     return Error(CallLoc, "unwind destination is not a basic block");
3033
3034   // If RetType is a non-function pointer type, then this is the short syntax
3035   // for the call, which means that RetType is just the return type.  Infer the
3036   // rest of the function argument types from the arguments that are present.
3037   const PointerType *PFTy = 0;
3038   const FunctionType *Ty = 0;
3039   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3040       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3041     // Pull out the types of all of the arguments...
3042     std::vector<const Type*> ParamTypes;
3043     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3044       ParamTypes.push_back(ArgList[i].V->getType());
3045
3046     if (!FunctionType::isValidReturnType(RetType))
3047       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3048
3049     Ty = FunctionType::get(RetType, ParamTypes, false);
3050     PFTy = PointerType::getUnqual(Ty);
3051   }
3052
3053   // Look up the callee.
3054   Value *Callee;
3055   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3056
3057   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3058   // function attributes.
3059   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3060   if (FnAttrs & ObsoleteFuncAttrs) {
3061     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3062     FnAttrs &= ~ObsoleteFuncAttrs;
3063   }
3064
3065   // Set up the Attributes for the function.
3066   SmallVector<AttributeWithIndex, 8> Attrs;
3067   if (RetAttrs != Attribute::None)
3068     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3069
3070   SmallVector<Value*, 8> Args;
3071
3072   // Loop through FunctionType's arguments and ensure they are specified
3073   // correctly.  Also, gather any parameter attributes.
3074   FunctionType::param_iterator I = Ty->param_begin();
3075   FunctionType::param_iterator E = Ty->param_end();
3076   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3077     const Type *ExpectedTy = 0;
3078     if (I != E) {
3079       ExpectedTy = *I++;
3080     } else if (!Ty->isVarArg()) {
3081       return Error(ArgList[i].Loc, "too many arguments specified");
3082     }
3083
3084     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3085       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3086                    ExpectedTy->getDescription() + "'");
3087     Args.push_back(ArgList[i].V);
3088     if (ArgList[i].Attrs != Attribute::None)
3089       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3090   }
3091
3092   if (I != E)
3093     return Error(CallLoc, "not enough parameters specified for call");
3094
3095   if (FnAttrs != Attribute::None)
3096     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3097
3098   // Finish off the Attributes and check them
3099   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3100
3101   InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3102                                       cast<BasicBlock>(UnwindBB),
3103                                       Args.begin(), Args.end());
3104   II->setCallingConv(CC);
3105   II->setAttributes(PAL);
3106   Inst = II;
3107   return false;
3108 }
3109
3110
3111
3112 //===----------------------------------------------------------------------===//
3113 // Binary Operators.
3114 //===----------------------------------------------------------------------===//
3115
3116 /// ParseArithmetic
3117 ///  ::= ArithmeticOps TypeAndValue ',' Value
3118 ///
3119 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3120 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3121 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3122                                unsigned Opc, unsigned OperandType) {
3123   LocTy Loc; Value *LHS, *RHS;
3124   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3125       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3126       ParseValue(LHS->getType(), RHS, PFS))
3127     return true;
3128
3129   bool Valid;
3130   switch (OperandType) {
3131   default: llvm_unreachable("Unknown operand type!");
3132   case 0: // int or FP.
3133     Valid = LHS->getType()->isIntOrIntVector() ||
3134             LHS->getType()->isFPOrFPVector();
3135     break;
3136   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3137   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3138   }
3139
3140   if (!Valid)
3141     return Error(Loc, "invalid operand type for instruction");
3142
3143   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3144   return false;
3145 }
3146
3147 /// ParseLogical
3148 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3149 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3150                             unsigned Opc) {
3151   LocTy Loc; Value *LHS, *RHS;
3152   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3153       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3154       ParseValue(LHS->getType(), RHS, PFS))
3155     return true;
3156
3157   if (!LHS->getType()->isIntOrIntVector())
3158     return Error(Loc,"instruction requires integer or integer vector operands");
3159
3160   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3161   return false;
3162 }
3163
3164
3165 /// ParseCompare
3166 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3167 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3168 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3169                             unsigned Opc) {
3170   // Parse the integer/fp comparison predicate.
3171   LocTy Loc;
3172   unsigned Pred;
3173   Value *LHS, *RHS;
3174   if (ParseCmpPredicate(Pred, Opc) ||
3175       ParseTypeAndValue(LHS, Loc, PFS) ||
3176       ParseToken(lltok::comma, "expected ',' after compare value") ||
3177       ParseValue(LHS->getType(), RHS, PFS))
3178     return true;
3179
3180   if (Opc == Instruction::FCmp) {
3181     if (!LHS->getType()->isFPOrFPVector())
3182       return Error(Loc, "fcmp requires floating point operands");
3183     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3184   } else {
3185     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3186     if (!LHS->getType()->isIntOrIntVector() &&
3187         !isa<PointerType>(LHS->getType()))
3188       return Error(Loc, "icmp requires integer operands");
3189     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3190   }
3191   return false;
3192 }
3193
3194 //===----------------------------------------------------------------------===//
3195 // Other Instructions.
3196 //===----------------------------------------------------------------------===//
3197
3198
3199 /// ParseCast
3200 ///   ::= CastOpc TypeAndValue 'to' Type
3201 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3202                          unsigned Opc) {
3203   LocTy Loc;  Value *Op;
3204   PATypeHolder DestTy(Type::getVoidTy(Context));
3205   if (ParseTypeAndValue(Op, Loc, PFS) ||
3206       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3207       ParseType(DestTy))
3208     return true;
3209
3210   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3211     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3212     return Error(Loc, "invalid cast opcode for cast from '" +
3213                  Op->getType()->getDescription() + "' to '" +
3214                  DestTy->getDescription() + "'");
3215   }
3216   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3217   return false;
3218 }
3219
3220 /// ParseSelect
3221 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3222 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3223   LocTy Loc;
3224   Value *Op0, *Op1, *Op2;
3225   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3226       ParseToken(lltok::comma, "expected ',' after select condition") ||
3227       ParseTypeAndValue(Op1, PFS) ||
3228       ParseToken(lltok::comma, "expected ',' after select value") ||
3229       ParseTypeAndValue(Op2, PFS))
3230     return true;
3231
3232   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3233     return Error(Loc, Reason);
3234
3235   Inst = SelectInst::Create(Op0, Op1, Op2);
3236   return false;
3237 }
3238
3239 /// ParseVA_Arg
3240 ///   ::= 'va_arg' TypeAndValue ',' Type
3241 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3242   Value *Op;
3243   PATypeHolder EltTy(Type::getVoidTy(Context));
3244   LocTy TypeLoc;
3245   if (ParseTypeAndValue(Op, PFS) ||
3246       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3247       ParseType(EltTy, TypeLoc))
3248     return true;
3249
3250   if (!EltTy->isFirstClassType())
3251     return Error(TypeLoc, "va_arg requires operand with first class type");
3252
3253   Inst = new VAArgInst(Op, EltTy);
3254   return false;
3255 }
3256
3257 /// ParseExtractElement
3258 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3259 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3260   LocTy Loc;
3261   Value *Op0, *Op1;
3262   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3263       ParseToken(lltok::comma, "expected ',' after extract value") ||
3264       ParseTypeAndValue(Op1, PFS))
3265     return true;
3266
3267   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3268     return Error(Loc, "invalid extractelement operands");
3269
3270   Inst = ExtractElementInst::Create(Op0, Op1);
3271   return false;
3272 }
3273
3274 /// ParseInsertElement
3275 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3276 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3277   LocTy Loc;
3278   Value *Op0, *Op1, *Op2;
3279   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3280       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3281       ParseTypeAndValue(Op1, PFS) ||
3282       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3283       ParseTypeAndValue(Op2, PFS))
3284     return true;
3285
3286   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3287     return Error(Loc, "invalid insertelement operands");
3288
3289   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3290   return false;
3291 }
3292
3293 /// ParseShuffleVector
3294 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3295 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3296   LocTy Loc;
3297   Value *Op0, *Op1, *Op2;
3298   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3299       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3300       ParseTypeAndValue(Op1, PFS) ||
3301       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3302       ParseTypeAndValue(Op2, PFS))
3303     return true;
3304
3305   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3306     return Error(Loc, "invalid extractelement operands");
3307
3308   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3309   return false;
3310 }
3311
3312 /// ParsePHI
3313 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3314 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3315   PATypeHolder Ty(Type::getVoidTy(Context));
3316   Value *Op0, *Op1;
3317   LocTy TypeLoc = Lex.getLoc();
3318
3319   if (ParseType(Ty) ||
3320       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3321       ParseValue(Ty, Op0, PFS) ||
3322       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3323       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3324       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3325     return true;
3326
3327   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3328   while (1) {
3329     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3330
3331     if (!EatIfPresent(lltok::comma))
3332       break;
3333
3334     if (Lex.getKind() == lltok::NamedOrCustomMD)
3335       break;
3336
3337     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3338         ParseValue(Ty, Op0, PFS) ||
3339         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3340         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3341         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3342       return true;
3343   }
3344
3345   if (Lex.getKind() == lltok::NamedOrCustomMD)
3346     if (ParseOptionalCustomMetadata()) return true;
3347
3348   if (!Ty->isFirstClassType())
3349     return Error(TypeLoc, "phi node must have first class type");
3350
3351   PHINode *PN = PHINode::Create(Ty);
3352   PN->reserveOperandSpace(PHIVals.size());
3353   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3354     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3355   Inst = PN;
3356   return false;
3357 }
3358
3359 /// ParseCall
3360 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3361 ///       ParameterList OptionalAttrs
3362 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3363                          bool isTail) {
3364   unsigned RetAttrs, FnAttrs;
3365   CallingConv::ID CC;
3366   PATypeHolder RetType(Type::getVoidTy(Context));
3367   LocTy RetTypeLoc;
3368   ValID CalleeID;
3369   SmallVector<ParamInfo, 16> ArgList;
3370   LocTy CallLoc = Lex.getLoc();
3371
3372   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3373       ParseOptionalCallingConv(CC) ||
3374       ParseOptionalAttrs(RetAttrs, 1) ||
3375       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3376       ParseValID(CalleeID) ||
3377       ParseParameterList(ArgList, PFS) ||
3378       ParseOptionalAttrs(FnAttrs, 2))
3379     return true;
3380
3381   // If RetType is a non-function pointer type, then this is the short syntax
3382   // for the call, which means that RetType is just the return type.  Infer the
3383   // rest of the function argument types from the arguments that are present.
3384   const PointerType *PFTy = 0;
3385   const FunctionType *Ty = 0;
3386   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3387       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3388     // Pull out the types of all of the arguments...
3389     std::vector<const Type*> ParamTypes;
3390     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3391       ParamTypes.push_back(ArgList[i].V->getType());
3392
3393     if (!FunctionType::isValidReturnType(RetType))
3394       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3395
3396     Ty = FunctionType::get(RetType, ParamTypes, false);
3397     PFTy = PointerType::getUnqual(Ty);
3398   }
3399
3400   // Look up the callee.
3401   Value *Callee;
3402   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3403
3404   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3405   // function attributes.
3406   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3407   if (FnAttrs & ObsoleteFuncAttrs) {
3408     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3409     FnAttrs &= ~ObsoleteFuncAttrs;
3410   }
3411
3412   // Set up the Attributes for the function.
3413   SmallVector<AttributeWithIndex, 8> Attrs;
3414   if (RetAttrs != Attribute::None)
3415     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3416
3417   SmallVector<Value*, 8> Args;
3418
3419   // Loop through FunctionType's arguments and ensure they are specified
3420   // correctly.  Also, gather any parameter attributes.
3421   FunctionType::param_iterator I = Ty->param_begin();
3422   FunctionType::param_iterator E = Ty->param_end();
3423   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3424     const Type *ExpectedTy = 0;
3425     if (I != E) {
3426       ExpectedTy = *I++;
3427     } else if (!Ty->isVarArg()) {
3428       return Error(ArgList[i].Loc, "too many arguments specified");
3429     }
3430
3431     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3432       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3433                    ExpectedTy->getDescription() + "'");
3434     Args.push_back(ArgList[i].V);
3435     if (ArgList[i].Attrs != Attribute::None)
3436       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3437   }
3438
3439   if (I != E)
3440     return Error(CallLoc, "not enough parameters specified for call");
3441
3442   if (FnAttrs != Attribute::None)
3443     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3444
3445   // Finish off the Attributes and check them
3446   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3447
3448   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3449   CI->setTailCall(isTail);
3450   CI->setCallingConv(CC);
3451   CI->setAttributes(PAL);
3452   Inst = CI;
3453   return false;
3454 }
3455
3456 //===----------------------------------------------------------------------===//
3457 // Memory Instructions.
3458 //===----------------------------------------------------------------------===//
3459
3460 /// ParseAlloc
3461 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3462 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3463 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3464                           BasicBlock* BB, bool isAlloca) {
3465   PATypeHolder Ty(Type::getVoidTy(Context));
3466   Value *Size = 0;
3467   LocTy SizeLoc;
3468   unsigned Alignment = 0;
3469   if (ParseType(Ty)) return true;
3470
3471   if (EatIfPresent(lltok::comma)) {
3472     if (Lex.getKind() == lltok::kw_align 
3473         || Lex.getKind() == lltok::NamedOrCustomMD) {
3474       if (ParseOptionalInfo(Alignment)) return true;
3475     } else {
3476       if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3477       if (EatIfPresent(lltok::comma))
3478         if (ParseOptionalInfo(Alignment)) return true;
3479     }
3480   }
3481
3482   if (Size && Size->getType() != Type::getInt32Ty(Context))
3483     return Error(SizeLoc, "element count must be i32");
3484
3485   if (isAlloca)
3486     Inst = new AllocaInst(Ty, Size, Alignment);
3487   else {
3488     // Autoupgrade old malloc instruction to malloc call.
3489     const Type* IntPtrTy = Type::getInt32Ty(Context);
3490     const Type* Int8PtrTy = PointerType::getUnqual(Type::getInt8Ty(Context));
3491     if (!MallocF)
3492       // Prototype malloc as "void *autoupgrade_malloc(int32)".
3493       MallocF = cast<Function>(M->getOrInsertFunction("autoupgrade_malloc",
3494                                Int8PtrTy, IntPtrTy, NULL));
3495       // "autoupgrade_malloc" updated to "malloc" in ValidateEndOfModule().
3496
3497     Inst = cast<Instruction>(CallInst::CreateMalloc(BB, IntPtrTy, Ty,
3498                                                     Size, MallocF));
3499   }
3500   return false;
3501 }
3502
3503 /// ParseFree
3504 ///   ::= 'free' TypeAndValue
3505 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3506   Value *Val; LocTy Loc;
3507   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3508   if (!isa<PointerType>(Val->getType()))
3509     return Error(Loc, "operand to free must be a pointer");
3510   Inst = new FreeInst(Val);
3511   return false;
3512 }
3513
3514 /// ParseLoad
3515 ///   ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3516 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3517                          bool isVolatile) {
3518   Value *Val; LocTy Loc;
3519   unsigned Alignment = 0;
3520   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3521
3522   if (EatIfPresent(lltok::comma))
3523     if (ParseOptionalInfo(Alignment)) return true;
3524
3525   if (!isa<PointerType>(Val->getType()) ||
3526       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3527     return Error(Loc, "load operand must be a pointer to a first class type");
3528
3529   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3530   return false;
3531 }
3532
3533 /// ParseStore
3534 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3535 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3536                           bool isVolatile) {
3537   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3538   unsigned Alignment = 0;
3539   if (ParseTypeAndValue(Val, Loc, PFS) ||
3540       ParseToken(lltok::comma, "expected ',' after store operand") ||
3541       ParseTypeAndValue(Ptr, PtrLoc, PFS))
3542     return true;
3543
3544   if (EatIfPresent(lltok::comma))
3545     if (ParseOptionalInfo(Alignment)) return true;
3546
3547   if (!isa<PointerType>(Ptr->getType()))
3548     return Error(PtrLoc, "store operand must be a pointer");
3549   if (!Val->getType()->isFirstClassType())
3550     return Error(Loc, "store operand must be a first class value");
3551   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3552     return Error(Loc, "stored value and pointer type do not match");
3553
3554   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3555   return false;
3556 }
3557
3558 /// ParseGetResult
3559 ///   ::= 'getresult' TypeAndValue ',' i32
3560 /// FIXME: Remove support for getresult in LLVM 3.0
3561 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3562   Value *Val; LocTy ValLoc, EltLoc;
3563   unsigned Element;
3564   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3565       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3566       ParseUInt32(Element, EltLoc))
3567     return true;
3568
3569   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3570     return Error(ValLoc, "getresult inst requires an aggregate operand");
3571   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3572     return Error(EltLoc, "invalid getresult index for value");
3573   Inst = ExtractValueInst::Create(Val, Element);
3574   return false;
3575 }
3576
3577 /// ParseGetElementPtr
3578 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3579 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3580   Value *Ptr, *Val; LocTy Loc, EltLoc;
3581
3582   bool InBounds = EatIfPresent(lltok::kw_inbounds);
3583
3584   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3585
3586   if (!isa<PointerType>(Ptr->getType()))
3587     return Error(Loc, "base of getelementptr must be a pointer");
3588
3589   SmallVector<Value*, 16> Indices;
3590   while (EatIfPresent(lltok::comma)) {
3591     if (Lex.getKind() == lltok::NamedOrCustomMD)
3592       break;
3593     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3594     if (!isa<IntegerType>(Val->getType()))
3595       return Error(EltLoc, "getelementptr index must be an integer");
3596     Indices.push_back(Val);
3597   }
3598   if (Lex.getKind() == lltok::NamedOrCustomMD)
3599     if (ParseOptionalCustomMetadata()) return true;
3600
3601   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3602                                          Indices.begin(), Indices.end()))
3603     return Error(Loc, "invalid getelementptr indices");
3604   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3605   if (InBounds)
3606     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3607   return false;
3608 }
3609
3610 /// ParseExtractValue
3611 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3612 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3613   Value *Val; LocTy Loc;
3614   SmallVector<unsigned, 4> Indices;
3615   if (ParseTypeAndValue(Val, Loc, PFS) ||
3616       ParseIndexList(Indices))
3617     return true;
3618
3619   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3620     return Error(Loc, "extractvalue operand must be array or struct");
3621
3622   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3623                                         Indices.end()))
3624     return Error(Loc, "invalid indices for extractvalue");
3625   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3626   return false;
3627 }
3628
3629 /// ParseInsertValue
3630 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3631 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3632   Value *Val0, *Val1; LocTy Loc0, Loc1;
3633   SmallVector<unsigned, 4> Indices;
3634   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3635       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3636       ParseTypeAndValue(Val1, Loc1, PFS) ||
3637       ParseIndexList(Indices))
3638     return true;
3639
3640   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3641     return Error(Loc0, "extractvalue operand must be array or struct");
3642
3643   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3644                                         Indices.end()))
3645     return Error(Loc0, "invalid indices for insertvalue");
3646   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3647   return false;
3648 }
3649
3650 //===----------------------------------------------------------------------===//
3651 // Embedded metadata.
3652 //===----------------------------------------------------------------------===//
3653
3654 /// ParseMDNodeVector
3655 ///   ::= Element (',' Element)*
3656 /// Element
3657 ///   ::= 'null' | TypeAndValue
3658 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3659   assert(Lex.getKind() == lltok::lbrace);
3660   Lex.Lex();
3661   do {
3662     Value *V = 0;
3663     if (Lex.getKind() == lltok::kw_null) {
3664       Lex.Lex();
3665       V = 0;
3666     } else {
3667       PATypeHolder Ty(Type::getVoidTy(Context));
3668       if (ParseType(Ty)) return true;
3669       if (Lex.getKind() == lltok::Metadata) {
3670         Lex.Lex();
3671         MetadataBase *Node = 0;
3672         if (!ParseMDNode(Node))
3673           V = Node;
3674         else {
3675           MetadataBase *MDS = 0;
3676           if (ParseMDString(MDS)) return true;
3677           V = MDS;
3678         }
3679       } else {
3680         Constant *C;
3681         if (ParseGlobalValue(Ty, C)) return true;
3682         V = C;
3683       }
3684     }
3685     Elts.push_back(V);
3686   } while (EatIfPresent(lltok::comma));
3687
3688   return false;
3689 }