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