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