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