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