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