064b74304a9fdf624d29b4787b39e02883ddf293
[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/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/SaveAndRestore.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33
34 static std::string getTypeString(Type *T) {
35   std::string Result;
36   raw_string_ostream Tmp(Result);
37   Tmp << *T;
38   return Tmp.str();
39 }
40
41 /// Run: module ::= toplevelentity*
42 bool LLParser::Run() {
43   // Prime the lexer.
44   Lex.Lex();
45
46   return ParseTopLevelEntities() ||
47          ValidateEndOfModule();
48 }
49
50 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
51 /// module.
52 bool LLParser::ValidateEndOfModule() {
53   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
54     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
55
56   // Handle any function attribute group forward references.
57   for (std::map<Value*, std::vector<unsigned> >::iterator
58          I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
59          I != E; ++I) {
60     Value *V = I->first;
61     std::vector<unsigned> &Vec = I->second;
62     AttrBuilder B;
63
64     for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
65          VI != VE; ++VI)
66       B.merge(NumberedAttrBuilders[*VI]);
67
68     if (Function *Fn = dyn_cast<Function>(V)) {
69       AttributeSet AS = Fn->getAttributes();
70       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
71       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
72                                AS.getFnAttributes());
73
74       FnAttrs.merge(B);
75
76       // If the alignment was parsed as an attribute, move to the alignment
77       // field.
78       if (FnAttrs.hasAlignmentAttr()) {
79         Fn->setAlignment(FnAttrs.getAlignment());
80         FnAttrs.removeAttribute(Attribute::Alignment);
81       }
82
83       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
84                             AttributeSet::get(Context,
85                                               AttributeSet::FunctionIndex,
86                                               FnAttrs));
87       Fn->setAttributes(AS);
88     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
89       AttributeSet AS = CI->getAttributes();
90       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92                                AS.getFnAttributes());
93       FnAttrs.merge(B);
94       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
95                             AttributeSet::get(Context,
96                                               AttributeSet::FunctionIndex,
97                                               FnAttrs));
98       CI->setAttributes(AS);
99     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
100       AttributeSet AS = II->getAttributes();
101       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
102       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
103                                AS.getFnAttributes());
104       FnAttrs.merge(B);
105       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
106                             AttributeSet::get(Context,
107                                               AttributeSet::FunctionIndex,
108                                               FnAttrs));
109       II->setAttributes(AS);
110     } else {
111       llvm_unreachable("invalid object with forward attribute group reference");
112     }
113   }
114
115   // If there are entries in ForwardRefBlockAddresses at this point, the
116   // function was never defined.
117   if (!ForwardRefBlockAddresses.empty())
118     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
119                  "expected function name in blockaddress");
120
121   for (const auto &NT : NumberedTypes)
122     if (NT.second.second.isValid())
123       return Error(NT.second.second,
124                    "use of undefined type '%" + Twine(NT.first) + "'");
125
126   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
127        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
128     if (I->second.second.isValid())
129       return Error(I->second.second,
130                    "use of undefined type named '" + I->getKey() + "'");
131
132   if (!ForwardRefComdats.empty())
133     return Error(ForwardRefComdats.begin()->second,
134                  "use of undefined comdat '$" +
135                      ForwardRefComdats.begin()->first + "'");
136
137   if (!ForwardRefVals.empty())
138     return Error(ForwardRefVals.begin()->second.second,
139                  "use of undefined value '@" + ForwardRefVals.begin()->first +
140                  "'");
141
142   if (!ForwardRefValIDs.empty())
143     return Error(ForwardRefValIDs.begin()->second.second,
144                  "use of undefined value '@" +
145                  Twine(ForwardRefValIDs.begin()->first) + "'");
146
147   if (!ForwardRefMDNodes.empty())
148     return Error(ForwardRefMDNodes.begin()->second.second,
149                  "use of undefined metadata '!" +
150                  Twine(ForwardRefMDNodes.begin()->first) + "'");
151
152   // Resolve metadata cycles.
153   for (auto &N : NumberedMetadata) {
154     if (N.second && !N.second->isResolved())
155       N.second->resolveCycles();
156   }
157
158   // Look for intrinsic functions and CallInst that need to be upgraded
159   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
160     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
161
162   UpgradeDebugInfo(*M);
163
164   return false;
165 }
166
167 //===----------------------------------------------------------------------===//
168 // Top-Level Entities
169 //===----------------------------------------------------------------------===//
170
171 bool LLParser::ParseTopLevelEntities() {
172   while (1) {
173     switch (Lex.getKind()) {
174     default:         return TokError("expected top-level entity");
175     case lltok::Eof: return false;
176     case lltok::kw_declare: if (ParseDeclare()) return true; break;
177     case lltok::kw_define:  if (ParseDefine()) return true; break;
178     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
179     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
180     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
181     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
182     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
183     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
184     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
185     case lltok::ComdatVar:  if (parseComdat()) return true; break;
186     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
187     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
188
189     // The Global variable production with no name can have many different
190     // optional leading prefixes, the production is:
191     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
192     //               OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
193     //               ('constant'|'global') ...
194     case lltok::kw_private:             // OptionalLinkage
195     case lltok::kw_internal:            // OptionalLinkage
196     case lltok::kw_weak:                // OptionalLinkage
197     case lltok::kw_weak_odr:            // OptionalLinkage
198     case lltok::kw_linkonce:            // OptionalLinkage
199     case lltok::kw_linkonce_odr:        // OptionalLinkage
200     case lltok::kw_appending:           // OptionalLinkage
201     case lltok::kw_common:              // OptionalLinkage
202     case lltok::kw_extern_weak:         // OptionalLinkage
203     case lltok::kw_external:            // OptionalLinkage
204     case lltok::kw_default:             // OptionalVisibility
205     case lltok::kw_hidden:              // OptionalVisibility
206     case lltok::kw_protected:           // OptionalVisibility
207     case lltok::kw_dllimport:           // OptionalDLLStorageClass
208     case lltok::kw_dllexport:           // OptionalDLLStorageClass
209     case lltok::kw_thread_local:        // OptionalThreadLocal
210     case lltok::kw_addrspace:           // OptionalAddrSpace
211     case lltok::kw_constant:            // GlobalType
212     case lltok::kw_global: {            // GlobalType
213       unsigned Linkage, Visibility, DLLStorageClass;
214       bool UnnamedAddr;
215       GlobalVariable::ThreadLocalMode TLM;
216       bool HasLinkage;
217       if (ParseOptionalLinkage(Linkage, HasLinkage) ||
218           ParseOptionalVisibility(Visibility) ||
219           ParseOptionalDLLStorageClass(DLLStorageClass) ||
220           ParseOptionalThreadLocal(TLM) ||
221           parseOptionalUnnamedAddr(UnnamedAddr) ||
222           ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
223                       DLLStorageClass, TLM, UnnamedAddr))
224         return true;
225       break;
226     }
227
228     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
229     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
230     case lltok::kw_uselistorder_bb:
231                                  if (ParseUseListOrderBB()) return true; break;
232     }
233   }
234 }
235
236
237 /// toplevelentity
238 ///   ::= 'module' 'asm' STRINGCONSTANT
239 bool LLParser::ParseModuleAsm() {
240   assert(Lex.getKind() == lltok::kw_module);
241   Lex.Lex();
242
243   std::string AsmStr;
244   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
245       ParseStringConstant(AsmStr)) return true;
246
247   M->appendModuleInlineAsm(AsmStr);
248   return false;
249 }
250
251 /// toplevelentity
252 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
253 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
254 bool LLParser::ParseTargetDefinition() {
255   assert(Lex.getKind() == lltok::kw_target);
256   std::string Str;
257   switch (Lex.Lex()) {
258   default: return TokError("unknown target property");
259   case lltok::kw_triple:
260     Lex.Lex();
261     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
262         ParseStringConstant(Str))
263       return true;
264     M->setTargetTriple(Str);
265     return false;
266   case lltok::kw_datalayout:
267     Lex.Lex();
268     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
269         ParseStringConstant(Str))
270       return true;
271     M->setDataLayout(Str);
272     return false;
273   }
274 }
275
276 /// toplevelentity
277 ///   ::= 'deplibs' '=' '[' ']'
278 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
279 /// FIXME: Remove in 4.0. Currently parse, but ignore.
280 bool LLParser::ParseDepLibs() {
281   assert(Lex.getKind() == lltok::kw_deplibs);
282   Lex.Lex();
283   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
285     return true;
286
287   if (EatIfPresent(lltok::rsquare))
288     return false;
289
290   do {
291     std::string Str;
292     if (ParseStringConstant(Str)) return true;
293   } while (EatIfPresent(lltok::comma));
294
295   return ParseToken(lltok::rsquare, "expected ']' at end of list");
296 }
297
298 /// ParseUnnamedType:
299 ///   ::= LocalVarID '=' 'type' type
300 bool LLParser::ParseUnnamedType() {
301   LocTy TypeLoc = Lex.getLoc();
302   unsigned TypeID = Lex.getUIntVal();
303   Lex.Lex(); // eat LocalVarID;
304
305   if (ParseToken(lltok::equal, "expected '=' after name") ||
306       ParseToken(lltok::kw_type, "expected 'type' after '='"))
307     return true;
308
309   Type *Result = nullptr;
310   if (ParseStructDefinition(TypeLoc, "",
311                             NumberedTypes[TypeID], Result)) return true;
312
313   if (!isa<StructType>(Result)) {
314     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315     if (Entry.first)
316       return Error(TypeLoc, "non-struct types may not be recursive");
317     Entry.first = Result;
318     Entry.second = SMLoc();
319   }
320
321   return false;
322 }
323
324
325 /// toplevelentity
326 ///   ::= LocalVar '=' 'type' type
327 bool LLParser::ParseNamedType() {
328   std::string Name = Lex.getStrVal();
329   LocTy NameLoc = Lex.getLoc();
330   Lex.Lex();  // eat LocalVar.
331
332   if (ParseToken(lltok::equal, "expected '=' after name") ||
333       ParseToken(lltok::kw_type, "expected 'type' after name"))
334     return true;
335
336   Type *Result = nullptr;
337   if (ParseStructDefinition(NameLoc, Name,
338                             NamedTypes[Name], Result)) return true;
339
340   if (!isa<StructType>(Result)) {
341     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342     if (Entry.first)
343       return Error(NameLoc, "non-struct types may not be recursive");
344     Entry.first = Result;
345     Entry.second = SMLoc();
346   }
347
348   return false;
349 }
350
351
352 /// toplevelentity
353 ///   ::= 'declare' FunctionHeader
354 bool LLParser::ParseDeclare() {
355   assert(Lex.getKind() == lltok::kw_declare);
356   Lex.Lex();
357
358   Function *F;
359   return ParseFunctionHeader(F, false);
360 }
361
362 /// toplevelentity
363 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
364 bool LLParser::ParseDefine() {
365   assert(Lex.getKind() == lltok::kw_define);
366   Lex.Lex();
367
368   Function *F;
369   return ParseFunctionHeader(F, true) ||
370          ParseOptionalFunctionMetadata(*F) ||
371          ParseFunctionBody(*F);
372 }
373
374 /// ParseGlobalType
375 ///   ::= 'constant'
376 ///   ::= 'global'
377 bool LLParser::ParseGlobalType(bool &IsConstant) {
378   if (Lex.getKind() == lltok::kw_constant)
379     IsConstant = true;
380   else if (Lex.getKind() == lltok::kw_global)
381     IsConstant = false;
382   else {
383     IsConstant = false;
384     return TokError("expected 'global' or 'constant'");
385   }
386   Lex.Lex();
387   return false;
388 }
389
390 /// ParseUnnamedGlobal:
391 ///   OptionalVisibility ALIAS ...
392 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
393 ///                                                     ...   -> global variable
394 ///   GlobalID '=' OptionalVisibility ALIAS ...
395 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
396 ///                                                     ...   -> global variable
397 bool LLParser::ParseUnnamedGlobal() {
398   unsigned VarID = NumberedVals.size();
399   std::string Name;
400   LocTy NameLoc = Lex.getLoc();
401
402   // Handle the GlobalID form.
403   if (Lex.getKind() == lltok::GlobalID) {
404     if (Lex.getUIntVal() != VarID)
405       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
406                    Twine(VarID) + "'");
407     Lex.Lex(); // eat GlobalID;
408
409     if (ParseToken(lltok::equal, "expected '=' after name"))
410       return true;
411   }
412
413   bool HasLinkage;
414   unsigned Linkage, Visibility, DLLStorageClass;
415   GlobalVariable::ThreadLocalMode TLM;
416   bool UnnamedAddr;
417   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
418       ParseOptionalVisibility(Visibility) ||
419       ParseOptionalDLLStorageClass(DLLStorageClass) ||
420       ParseOptionalThreadLocal(TLM) ||
421       parseOptionalUnnamedAddr(UnnamedAddr))
422     return true;
423
424   if (Lex.getKind() != lltok::kw_alias)
425     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
426                        DLLStorageClass, TLM, UnnamedAddr);
427   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
428                     UnnamedAddr);
429 }
430
431 /// ParseNamedGlobal:
432 ///   GlobalVar '=' OptionalVisibility ALIAS ...
433 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
434 ///                                                     ...   -> global variable
435 bool LLParser::ParseNamedGlobal() {
436   assert(Lex.getKind() == lltok::GlobalVar);
437   LocTy NameLoc = Lex.getLoc();
438   std::string Name = Lex.getStrVal();
439   Lex.Lex();
440
441   bool HasLinkage;
442   unsigned Linkage, Visibility, DLLStorageClass;
443   GlobalVariable::ThreadLocalMode TLM;
444   bool UnnamedAddr;
445   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
446       ParseOptionalLinkage(Linkage, HasLinkage) ||
447       ParseOptionalVisibility(Visibility) ||
448       ParseOptionalDLLStorageClass(DLLStorageClass) ||
449       ParseOptionalThreadLocal(TLM) ||
450       parseOptionalUnnamedAddr(UnnamedAddr))
451     return true;
452
453   if (Lex.getKind() != lltok::kw_alias)
454     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
455                        DLLStorageClass, TLM, UnnamedAddr);
456
457   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
458                     UnnamedAddr);
459 }
460
461 bool LLParser::parseComdat() {
462   assert(Lex.getKind() == lltok::ComdatVar);
463   std::string Name = Lex.getStrVal();
464   LocTy NameLoc = Lex.getLoc();
465   Lex.Lex();
466
467   if (ParseToken(lltok::equal, "expected '=' here"))
468     return true;
469
470   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
471     return TokError("expected comdat type");
472
473   Comdat::SelectionKind SK;
474   switch (Lex.getKind()) {
475   default:
476     return TokError("unknown selection kind");
477   case lltok::kw_any:
478     SK = Comdat::Any;
479     break;
480   case lltok::kw_exactmatch:
481     SK = Comdat::ExactMatch;
482     break;
483   case lltok::kw_largest:
484     SK = Comdat::Largest;
485     break;
486   case lltok::kw_noduplicates:
487     SK = Comdat::NoDuplicates;
488     break;
489   case lltok::kw_samesize:
490     SK = Comdat::SameSize;
491     break;
492   }
493   Lex.Lex();
494
495   // See if the comdat was forward referenced, if so, use the comdat.
496   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
497   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
498   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
499     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
500
501   Comdat *C;
502   if (I != ComdatSymTab.end())
503     C = &I->second;
504   else
505     C = M->getOrInsertComdat(Name);
506   C->setSelectionKind(SK);
507
508   return false;
509 }
510
511 // MDString:
512 //   ::= '!' STRINGCONSTANT
513 bool LLParser::ParseMDString(MDString *&Result) {
514   std::string Str;
515   if (ParseStringConstant(Str)) return true;
516   llvm::UpgradeMDStringConstant(Str);
517   Result = MDString::get(Context, Str);
518   return false;
519 }
520
521 // MDNode:
522 //   ::= '!' MDNodeNumber
523 bool LLParser::ParseMDNodeID(MDNode *&Result) {
524   // !{ ..., !42, ... }
525   unsigned MID = 0;
526   if (ParseUInt32(MID))
527     return true;
528
529   // If not a forward reference, just return it now.
530   if (NumberedMetadata.count(MID)) {
531     Result = NumberedMetadata[MID];
532     return false;
533   }
534
535   // Otherwise, create MDNode forward reference.
536   auto &FwdRef = ForwardRefMDNodes[MID];
537   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
538
539   Result = FwdRef.first.get();
540   NumberedMetadata[MID].reset(Result);
541   return false;
542 }
543
544 /// ParseNamedMetadata:
545 ///   !foo = !{ !1, !2 }
546 bool LLParser::ParseNamedMetadata() {
547   assert(Lex.getKind() == lltok::MetadataVar);
548   std::string Name = Lex.getStrVal();
549   Lex.Lex();
550
551   if (ParseToken(lltok::equal, "expected '=' here") ||
552       ParseToken(lltok::exclaim, "Expected '!' here") ||
553       ParseToken(lltok::lbrace, "Expected '{' here"))
554     return true;
555
556   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
557   if (Lex.getKind() != lltok::rbrace)
558     do {
559       if (ParseToken(lltok::exclaim, "Expected '!' here"))
560         return true;
561
562       MDNode *N = nullptr;
563       if (ParseMDNodeID(N)) return true;
564       NMD->addOperand(N);
565     } while (EatIfPresent(lltok::comma));
566
567   return ParseToken(lltok::rbrace, "expected end of metadata node");
568 }
569
570 /// ParseStandaloneMetadata:
571 ///   !42 = !{...}
572 bool LLParser::ParseStandaloneMetadata() {
573   assert(Lex.getKind() == lltok::exclaim);
574   Lex.Lex();
575   unsigned MetadataID = 0;
576
577   MDNode *Init;
578   if (ParseUInt32(MetadataID) ||
579       ParseToken(lltok::equal, "expected '=' here"))
580     return true;
581
582   // Detect common error, from old metadata syntax.
583   if (Lex.getKind() == lltok::Type)
584     return TokError("unexpected type in metadata definition");
585
586   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
587   if (Lex.getKind() == lltok::MetadataVar) {
588     if (ParseSpecializedMDNode(Init, IsDistinct))
589       return true;
590   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
591              ParseMDTuple(Init, IsDistinct))
592     return true;
593
594   // See if this was forward referenced, if so, handle it.
595   auto FI = ForwardRefMDNodes.find(MetadataID);
596   if (FI != ForwardRefMDNodes.end()) {
597     FI->second.first->replaceAllUsesWith(Init);
598     ForwardRefMDNodes.erase(FI);
599
600     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
601   } else {
602     if (NumberedMetadata.count(MetadataID))
603       return TokError("Metadata id is already used");
604     NumberedMetadata[MetadataID].reset(Init);
605   }
606
607   return false;
608 }
609
610 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
611   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
612          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
613 }
614
615 /// ParseAlias:
616 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
617 ///                     OptionalDLLStorageClass OptionalThreadLocal
618 ///                     OptionalUnnamedAddr 'alias' Aliasee
619 ///
620 /// Aliasee
621 ///   ::= TypeAndValue
622 ///
623 /// Everything through OptionalUnnamedAddr has already been parsed.
624 ///
625 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
626                           unsigned Visibility, unsigned DLLStorageClass,
627                           GlobalVariable::ThreadLocalMode TLM,
628                           bool UnnamedAddr) {
629   assert(Lex.getKind() == lltok::kw_alias);
630   Lex.Lex();
631
632   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
633
634   if(!GlobalAlias::isValidLinkage(Linkage))
635     return Error(NameLoc, "invalid linkage type for alias");
636
637   if (!isValidVisibilityForLinkage(Visibility, L))
638     return Error(NameLoc,
639                  "symbol with local linkage must have default visibility");
640
641   Constant *Aliasee;
642   LocTy AliaseeLoc = Lex.getLoc();
643   if (Lex.getKind() != lltok::kw_bitcast &&
644       Lex.getKind() != lltok::kw_getelementptr &&
645       Lex.getKind() != lltok::kw_addrspacecast &&
646       Lex.getKind() != lltok::kw_inttoptr) {
647     if (ParseGlobalTypeAndValue(Aliasee))
648       return true;
649   } else {
650     // The bitcast dest type is not present, it is implied by the dest type.
651     ValID ID;
652     if (ParseValID(ID))
653       return true;
654     if (ID.Kind != ValID::t_Constant)
655       return Error(AliaseeLoc, "invalid aliasee");
656     Aliasee = ID.ConstantVal;
657   }
658
659   Type *AliaseeType = Aliasee->getType();
660   auto *PTy = dyn_cast<PointerType>(AliaseeType);
661   if (!PTy)
662     return Error(AliaseeLoc, "An alias must have pointer type");
663
664   // Okay, create the alias but do not insert it into the module yet.
665   std::unique_ptr<GlobalAlias> GA(
666       GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
667                           Aliasee, /*Parent*/ nullptr));
668   GA->setThreadLocalMode(TLM);
669   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
670   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
671   GA->setUnnamedAddr(UnnamedAddr);
672
673   if (Name.empty())
674     NumberedVals.push_back(GA.get());
675
676   // See if this value already exists in the symbol table.  If so, it is either
677   // a redefinition or a definition of a forward reference.
678   if (GlobalValue *Val = M->getNamedValue(Name)) {
679     // See if this was a redefinition.  If so, there is no entry in
680     // ForwardRefVals.
681     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
682       I = ForwardRefVals.find(Name);
683     if (I == ForwardRefVals.end())
684       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
685
686     // Otherwise, this was a definition of forward ref.  Verify that types
687     // agree.
688     if (Val->getType() != GA->getType())
689       return Error(NameLoc,
690               "forward reference and definition of alias have different types");
691
692     // If they agree, just RAUW the old value with the alias and remove the
693     // forward ref info.
694     Val->replaceAllUsesWith(GA.get());
695     Val->eraseFromParent();
696     ForwardRefVals.erase(I);
697   }
698
699   // Insert into the module, we know its name won't collide now.
700   M->getAliasList().push_back(GA.get());
701   assert(GA->getName() == Name && "Should not be a name conflict!");
702
703   // The module owns this now
704   GA.release();
705
706   return false;
707 }
708
709 /// ParseGlobal
710 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
711 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
712 ///       OptionalExternallyInitialized GlobalType Type Const
713 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
714 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
715 ///       OptionalExternallyInitialized GlobalType Type Const
716 ///
717 /// Everything up to and including OptionalUnnamedAddr has been parsed
718 /// already.
719 ///
720 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
721                            unsigned Linkage, bool HasLinkage,
722                            unsigned Visibility, unsigned DLLStorageClass,
723                            GlobalVariable::ThreadLocalMode TLM,
724                            bool UnnamedAddr) {
725   if (!isValidVisibilityForLinkage(Visibility, Linkage))
726     return Error(NameLoc,
727                  "symbol with local linkage must have default visibility");
728
729   unsigned AddrSpace;
730   bool IsConstant, IsExternallyInitialized;
731   LocTy IsExternallyInitializedLoc;
732   LocTy TyLoc;
733
734   Type *Ty = nullptr;
735   if (ParseOptionalAddrSpace(AddrSpace) ||
736       ParseOptionalToken(lltok::kw_externally_initialized,
737                          IsExternallyInitialized,
738                          &IsExternallyInitializedLoc) ||
739       ParseGlobalType(IsConstant) ||
740       ParseType(Ty, TyLoc))
741     return true;
742
743   // If the linkage is specified and is external, then no initializer is
744   // present.
745   Constant *Init = nullptr;
746   if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
747                       Linkage != GlobalValue::ExternalLinkage)) {
748     if (ParseGlobalValue(Ty, Init))
749       return true;
750   }
751
752   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
753     return Error(TyLoc, "invalid type for global variable");
754
755   GlobalValue *GVal = nullptr;
756
757   // See if the global was forward referenced, if so, use the global.
758   if (!Name.empty()) {
759     GVal = M->getNamedValue(Name);
760     if (GVal) {
761       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
762         return Error(NameLoc, "redefinition of global '@" + Name + "'");
763     }
764   } else {
765     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
766       I = ForwardRefValIDs.find(NumberedVals.size());
767     if (I != ForwardRefValIDs.end()) {
768       GVal = I->second.first;
769       ForwardRefValIDs.erase(I);
770     }
771   }
772
773   GlobalVariable *GV;
774   if (!GVal) {
775     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
776                             Name, nullptr, GlobalVariable::NotThreadLocal,
777                             AddrSpace);
778   } else {
779     if (GVal->getValueType() != Ty)
780       return Error(TyLoc,
781             "forward reference and definition of global have different types");
782
783     GV = cast<GlobalVariable>(GVal);
784
785     // Move the forward-reference to the correct spot in the module.
786     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
787   }
788
789   if (Name.empty())
790     NumberedVals.push_back(GV);
791
792   // Set the parsed properties on the global.
793   if (Init)
794     GV->setInitializer(Init);
795   GV->setConstant(IsConstant);
796   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
797   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
798   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
799   GV->setExternallyInitialized(IsExternallyInitialized);
800   GV->setThreadLocalMode(TLM);
801   GV->setUnnamedAddr(UnnamedAddr);
802
803   // Parse attributes on the global.
804   while (Lex.getKind() == lltok::comma) {
805     Lex.Lex();
806
807     if (Lex.getKind() == lltok::kw_section) {
808       Lex.Lex();
809       GV->setSection(Lex.getStrVal());
810       if (ParseToken(lltok::StringConstant, "expected global section string"))
811         return true;
812     } else if (Lex.getKind() == lltok::kw_align) {
813       unsigned Alignment;
814       if (ParseOptionalAlignment(Alignment)) return true;
815       GV->setAlignment(Alignment);
816     } else {
817       Comdat *C;
818       if (parseOptionalComdat(Name, C))
819         return true;
820       if (C)
821         GV->setComdat(C);
822       else
823         return TokError("unknown global variable property!");
824     }
825   }
826
827   return false;
828 }
829
830 /// ParseUnnamedAttrGrp
831 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
832 bool LLParser::ParseUnnamedAttrGrp() {
833   assert(Lex.getKind() == lltok::kw_attributes);
834   LocTy AttrGrpLoc = Lex.getLoc();
835   Lex.Lex();
836
837   if (Lex.getKind() != lltok::AttrGrpID)
838     return TokError("expected attribute group id");
839
840   unsigned VarID = Lex.getUIntVal();
841   std::vector<unsigned> unused;
842   LocTy BuiltinLoc;
843   Lex.Lex();
844
845   if (ParseToken(lltok::equal, "expected '=' here") ||
846       ParseToken(lltok::lbrace, "expected '{' here") ||
847       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
848                                  BuiltinLoc) ||
849       ParseToken(lltok::rbrace, "expected end of attribute group"))
850     return true;
851
852   if (!NumberedAttrBuilders[VarID].hasAttributes())
853     return Error(AttrGrpLoc, "attribute group has no attributes");
854
855   return false;
856 }
857
858 /// ParseFnAttributeValuePairs
859 ///   ::= <attr> | <attr> '=' <value>
860 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
861                                           std::vector<unsigned> &FwdRefAttrGrps,
862                                           bool inAttrGrp, LocTy &BuiltinLoc) {
863   bool HaveError = false;
864
865   B.clear();
866
867   while (true) {
868     lltok::Kind Token = Lex.getKind();
869     if (Token == lltok::kw_builtin)
870       BuiltinLoc = Lex.getLoc();
871     switch (Token) {
872     default:
873       if (!inAttrGrp) return HaveError;
874       return Error(Lex.getLoc(), "unterminated attribute group");
875     case lltok::rbrace:
876       // Finished.
877       return false;
878
879     case lltok::AttrGrpID: {
880       // Allow a function to reference an attribute group:
881       //
882       //   define void @foo() #1 { ... }
883       if (inAttrGrp)
884         HaveError |=
885           Error(Lex.getLoc(),
886               "cannot have an attribute group reference in an attribute group");
887
888       unsigned AttrGrpNum = Lex.getUIntVal();
889       if (inAttrGrp) break;
890
891       // Save the reference to the attribute group. We'll fill it in later.
892       FwdRefAttrGrps.push_back(AttrGrpNum);
893       break;
894     }
895     // Target-dependent attributes:
896     case lltok::StringConstant: {
897       std::string Attr = Lex.getStrVal();
898       Lex.Lex();
899       std::string Val;
900       if (EatIfPresent(lltok::equal) &&
901           ParseStringConstant(Val))
902         return true;
903
904       B.addAttribute(Attr, Val);
905       continue;
906     }
907
908     // Target-independent attributes:
909     case lltok::kw_align: {
910       // As a hack, we allow function alignment to be initially parsed as an
911       // attribute on a function declaration/definition or added to an attribute
912       // group and later moved to the alignment field.
913       unsigned Alignment;
914       if (inAttrGrp) {
915         Lex.Lex();
916         if (ParseToken(lltok::equal, "expected '=' here") ||
917             ParseUInt32(Alignment))
918           return true;
919       } else {
920         if (ParseOptionalAlignment(Alignment))
921           return true;
922       }
923       B.addAlignmentAttr(Alignment);
924       continue;
925     }
926     case lltok::kw_alignstack: {
927       unsigned Alignment;
928       if (inAttrGrp) {
929         Lex.Lex();
930         if (ParseToken(lltok::equal, "expected '=' here") ||
931             ParseUInt32(Alignment))
932           return true;
933       } else {
934         if (ParseOptionalStackAlignment(Alignment))
935           return true;
936       }
937       B.addStackAlignmentAttr(Alignment);
938       continue;
939     }
940     case lltok::kw_alwaysinline:      B.addAttribute(Attribute::AlwaysInline); break;
941     case lltok::kw_builtin:           B.addAttribute(Attribute::Builtin); break;
942     case lltok::kw_cold:              B.addAttribute(Attribute::Cold); break;
943     case lltok::kw_convergent:        B.addAttribute(Attribute::Convergent); break;
944     case lltok::kw_inlinehint:        B.addAttribute(Attribute::InlineHint); break;
945     case lltok::kw_jumptable:         B.addAttribute(Attribute::JumpTable); break;
946     case lltok::kw_minsize:           B.addAttribute(Attribute::MinSize); break;
947     case lltok::kw_naked:             B.addAttribute(Attribute::Naked); break;
948     case lltok::kw_nobuiltin:         B.addAttribute(Attribute::NoBuiltin); break;
949     case lltok::kw_noduplicate:       B.addAttribute(Attribute::NoDuplicate); break;
950     case lltok::kw_noimplicitfloat:   B.addAttribute(Attribute::NoImplicitFloat); break;
951     case lltok::kw_noinline:          B.addAttribute(Attribute::NoInline); break;
952     case lltok::kw_nonlazybind:       B.addAttribute(Attribute::NonLazyBind); break;
953     case lltok::kw_noredzone:         B.addAttribute(Attribute::NoRedZone); break;
954     case lltok::kw_noreturn:          B.addAttribute(Attribute::NoReturn); break;
955     case lltok::kw_nounwind:          B.addAttribute(Attribute::NoUnwind); break;
956     case lltok::kw_optnone:           B.addAttribute(Attribute::OptimizeNone); break;
957     case lltok::kw_optsize:           B.addAttribute(Attribute::OptimizeForSize); break;
958     case lltok::kw_readnone:          B.addAttribute(Attribute::ReadNone); break;
959     case lltok::kw_readonly:          B.addAttribute(Attribute::ReadOnly); break;
960     case lltok::kw_returns_twice:     B.addAttribute(Attribute::ReturnsTwice); break;
961     case lltok::kw_ssp:               B.addAttribute(Attribute::StackProtect); break;
962     case lltok::kw_sspreq:            B.addAttribute(Attribute::StackProtectReq); break;
963     case lltok::kw_sspstrong:         B.addAttribute(Attribute::StackProtectStrong); break;
964     case lltok::kw_safestack:         B.addAttribute(Attribute::SafeStack); break;
965     case lltok::kw_sanitize_address:  B.addAttribute(Attribute::SanitizeAddress); break;
966     case lltok::kw_sanitize_thread:   B.addAttribute(Attribute::SanitizeThread); break;
967     case lltok::kw_sanitize_memory:   B.addAttribute(Attribute::SanitizeMemory); break;
968     case lltok::kw_uwtable:           B.addAttribute(Attribute::UWTable); break;
969
970     // Error handling.
971     case lltok::kw_inreg:
972     case lltok::kw_signext:
973     case lltok::kw_zeroext:
974       HaveError |=
975         Error(Lex.getLoc(),
976               "invalid use of attribute on a function");
977       break;
978     case lltok::kw_byval:
979     case lltok::kw_dereferenceable:
980     case lltok::kw_dereferenceable_or_null:
981     case lltok::kw_inalloca:
982     case lltok::kw_nest:
983     case lltok::kw_noalias:
984     case lltok::kw_nocapture:
985     case lltok::kw_nonnull:
986     case lltok::kw_returned:
987     case lltok::kw_sret:
988       HaveError |=
989         Error(Lex.getLoc(),
990               "invalid use of parameter-only attribute on a function");
991       break;
992     }
993
994     Lex.Lex();
995   }
996 }
997
998 //===----------------------------------------------------------------------===//
999 // GlobalValue Reference/Resolution Routines.
1000 //===----------------------------------------------------------------------===//
1001
1002 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1003 /// forward reference record if needed.  This can return null if the value
1004 /// exists but does not have the right type.
1005 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1006                                     LocTy Loc) {
1007   PointerType *PTy = dyn_cast<PointerType>(Ty);
1008   if (!PTy) {
1009     Error(Loc, "global variable reference must have pointer type");
1010     return nullptr;
1011   }
1012
1013   // Look this name up in the normal function symbol table.
1014   GlobalValue *Val =
1015     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1016
1017   // If this is a forward reference for the value, see if we already created a
1018   // forward ref record.
1019   if (!Val) {
1020     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1021       I = ForwardRefVals.find(Name);
1022     if (I != ForwardRefVals.end())
1023       Val = I->second.first;
1024   }
1025
1026   // If we have the value in the symbol table or fwd-ref table, return it.
1027   if (Val) {
1028     if (Val->getType() == Ty) return Val;
1029     Error(Loc, "'@" + Name + "' defined with type '" +
1030           getTypeString(Val->getType()) + "'");
1031     return nullptr;
1032   }
1033
1034   // Otherwise, create a new forward reference for this value and remember it.
1035   GlobalValue *FwdVal;
1036   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1037     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1038   else
1039     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1040                                 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1041                                 nullptr, GlobalVariable::NotThreadLocal,
1042                                 PTy->getAddressSpace());
1043
1044   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1045   return FwdVal;
1046 }
1047
1048 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1049   PointerType *PTy = dyn_cast<PointerType>(Ty);
1050   if (!PTy) {
1051     Error(Loc, "global variable reference must have pointer type");
1052     return nullptr;
1053   }
1054
1055   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1056
1057   // If this is a forward reference for the value, see if we already created a
1058   // forward ref record.
1059   if (!Val) {
1060     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1061       I = ForwardRefValIDs.find(ID);
1062     if (I != ForwardRefValIDs.end())
1063       Val = I->second.first;
1064   }
1065
1066   // If we have the value in the symbol table or fwd-ref table, return it.
1067   if (Val) {
1068     if (Val->getType() == Ty) return Val;
1069     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1070           getTypeString(Val->getType()) + "'");
1071     return nullptr;
1072   }
1073
1074   // Otherwise, create a new forward reference for this value and remember it.
1075   GlobalValue *FwdVal;
1076   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1077     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1078   else
1079     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1080                                 GlobalValue::ExternalWeakLinkage, nullptr, "");
1081
1082   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1083   return FwdVal;
1084 }
1085
1086
1087 //===----------------------------------------------------------------------===//
1088 // Comdat Reference/Resolution Routines.
1089 //===----------------------------------------------------------------------===//
1090
1091 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1092   // Look this name up in the comdat symbol table.
1093   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1094   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1095   if (I != ComdatSymTab.end())
1096     return &I->second;
1097
1098   // Otherwise, create a new forward reference for this value and remember it.
1099   Comdat *C = M->getOrInsertComdat(Name);
1100   ForwardRefComdats[Name] = Loc;
1101   return C;
1102 }
1103
1104
1105 //===----------------------------------------------------------------------===//
1106 // Helper Routines.
1107 //===----------------------------------------------------------------------===//
1108
1109 /// ParseToken - If the current token has the specified kind, eat it and return
1110 /// success.  Otherwise, emit the specified error and return failure.
1111 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1112   if (Lex.getKind() != T)
1113     return TokError(ErrMsg);
1114   Lex.Lex();
1115   return false;
1116 }
1117
1118 /// ParseStringConstant
1119 ///   ::= StringConstant
1120 bool LLParser::ParseStringConstant(std::string &Result) {
1121   if (Lex.getKind() != lltok::StringConstant)
1122     return TokError("expected string constant");
1123   Result = Lex.getStrVal();
1124   Lex.Lex();
1125   return false;
1126 }
1127
1128 /// ParseUInt32
1129 ///   ::= uint32
1130 bool LLParser::ParseUInt32(unsigned &Val) {
1131   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1132     return TokError("expected integer");
1133   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1134   if (Val64 != unsigned(Val64))
1135     return TokError("expected 32-bit integer (too large)");
1136   Val = Val64;
1137   Lex.Lex();
1138   return false;
1139 }
1140
1141 /// ParseUInt64
1142 ///   ::= uint64
1143 bool LLParser::ParseUInt64(uint64_t &Val) {
1144   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1145     return TokError("expected integer");
1146   Val = Lex.getAPSIntVal().getLimitedValue();
1147   Lex.Lex();
1148   return false;
1149 }
1150
1151 /// ParseTLSModel
1152 ///   := 'localdynamic'
1153 ///   := 'initialexec'
1154 ///   := 'localexec'
1155 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1156   switch (Lex.getKind()) {
1157     default:
1158       return TokError("expected localdynamic, initialexec or localexec");
1159     case lltok::kw_localdynamic:
1160       TLM = GlobalVariable::LocalDynamicTLSModel;
1161       break;
1162     case lltok::kw_initialexec:
1163       TLM = GlobalVariable::InitialExecTLSModel;
1164       break;
1165     case lltok::kw_localexec:
1166       TLM = GlobalVariable::LocalExecTLSModel;
1167       break;
1168   }
1169
1170   Lex.Lex();
1171   return false;
1172 }
1173
1174 /// ParseOptionalThreadLocal
1175 ///   := /*empty*/
1176 ///   := 'thread_local'
1177 ///   := 'thread_local' '(' tlsmodel ')'
1178 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1179   TLM = GlobalVariable::NotThreadLocal;
1180   if (!EatIfPresent(lltok::kw_thread_local))
1181     return false;
1182
1183   TLM = GlobalVariable::GeneralDynamicTLSModel;
1184   if (Lex.getKind() == lltok::lparen) {
1185     Lex.Lex();
1186     return ParseTLSModel(TLM) ||
1187       ParseToken(lltok::rparen, "expected ')' after thread local model");
1188   }
1189   return false;
1190 }
1191
1192 /// ParseOptionalAddrSpace
1193 ///   := /*empty*/
1194 ///   := 'addrspace' '(' uint32 ')'
1195 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1196   AddrSpace = 0;
1197   if (!EatIfPresent(lltok::kw_addrspace))
1198     return false;
1199   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1200          ParseUInt32(AddrSpace) ||
1201          ParseToken(lltok::rparen, "expected ')' in address space");
1202 }
1203
1204 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1205 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1206   bool HaveError = false;
1207
1208   B.clear();
1209
1210   while (1) {
1211     lltok::Kind Token = Lex.getKind();
1212     switch (Token) {
1213     default:  // End of attributes.
1214       return HaveError;
1215     case lltok::kw_align: {
1216       unsigned Alignment;
1217       if (ParseOptionalAlignment(Alignment))
1218         return true;
1219       B.addAlignmentAttr(Alignment);
1220       continue;
1221     }
1222     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1223     case lltok::kw_dereferenceable: {
1224       uint64_t Bytes;
1225       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1226         return true;
1227       B.addDereferenceableAttr(Bytes);
1228       continue;
1229     }
1230     case lltok::kw_dereferenceable_or_null: {
1231       uint64_t Bytes;
1232       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1233         return true;
1234       B.addDereferenceableOrNullAttr(Bytes);
1235       continue;
1236     }
1237     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1238     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1239     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1240     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1241     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1242     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1243     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1244     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1245     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1246     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1247     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1248     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1249
1250     case lltok::kw_alignstack:
1251     case lltok::kw_alwaysinline:
1252     case lltok::kw_builtin:
1253     case lltok::kw_inlinehint:
1254     case lltok::kw_jumptable:
1255     case lltok::kw_minsize:
1256     case lltok::kw_naked:
1257     case lltok::kw_nobuiltin:
1258     case lltok::kw_noduplicate:
1259     case lltok::kw_noimplicitfloat:
1260     case lltok::kw_noinline:
1261     case lltok::kw_nonlazybind:
1262     case lltok::kw_noredzone:
1263     case lltok::kw_noreturn:
1264     case lltok::kw_nounwind:
1265     case lltok::kw_optnone:
1266     case lltok::kw_optsize:
1267     case lltok::kw_returns_twice:
1268     case lltok::kw_sanitize_address:
1269     case lltok::kw_sanitize_memory:
1270     case lltok::kw_sanitize_thread:
1271     case lltok::kw_ssp:
1272     case lltok::kw_sspreq:
1273     case lltok::kw_sspstrong:
1274     case lltok::kw_safestack:
1275     case lltok::kw_uwtable:
1276       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1277       break;
1278     }
1279
1280     Lex.Lex();
1281   }
1282 }
1283
1284 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1285 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1286   bool HaveError = false;
1287
1288   B.clear();
1289
1290   while (1) {
1291     lltok::Kind Token = Lex.getKind();
1292     switch (Token) {
1293     default:  // End of attributes.
1294       return HaveError;
1295     case lltok::kw_dereferenceable: {
1296       uint64_t Bytes;
1297       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1298         return true;
1299       B.addDereferenceableAttr(Bytes);
1300       continue;
1301     }
1302     case lltok::kw_dereferenceable_or_null: {
1303       uint64_t Bytes;
1304       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1305         return true;
1306       B.addDereferenceableOrNullAttr(Bytes);
1307       continue;
1308     }
1309     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1310     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1311     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1312     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1313     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1314
1315     // Error handling.
1316     case lltok::kw_align:
1317     case lltok::kw_byval:
1318     case lltok::kw_inalloca:
1319     case lltok::kw_nest:
1320     case lltok::kw_nocapture:
1321     case lltok::kw_returned:
1322     case lltok::kw_sret:
1323       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1324       break;
1325
1326     case lltok::kw_alignstack:
1327     case lltok::kw_alwaysinline:
1328     case lltok::kw_builtin:
1329     case lltok::kw_cold:
1330     case lltok::kw_inlinehint:
1331     case lltok::kw_jumptable:
1332     case lltok::kw_minsize:
1333     case lltok::kw_naked:
1334     case lltok::kw_nobuiltin:
1335     case lltok::kw_noduplicate:
1336     case lltok::kw_noimplicitfloat:
1337     case lltok::kw_noinline:
1338     case lltok::kw_nonlazybind:
1339     case lltok::kw_noredzone:
1340     case lltok::kw_noreturn:
1341     case lltok::kw_nounwind:
1342     case lltok::kw_optnone:
1343     case lltok::kw_optsize:
1344     case lltok::kw_returns_twice:
1345     case lltok::kw_sanitize_address:
1346     case lltok::kw_sanitize_memory:
1347     case lltok::kw_sanitize_thread:
1348     case lltok::kw_ssp:
1349     case lltok::kw_sspreq:
1350     case lltok::kw_sspstrong:
1351     case lltok::kw_safestack:
1352     case lltok::kw_uwtable:
1353       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1354       break;
1355
1356     case lltok::kw_readnone:
1357     case lltok::kw_readonly:
1358       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1359     }
1360
1361     Lex.Lex();
1362   }
1363 }
1364
1365 /// ParseOptionalLinkage
1366 ///   ::= /*empty*/
1367 ///   ::= 'private'
1368 ///   ::= 'internal'
1369 ///   ::= 'weak'
1370 ///   ::= 'weak_odr'
1371 ///   ::= 'linkonce'
1372 ///   ::= 'linkonce_odr'
1373 ///   ::= 'available_externally'
1374 ///   ::= 'appending'
1375 ///   ::= 'common'
1376 ///   ::= 'extern_weak'
1377 ///   ::= 'external'
1378 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1379   HasLinkage = false;
1380   switch (Lex.getKind()) {
1381   default:                       Res=GlobalValue::ExternalLinkage; return false;
1382   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1383   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1384   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1385   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1386   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1387   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1388   case lltok::kw_available_externally:
1389     Res = GlobalValue::AvailableExternallyLinkage;
1390     break;
1391   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1392   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1393   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1394   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1395   }
1396   Lex.Lex();
1397   HasLinkage = true;
1398   return false;
1399 }
1400
1401 /// ParseOptionalVisibility
1402 ///   ::= /*empty*/
1403 ///   ::= 'default'
1404 ///   ::= 'hidden'
1405 ///   ::= 'protected'
1406 ///
1407 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1408   switch (Lex.getKind()) {
1409   default:                  Res = GlobalValue::DefaultVisibility; return false;
1410   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1411   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1412   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1413   }
1414   Lex.Lex();
1415   return false;
1416 }
1417
1418 /// ParseOptionalDLLStorageClass
1419 ///   ::= /*empty*/
1420 ///   ::= 'dllimport'
1421 ///   ::= 'dllexport'
1422 ///
1423 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1424   switch (Lex.getKind()) {
1425   default:                  Res = GlobalValue::DefaultStorageClass; return false;
1426   case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1427   case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1428   }
1429   Lex.Lex();
1430   return false;
1431 }
1432
1433 /// ParseOptionalCallingConv
1434 ///   ::= /*empty*/
1435 ///   ::= 'ccc'
1436 ///   ::= 'fastcc'
1437 ///   ::= 'intel_ocl_bicc'
1438 ///   ::= 'coldcc'
1439 ///   ::= 'x86_stdcallcc'
1440 ///   ::= 'x86_fastcallcc'
1441 ///   ::= 'x86_thiscallcc'
1442 ///   ::= 'x86_vectorcallcc'
1443 ///   ::= 'arm_apcscc'
1444 ///   ::= 'arm_aapcscc'
1445 ///   ::= 'arm_aapcs_vfpcc'
1446 ///   ::= 'msp430_intrcc'
1447 ///   ::= 'ptx_kernel'
1448 ///   ::= 'ptx_device'
1449 ///   ::= 'spir_func'
1450 ///   ::= 'spir_kernel'
1451 ///   ::= 'x86_64_sysvcc'
1452 ///   ::= 'x86_64_win64cc'
1453 ///   ::= 'webkit_jscc'
1454 ///   ::= 'anyregcc'
1455 ///   ::= 'preserve_mostcc'
1456 ///   ::= 'preserve_allcc'
1457 ///   ::= 'ghccc'
1458 ///   ::= 'cc' UINT
1459 ///
1460 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1461   switch (Lex.getKind()) {
1462   default:                       CC = CallingConv::C; return false;
1463   case lltok::kw_ccc:            CC = CallingConv::C; break;
1464   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1465   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1466   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1467   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1468   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1469   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1470   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1471   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1472   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1473   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1474   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1475   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1476   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1477   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1478   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1479   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1480   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1481   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1482   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1483   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1484   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1485   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1486   case lltok::kw_cc: {
1487       Lex.Lex();
1488       return ParseUInt32(CC);
1489     }
1490   }
1491
1492   Lex.Lex();
1493   return false;
1494 }
1495
1496 /// ParseMetadataAttachment
1497 ///   ::= !dbg !42
1498 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1499   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1500
1501   std::string Name = Lex.getStrVal();
1502   Kind = M->getMDKindID(Name);
1503   Lex.Lex();
1504
1505   return ParseMDNode(MD);
1506 }
1507
1508 /// ParseInstructionMetadata
1509 ///   ::= !dbg !42 (',' !dbg !57)*
1510 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1511   do {
1512     if (Lex.getKind() != lltok::MetadataVar)
1513       return TokError("expected metadata after comma");
1514
1515     unsigned MDK;
1516     MDNode *N;
1517     if (ParseMetadataAttachment(MDK, N))
1518       return true;
1519
1520     Inst.setMetadata(MDK, N);
1521     if (MDK == LLVMContext::MD_tbaa)
1522       InstsWithTBAATag.push_back(&Inst);
1523
1524     // If this is the end of the list, we're done.
1525   } while (EatIfPresent(lltok::comma));
1526   return false;
1527 }
1528
1529 /// ParseOptionalFunctionMetadata
1530 ///   ::= (!dbg !57)*
1531 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1532   while (Lex.getKind() == lltok::MetadataVar) {
1533     unsigned MDK;
1534     MDNode *N;
1535     if (ParseMetadataAttachment(MDK, N))
1536       return true;
1537
1538     F.setMetadata(MDK, N);
1539   }
1540   return false;
1541 }
1542
1543 /// ParseOptionalAlignment
1544 ///   ::= /* empty */
1545 ///   ::= 'align' 4
1546 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1547   Alignment = 0;
1548   if (!EatIfPresent(lltok::kw_align))
1549     return false;
1550   LocTy AlignLoc = Lex.getLoc();
1551   if (ParseUInt32(Alignment)) return true;
1552   if (!isPowerOf2_32(Alignment))
1553     return Error(AlignLoc, "alignment is not a power of two");
1554   if (Alignment > Value::MaximumAlignment)
1555     return Error(AlignLoc, "huge alignments are not supported yet");
1556   return false;
1557 }
1558
1559 /// ParseOptionalDerefAttrBytes
1560 ///   ::= /* empty */
1561 ///   ::= AttrKind '(' 4 ')'
1562 ///
1563 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1564 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1565                                            uint64_t &Bytes) {
1566   assert((AttrKind == lltok::kw_dereferenceable ||
1567           AttrKind == lltok::kw_dereferenceable_or_null) &&
1568          "contract!");
1569
1570   Bytes = 0;
1571   if (!EatIfPresent(AttrKind))
1572     return false;
1573   LocTy ParenLoc = Lex.getLoc();
1574   if (!EatIfPresent(lltok::lparen))
1575     return Error(ParenLoc, "expected '('");
1576   LocTy DerefLoc = Lex.getLoc();
1577   if (ParseUInt64(Bytes)) return true;
1578   ParenLoc = Lex.getLoc();
1579   if (!EatIfPresent(lltok::rparen))
1580     return Error(ParenLoc, "expected ')'");
1581   if (!Bytes)
1582     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1583   return false;
1584 }
1585
1586 /// ParseOptionalCommaAlign
1587 ///   ::=
1588 ///   ::= ',' align 4
1589 ///
1590 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1591 /// end.
1592 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1593                                        bool &AteExtraComma) {
1594   AteExtraComma = false;
1595   while (EatIfPresent(lltok::comma)) {
1596     // Metadata at the end is an early exit.
1597     if (Lex.getKind() == lltok::MetadataVar) {
1598       AteExtraComma = true;
1599       return false;
1600     }
1601
1602     if (Lex.getKind() != lltok::kw_align)
1603       return Error(Lex.getLoc(), "expected metadata or 'align'");
1604
1605     if (ParseOptionalAlignment(Alignment)) return true;
1606   }
1607
1608   return false;
1609 }
1610
1611 /// ParseScopeAndOrdering
1612 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1613 ///   else: ::=
1614 ///
1615 /// This sets Scope and Ordering to the parsed values.
1616 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1617                                      AtomicOrdering &Ordering) {
1618   if (!isAtomic)
1619     return false;
1620
1621   Scope = CrossThread;
1622   if (EatIfPresent(lltok::kw_singlethread))
1623     Scope = SingleThread;
1624
1625   return ParseOrdering(Ordering);
1626 }
1627
1628 /// ParseOrdering
1629 ///   ::= AtomicOrdering
1630 ///
1631 /// This sets Ordering to the parsed value.
1632 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1633   switch (Lex.getKind()) {
1634   default: return TokError("Expected ordering on atomic instruction");
1635   case lltok::kw_unordered: Ordering = Unordered; break;
1636   case lltok::kw_monotonic: Ordering = Monotonic; break;
1637   case lltok::kw_acquire: Ordering = Acquire; break;
1638   case lltok::kw_release: Ordering = Release; break;
1639   case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1640   case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1641   }
1642   Lex.Lex();
1643   return false;
1644 }
1645
1646 /// ParseOptionalStackAlignment
1647 ///   ::= /* empty */
1648 ///   ::= 'alignstack' '(' 4 ')'
1649 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1650   Alignment = 0;
1651   if (!EatIfPresent(lltok::kw_alignstack))
1652     return false;
1653   LocTy ParenLoc = Lex.getLoc();
1654   if (!EatIfPresent(lltok::lparen))
1655     return Error(ParenLoc, "expected '('");
1656   LocTy AlignLoc = Lex.getLoc();
1657   if (ParseUInt32(Alignment)) return true;
1658   ParenLoc = Lex.getLoc();
1659   if (!EatIfPresent(lltok::rparen))
1660     return Error(ParenLoc, "expected ')'");
1661   if (!isPowerOf2_32(Alignment))
1662     return Error(AlignLoc, "stack alignment is not a power of two");
1663   return false;
1664 }
1665
1666 /// ParseIndexList - This parses the index list for an insert/extractvalue
1667 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1668 /// comma at the end of the line and find that it is followed by metadata.
1669 /// Clients that don't allow metadata can call the version of this function that
1670 /// only takes one argument.
1671 ///
1672 /// ParseIndexList
1673 ///    ::=  (',' uint32)+
1674 ///
1675 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1676                               bool &AteExtraComma) {
1677   AteExtraComma = false;
1678
1679   if (Lex.getKind() != lltok::comma)
1680     return TokError("expected ',' as start of index list");
1681
1682   while (EatIfPresent(lltok::comma)) {
1683     if (Lex.getKind() == lltok::MetadataVar) {
1684       if (Indices.empty()) return TokError("expected index");
1685       AteExtraComma = true;
1686       return false;
1687     }
1688     unsigned Idx = 0;
1689     if (ParseUInt32(Idx)) return true;
1690     Indices.push_back(Idx);
1691   }
1692
1693   return false;
1694 }
1695
1696 //===----------------------------------------------------------------------===//
1697 // Type Parsing.
1698 //===----------------------------------------------------------------------===//
1699
1700 /// ParseType - Parse a type.
1701 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1702   SMLoc TypeLoc = Lex.getLoc();
1703   switch (Lex.getKind()) {
1704   default:
1705     return TokError(Msg);
1706   case lltok::Type:
1707     // Type ::= 'float' | 'void' (etc)
1708     Result = Lex.getTyVal();
1709     Lex.Lex();
1710     break;
1711   case lltok::lbrace:
1712     // Type ::= StructType
1713     if (ParseAnonStructType(Result, false))
1714       return true;
1715     break;
1716   case lltok::lsquare:
1717     // Type ::= '[' ... ']'
1718     Lex.Lex(); // eat the lsquare.
1719     if (ParseArrayVectorType(Result, false))
1720       return true;
1721     break;
1722   case lltok::less: // Either vector or packed struct.
1723     // Type ::= '<' ... '>'
1724     Lex.Lex();
1725     if (Lex.getKind() == lltok::lbrace) {
1726       if (ParseAnonStructType(Result, true) ||
1727           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1728         return true;
1729     } else if (ParseArrayVectorType(Result, true))
1730       return true;
1731     break;
1732   case lltok::LocalVar: {
1733     // Type ::= %foo
1734     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1735
1736     // If the type hasn't been defined yet, create a forward definition and
1737     // remember where that forward def'n was seen (in case it never is defined).
1738     if (!Entry.first) {
1739       Entry.first = StructType::create(Context, Lex.getStrVal());
1740       Entry.second = Lex.getLoc();
1741     }
1742     Result = Entry.first;
1743     Lex.Lex();
1744     break;
1745   }
1746
1747   case lltok::LocalVarID: {
1748     // Type ::= %4
1749     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1750
1751     // If the type hasn't been defined yet, create a forward definition and
1752     // remember where that forward def'n was seen (in case it never is defined).
1753     if (!Entry.first) {
1754       Entry.first = StructType::create(Context);
1755       Entry.second = Lex.getLoc();
1756     }
1757     Result = Entry.first;
1758     Lex.Lex();
1759     break;
1760   }
1761   }
1762
1763   // Parse the type suffixes.
1764   while (1) {
1765     switch (Lex.getKind()) {
1766     // End of type.
1767     default:
1768       if (!AllowVoid && Result->isVoidTy())
1769         return Error(TypeLoc, "void type only allowed for function results");
1770       return false;
1771
1772     // Type ::= Type '*'
1773     case lltok::star:
1774       if (Result->isLabelTy())
1775         return TokError("basic block pointers are invalid");
1776       if (Result->isVoidTy())
1777         return TokError("pointers to void are invalid - use i8* instead");
1778       if (!PointerType::isValidElementType(Result))
1779         return TokError("pointer to this type is invalid");
1780       Result = PointerType::getUnqual(Result);
1781       Lex.Lex();
1782       break;
1783
1784     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1785     case lltok::kw_addrspace: {
1786       if (Result->isLabelTy())
1787         return TokError("basic block pointers are invalid");
1788       if (Result->isVoidTy())
1789         return TokError("pointers to void are invalid; use i8* instead");
1790       if (!PointerType::isValidElementType(Result))
1791         return TokError("pointer to this type is invalid");
1792       unsigned AddrSpace;
1793       if (ParseOptionalAddrSpace(AddrSpace) ||
1794           ParseToken(lltok::star, "expected '*' in address space"))
1795         return true;
1796
1797       Result = PointerType::get(Result, AddrSpace);
1798       break;
1799     }
1800
1801     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1802     case lltok::lparen:
1803       if (ParseFunctionType(Result))
1804         return true;
1805       break;
1806     }
1807   }
1808 }
1809
1810 /// ParseParameterList
1811 ///    ::= '(' ')'
1812 ///    ::= '(' Arg (',' Arg)* ')'
1813 ///  Arg
1814 ///    ::= Type OptionalAttributes Value OptionalAttributes
1815 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1816                                   PerFunctionState &PFS, bool IsMustTailCall,
1817                                   bool InVarArgsFunc) {
1818   if (ParseToken(lltok::lparen, "expected '(' in call"))
1819     return true;
1820
1821   unsigned AttrIndex = 1;
1822   while (Lex.getKind() != lltok::rparen) {
1823     // If this isn't the first argument, we need a comma.
1824     if (!ArgList.empty() &&
1825         ParseToken(lltok::comma, "expected ',' in argument list"))
1826       return true;
1827
1828     // Parse an ellipsis if this is a musttail call in a variadic function.
1829     if (Lex.getKind() == lltok::dotdotdot) {
1830       const char *Msg = "unexpected ellipsis in argument list for ";
1831       if (!IsMustTailCall)
1832         return TokError(Twine(Msg) + "non-musttail call");
1833       if (!InVarArgsFunc)
1834         return TokError(Twine(Msg) + "musttail call in non-varargs function");
1835       Lex.Lex();  // Lex the '...', it is purely for readability.
1836       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1837     }
1838
1839     // Parse the argument.
1840     LocTy ArgLoc;
1841     Type *ArgTy = nullptr;
1842     AttrBuilder ArgAttrs;
1843     Value *V;
1844     if (ParseType(ArgTy, ArgLoc))
1845       return true;
1846
1847     if (ArgTy->isMetadataTy()) {
1848       if (ParseMetadataAsValue(V, PFS))
1849         return true;
1850     } else {
1851       // Otherwise, handle normal operands.
1852       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1853         return true;
1854     }
1855     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1856                                                              AttrIndex++,
1857                                                              ArgAttrs)));
1858   }
1859
1860   if (IsMustTailCall && InVarArgsFunc)
1861     return TokError("expected '...' at end of argument list for musttail call "
1862                     "in varargs function");
1863
1864   Lex.Lex();  // Lex the ')'.
1865   return false;
1866 }
1867
1868
1869
1870 /// ParseArgumentList - Parse the argument list for a function type or function
1871 /// prototype.
1872 ///   ::= '(' ArgTypeListI ')'
1873 /// ArgTypeListI
1874 ///   ::= /*empty*/
1875 ///   ::= '...'
1876 ///   ::= ArgTypeList ',' '...'
1877 ///   ::= ArgType (',' ArgType)*
1878 ///
1879 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1880                                  bool &isVarArg){
1881   isVarArg = false;
1882   assert(Lex.getKind() == lltok::lparen);
1883   Lex.Lex(); // eat the (.
1884
1885   if (Lex.getKind() == lltok::rparen) {
1886     // empty
1887   } else if (Lex.getKind() == lltok::dotdotdot) {
1888     isVarArg = true;
1889     Lex.Lex();
1890   } else {
1891     LocTy TypeLoc = Lex.getLoc();
1892     Type *ArgTy = nullptr;
1893     AttrBuilder Attrs;
1894     std::string Name;
1895
1896     if (ParseType(ArgTy) ||
1897         ParseOptionalParamAttrs(Attrs)) return true;
1898
1899     if (ArgTy->isVoidTy())
1900       return Error(TypeLoc, "argument can not have void type");
1901
1902     if (Lex.getKind() == lltok::LocalVar) {
1903       Name = Lex.getStrVal();
1904       Lex.Lex();
1905     }
1906
1907     if (!FunctionType::isValidArgumentType(ArgTy))
1908       return Error(TypeLoc, "invalid type for function argument");
1909
1910     unsigned AttrIndex = 1;
1911     ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1912                                                            AttrIndex++, Attrs),
1913                          std::move(Name));
1914
1915     while (EatIfPresent(lltok::comma)) {
1916       // Handle ... at end of arg list.
1917       if (EatIfPresent(lltok::dotdotdot)) {
1918         isVarArg = true;
1919         break;
1920       }
1921
1922       // Otherwise must be an argument type.
1923       TypeLoc = Lex.getLoc();
1924       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1925
1926       if (ArgTy->isVoidTy())
1927         return Error(TypeLoc, "argument can not have void type");
1928
1929       if (Lex.getKind() == lltok::LocalVar) {
1930         Name = Lex.getStrVal();
1931         Lex.Lex();
1932       } else {
1933         Name = "";
1934       }
1935
1936       if (!ArgTy->isFirstClassType())
1937         return Error(TypeLoc, "invalid type for function argument");
1938
1939       ArgList.emplace_back(
1940           TypeLoc, ArgTy,
1941           AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1942           std::move(Name));
1943     }
1944   }
1945
1946   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1947 }
1948
1949 /// ParseFunctionType
1950 ///  ::= Type ArgumentList OptionalAttrs
1951 bool LLParser::ParseFunctionType(Type *&Result) {
1952   assert(Lex.getKind() == lltok::lparen);
1953
1954   if (!FunctionType::isValidReturnType(Result))
1955     return TokError("invalid function return type");
1956
1957   SmallVector<ArgInfo, 8> ArgList;
1958   bool isVarArg;
1959   if (ParseArgumentList(ArgList, isVarArg))
1960     return true;
1961
1962   // Reject names on the arguments lists.
1963   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1964     if (!ArgList[i].Name.empty())
1965       return Error(ArgList[i].Loc, "argument name invalid in function type");
1966     if (ArgList[i].Attrs.hasAttributes(i + 1))
1967       return Error(ArgList[i].Loc,
1968                    "argument attributes invalid in function type");
1969   }
1970
1971   SmallVector<Type*, 16> ArgListTy;
1972   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1973     ArgListTy.push_back(ArgList[i].Ty);
1974
1975   Result = FunctionType::get(Result, ArgListTy, isVarArg);
1976   return false;
1977 }
1978
1979 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1980 /// other structs.
1981 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1982   SmallVector<Type*, 8> Elts;
1983   if (ParseStructBody(Elts)) return true;
1984
1985   Result = StructType::get(Context, Elts, Packed);
1986   return false;
1987 }
1988
1989 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1990 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1991                                      std::pair<Type*, LocTy> &Entry,
1992                                      Type *&ResultTy) {
1993   // If the type was already defined, diagnose the redefinition.
1994   if (Entry.first && !Entry.second.isValid())
1995     return Error(TypeLoc, "redefinition of type");
1996
1997   // If we have opaque, just return without filling in the definition for the
1998   // struct.  This counts as a definition as far as the .ll file goes.
1999   if (EatIfPresent(lltok::kw_opaque)) {
2000     // This type is being defined, so clear the location to indicate this.
2001     Entry.second = SMLoc();
2002
2003     // If this type number has never been uttered, create it.
2004     if (!Entry.first)
2005       Entry.first = StructType::create(Context, Name);
2006     ResultTy = Entry.first;
2007     return false;
2008   }
2009
2010   // If the type starts with '<', then it is either a packed struct or a vector.
2011   bool isPacked = EatIfPresent(lltok::less);
2012
2013   // If we don't have a struct, then we have a random type alias, which we
2014   // accept for compatibility with old files.  These types are not allowed to be
2015   // forward referenced and not allowed to be recursive.
2016   if (Lex.getKind() != lltok::lbrace) {
2017     if (Entry.first)
2018       return Error(TypeLoc, "forward references to non-struct type");
2019
2020     ResultTy = nullptr;
2021     if (isPacked)
2022       return ParseArrayVectorType(ResultTy, true);
2023     return ParseType(ResultTy);
2024   }
2025
2026   // This type is being defined, so clear the location to indicate this.
2027   Entry.second = SMLoc();
2028
2029   // If this type number has never been uttered, create it.
2030   if (!Entry.first)
2031     Entry.first = StructType::create(Context, Name);
2032
2033   StructType *STy = cast<StructType>(Entry.first);
2034
2035   SmallVector<Type*, 8> Body;
2036   if (ParseStructBody(Body) ||
2037       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2038     return true;
2039
2040   STy->setBody(Body, isPacked);
2041   ResultTy = STy;
2042   return false;
2043 }
2044
2045
2046 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2047 ///   StructType
2048 ///     ::= '{' '}'
2049 ///     ::= '{' Type (',' Type)* '}'
2050 ///     ::= '<' '{' '}' '>'
2051 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2052 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2053   assert(Lex.getKind() == lltok::lbrace);
2054   Lex.Lex(); // Consume the '{'
2055
2056   // Handle the empty struct.
2057   if (EatIfPresent(lltok::rbrace))
2058     return false;
2059
2060   LocTy EltTyLoc = Lex.getLoc();
2061   Type *Ty = nullptr;
2062   if (ParseType(Ty)) return true;
2063   Body.push_back(Ty);
2064
2065   if (!StructType::isValidElementType(Ty))
2066     return Error(EltTyLoc, "invalid element type for struct");
2067
2068   while (EatIfPresent(lltok::comma)) {
2069     EltTyLoc = Lex.getLoc();
2070     if (ParseType(Ty)) return true;
2071
2072     if (!StructType::isValidElementType(Ty))
2073       return Error(EltTyLoc, "invalid element type for struct");
2074
2075     Body.push_back(Ty);
2076   }
2077
2078   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2079 }
2080
2081 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2082 /// token has already been consumed.
2083 ///   Type
2084 ///     ::= '[' APSINTVAL 'x' Types ']'
2085 ///     ::= '<' APSINTVAL 'x' Types '>'
2086 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2087   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2088       Lex.getAPSIntVal().getBitWidth() > 64)
2089     return TokError("expected number in address space");
2090
2091   LocTy SizeLoc = Lex.getLoc();
2092   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2093   Lex.Lex();
2094
2095   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2096       return true;
2097
2098   LocTy TypeLoc = Lex.getLoc();
2099   Type *EltTy = nullptr;
2100   if (ParseType(EltTy)) return true;
2101
2102   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2103                  "expected end of sequential type"))
2104     return true;
2105
2106   if (isVector) {
2107     if (Size == 0)
2108       return Error(SizeLoc, "zero element vector is illegal");
2109     if ((unsigned)Size != Size)
2110       return Error(SizeLoc, "size too large for vector");
2111     if (!VectorType::isValidElementType(EltTy))
2112       return Error(TypeLoc, "invalid vector element type");
2113     Result = VectorType::get(EltTy, unsigned(Size));
2114   } else {
2115     if (!ArrayType::isValidElementType(EltTy))
2116       return Error(TypeLoc, "invalid array element type");
2117     Result = ArrayType::get(EltTy, Size);
2118   }
2119   return false;
2120 }
2121
2122 //===----------------------------------------------------------------------===//
2123 // Function Semantic Analysis.
2124 //===----------------------------------------------------------------------===//
2125
2126 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2127                                              int functionNumber)
2128   : P(p), F(f), FunctionNumber(functionNumber) {
2129
2130   // Insert unnamed arguments into the NumberedVals list.
2131   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2132        AI != E; ++AI)
2133     if (!AI->hasName())
2134       NumberedVals.push_back(AI);
2135 }
2136
2137 LLParser::PerFunctionState::~PerFunctionState() {
2138   // If there were any forward referenced non-basicblock values, delete them.
2139   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2140        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2141     if (!isa<BasicBlock>(I->second.first)) {
2142       I->second.first->replaceAllUsesWith(
2143                            UndefValue::get(I->second.first->getType()));
2144       delete I->second.first;
2145       I->second.first = nullptr;
2146     }
2147
2148   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2149        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2150     if (!isa<BasicBlock>(I->second.first)) {
2151       I->second.first->replaceAllUsesWith(
2152                            UndefValue::get(I->second.first->getType()));
2153       delete I->second.first;
2154       I->second.first = nullptr;
2155     }
2156 }
2157
2158 bool LLParser::PerFunctionState::FinishFunction() {
2159   if (!ForwardRefVals.empty())
2160     return P.Error(ForwardRefVals.begin()->second.second,
2161                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2162                    "'");
2163   if (!ForwardRefValIDs.empty())
2164     return P.Error(ForwardRefValIDs.begin()->second.second,
2165                    "use of undefined value '%" +
2166                    Twine(ForwardRefValIDs.begin()->first) + "'");
2167   return false;
2168 }
2169
2170
2171 /// GetVal - Get a value with the specified name or ID, creating a
2172 /// forward reference record if needed.  This can return null if the value
2173 /// exists but does not have the right type.
2174 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2175                                           Type *Ty, LocTy Loc) {
2176   // Look this name up in the normal function symbol table.
2177   Value *Val = F.getValueSymbolTable().lookup(Name);
2178
2179   // If this is a forward reference for the value, see if we already created a
2180   // forward ref record.
2181   if (!Val) {
2182     std::map<std::string, std::pair<Value*, LocTy> >::iterator
2183       I = ForwardRefVals.find(Name);
2184     if (I != ForwardRefVals.end())
2185       Val = I->second.first;
2186   }
2187
2188   // If we have the value in the symbol table or fwd-ref table, return it.
2189   if (Val) {
2190     if (Val->getType() == Ty) return Val;
2191     if (Ty->isLabelTy())
2192       P.Error(Loc, "'%" + Name + "' is not a basic block");
2193     else
2194       P.Error(Loc, "'%" + Name + "' defined with type '" +
2195               getTypeString(Val->getType()) + "'");
2196     return nullptr;
2197   }
2198
2199   // Don't make placeholders with invalid type.
2200   if (!Ty->isFirstClassType()) {
2201     P.Error(Loc, "invalid use of a non-first-class type");
2202     return nullptr;
2203   }
2204
2205   // Otherwise, create a new forward reference for this value and remember it.
2206   Value *FwdVal;
2207   if (Ty->isLabelTy())
2208     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2209   else
2210     FwdVal = new Argument(Ty, Name);
2211
2212   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2213   return FwdVal;
2214 }
2215
2216 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2217                                           LocTy Loc) {
2218   // Look this name up in the normal function symbol table.
2219   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2220
2221   // If this is a forward reference for the value, see if we already created a
2222   // forward ref record.
2223   if (!Val) {
2224     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2225       I = ForwardRefValIDs.find(ID);
2226     if (I != ForwardRefValIDs.end())
2227       Val = I->second.first;
2228   }
2229
2230   // If we have the value in the symbol table or fwd-ref table, return it.
2231   if (Val) {
2232     if (Val->getType() == Ty) return Val;
2233     if (Ty->isLabelTy())
2234       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2235     else
2236       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2237               getTypeString(Val->getType()) + "'");
2238     return nullptr;
2239   }
2240
2241   if (!Ty->isFirstClassType()) {
2242     P.Error(Loc, "invalid use of a non-first-class type");
2243     return nullptr;
2244   }
2245
2246   // Otherwise, create a new forward reference for this value and remember it.
2247   Value *FwdVal;
2248   if (Ty->isLabelTy())
2249     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2250   else
2251     FwdVal = new Argument(Ty);
2252
2253   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2254   return FwdVal;
2255 }
2256
2257 /// SetInstName - After an instruction is parsed and inserted into its
2258 /// basic block, this installs its name.
2259 bool LLParser::PerFunctionState::SetInstName(int NameID,
2260                                              const std::string &NameStr,
2261                                              LocTy NameLoc, Instruction *Inst) {
2262   // If this instruction has void type, it cannot have a name or ID specified.
2263   if (Inst->getType()->isVoidTy()) {
2264     if (NameID != -1 || !NameStr.empty())
2265       return P.Error(NameLoc, "instructions returning void cannot have a name");
2266     return false;
2267   }
2268
2269   // If this was a numbered instruction, verify that the instruction is the
2270   // expected value and resolve any forward references.
2271   if (NameStr.empty()) {
2272     // If neither a name nor an ID was specified, just use the next ID.
2273     if (NameID == -1)
2274       NameID = NumberedVals.size();
2275
2276     if (unsigned(NameID) != NumberedVals.size())
2277       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2278                      Twine(NumberedVals.size()) + "'");
2279
2280     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2281       ForwardRefValIDs.find(NameID);
2282     if (FI != ForwardRefValIDs.end()) {
2283       if (FI->second.first->getType() != Inst->getType())
2284         return P.Error(NameLoc, "instruction forward referenced with type '" +
2285                        getTypeString(FI->second.first->getType()) + "'");
2286       FI->second.first->replaceAllUsesWith(Inst);
2287       delete FI->second.first;
2288       ForwardRefValIDs.erase(FI);
2289     }
2290
2291     NumberedVals.push_back(Inst);
2292     return false;
2293   }
2294
2295   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2296   std::map<std::string, std::pair<Value*, LocTy> >::iterator
2297     FI = ForwardRefVals.find(NameStr);
2298   if (FI != ForwardRefVals.end()) {
2299     if (FI->second.first->getType() != Inst->getType())
2300       return P.Error(NameLoc, "instruction forward referenced with type '" +
2301                      getTypeString(FI->second.first->getType()) + "'");
2302     FI->second.first->replaceAllUsesWith(Inst);
2303     delete FI->second.first;
2304     ForwardRefVals.erase(FI);
2305   }
2306
2307   // Set the name on the instruction.
2308   Inst->setName(NameStr);
2309
2310   if (Inst->getName() != NameStr)
2311     return P.Error(NameLoc, "multiple definition of local value named '" +
2312                    NameStr + "'");
2313   return false;
2314 }
2315
2316 /// GetBB - Get a basic block with the specified name or ID, creating a
2317 /// forward reference record if needed.
2318 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2319                                               LocTy Loc) {
2320   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2321                                       Type::getLabelTy(F.getContext()), Loc));
2322 }
2323
2324 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2325   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2326                                       Type::getLabelTy(F.getContext()), Loc));
2327 }
2328
2329 /// DefineBB - Define the specified basic block, which is either named or
2330 /// unnamed.  If there is an error, this returns null otherwise it returns
2331 /// the block being defined.
2332 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2333                                                  LocTy Loc) {
2334   BasicBlock *BB;
2335   if (Name.empty())
2336     BB = GetBB(NumberedVals.size(), Loc);
2337   else
2338     BB = GetBB(Name, Loc);
2339   if (!BB) return nullptr; // Already diagnosed error.
2340
2341   // Move the block to the end of the function.  Forward ref'd blocks are
2342   // inserted wherever they happen to be referenced.
2343   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2344
2345   // Remove the block from forward ref sets.
2346   if (Name.empty()) {
2347     ForwardRefValIDs.erase(NumberedVals.size());
2348     NumberedVals.push_back(BB);
2349   } else {
2350     // BB forward references are already in the function symbol table.
2351     ForwardRefVals.erase(Name);
2352   }
2353
2354   return BB;
2355 }
2356
2357 //===----------------------------------------------------------------------===//
2358 // Constants.
2359 //===----------------------------------------------------------------------===//
2360
2361 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2362 /// type implied.  For example, if we parse "4" we don't know what integer type
2363 /// it has.  The value will later be combined with its type and checked for
2364 /// sanity.  PFS is used to convert function-local operands of metadata (since
2365 /// metadata operands are not just parsed here but also converted to values).
2366 /// PFS can be null when we are not parsing metadata values inside a function.
2367 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2368   ID.Loc = Lex.getLoc();
2369   switch (Lex.getKind()) {
2370   default: return TokError("expected value token");
2371   case lltok::GlobalID:  // @42
2372     ID.UIntVal = Lex.getUIntVal();
2373     ID.Kind = ValID::t_GlobalID;
2374     break;
2375   case lltok::GlobalVar:  // @foo
2376     ID.StrVal = Lex.getStrVal();
2377     ID.Kind = ValID::t_GlobalName;
2378     break;
2379   case lltok::LocalVarID:  // %42
2380     ID.UIntVal = Lex.getUIntVal();
2381     ID.Kind = ValID::t_LocalID;
2382     break;
2383   case lltok::LocalVar:  // %foo
2384     ID.StrVal = Lex.getStrVal();
2385     ID.Kind = ValID::t_LocalName;
2386     break;
2387   case lltok::APSInt:
2388     ID.APSIntVal = Lex.getAPSIntVal();
2389     ID.Kind = ValID::t_APSInt;
2390     break;
2391   case lltok::APFloat:
2392     ID.APFloatVal = Lex.getAPFloatVal();
2393     ID.Kind = ValID::t_APFloat;
2394     break;
2395   case lltok::kw_true:
2396     ID.ConstantVal = ConstantInt::getTrue(Context);
2397     ID.Kind = ValID::t_Constant;
2398     break;
2399   case lltok::kw_false:
2400     ID.ConstantVal = ConstantInt::getFalse(Context);
2401     ID.Kind = ValID::t_Constant;
2402     break;
2403   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2404   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2405   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2406
2407   case lltok::lbrace: {
2408     // ValID ::= '{' ConstVector '}'
2409     Lex.Lex();
2410     SmallVector<Constant*, 16> Elts;
2411     if (ParseGlobalValueVector(Elts) ||
2412         ParseToken(lltok::rbrace, "expected end of struct constant"))
2413       return true;
2414
2415     ID.ConstantStructElts = new Constant*[Elts.size()];
2416     ID.UIntVal = Elts.size();
2417     memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2418     ID.Kind = ValID::t_ConstantStruct;
2419     return false;
2420   }
2421   case lltok::less: {
2422     // ValID ::= '<' ConstVector '>'         --> Vector.
2423     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2424     Lex.Lex();
2425     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2426
2427     SmallVector<Constant*, 16> Elts;
2428     LocTy FirstEltLoc = Lex.getLoc();
2429     if (ParseGlobalValueVector(Elts) ||
2430         (isPackedStruct &&
2431          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2432         ParseToken(lltok::greater, "expected end of constant"))
2433       return true;
2434
2435     if (isPackedStruct) {
2436       ID.ConstantStructElts = new Constant*[Elts.size()];
2437       memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2438       ID.UIntVal = Elts.size();
2439       ID.Kind = ValID::t_PackedConstantStruct;
2440       return false;
2441     }
2442
2443     if (Elts.empty())
2444       return Error(ID.Loc, "constant vector must not be empty");
2445
2446     if (!Elts[0]->getType()->isIntegerTy() &&
2447         !Elts[0]->getType()->isFloatingPointTy() &&
2448         !Elts[0]->getType()->isPointerTy())
2449       return Error(FirstEltLoc,
2450             "vector elements must have integer, pointer or floating point type");
2451
2452     // Verify that all the vector elements have the same type.
2453     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2454       if (Elts[i]->getType() != Elts[0]->getType())
2455         return Error(FirstEltLoc,
2456                      "vector element #" + Twine(i) +
2457                     " is not of type '" + getTypeString(Elts[0]->getType()));
2458
2459     ID.ConstantVal = ConstantVector::get(Elts);
2460     ID.Kind = ValID::t_Constant;
2461     return false;
2462   }
2463   case lltok::lsquare: {   // Array Constant
2464     Lex.Lex();
2465     SmallVector<Constant*, 16> Elts;
2466     LocTy FirstEltLoc = Lex.getLoc();
2467     if (ParseGlobalValueVector(Elts) ||
2468         ParseToken(lltok::rsquare, "expected end of array constant"))
2469       return true;
2470
2471     // Handle empty element.
2472     if (Elts.empty()) {
2473       // Use undef instead of an array because it's inconvenient to determine
2474       // the element type at this point, there being no elements to examine.
2475       ID.Kind = ValID::t_EmptyArray;
2476       return false;
2477     }
2478
2479     if (!Elts[0]->getType()->isFirstClassType())
2480       return Error(FirstEltLoc, "invalid array element type: " +
2481                    getTypeString(Elts[0]->getType()));
2482
2483     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2484
2485     // Verify all elements are correct type!
2486     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2487       if (Elts[i]->getType() != Elts[0]->getType())
2488         return Error(FirstEltLoc,
2489                      "array element #" + Twine(i) +
2490                      " is not of type '" + getTypeString(Elts[0]->getType()));
2491     }
2492
2493     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2494     ID.Kind = ValID::t_Constant;
2495     return false;
2496   }
2497   case lltok::kw_c:  // c "foo"
2498     Lex.Lex();
2499     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2500                                                   false);
2501     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2502     ID.Kind = ValID::t_Constant;
2503     return false;
2504
2505   case lltok::kw_asm: {
2506     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2507     //             STRINGCONSTANT
2508     bool HasSideEffect, AlignStack, AsmDialect;
2509     Lex.Lex();
2510     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2511         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2512         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2513         ParseStringConstant(ID.StrVal) ||
2514         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2515         ParseToken(lltok::StringConstant, "expected constraint string"))
2516       return true;
2517     ID.StrVal2 = Lex.getStrVal();
2518     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2519       (unsigned(AsmDialect)<<2);
2520     ID.Kind = ValID::t_InlineAsm;
2521     return false;
2522   }
2523
2524   case lltok::kw_blockaddress: {
2525     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2526     Lex.Lex();
2527
2528     ValID Fn, Label;
2529
2530     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2531         ParseValID(Fn) ||
2532         ParseToken(lltok::comma, "expected comma in block address expression")||
2533         ParseValID(Label) ||
2534         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2535       return true;
2536
2537     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2538       return Error(Fn.Loc, "expected function name in blockaddress");
2539     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2540       return Error(Label.Loc, "expected basic block name in blockaddress");
2541
2542     // Try to find the function (but skip it if it's forward-referenced).
2543     GlobalValue *GV = nullptr;
2544     if (Fn.Kind == ValID::t_GlobalID) {
2545       if (Fn.UIntVal < NumberedVals.size())
2546         GV = NumberedVals[Fn.UIntVal];
2547     } else if (!ForwardRefVals.count(Fn.StrVal)) {
2548       GV = M->getNamedValue(Fn.StrVal);
2549     }
2550     Function *F = nullptr;
2551     if (GV) {
2552       // Confirm that it's actually a function with a definition.
2553       if (!isa<Function>(GV))
2554         return Error(Fn.Loc, "expected function name in blockaddress");
2555       F = cast<Function>(GV);
2556       if (F->isDeclaration())
2557         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2558     }
2559
2560     if (!F) {
2561       // Make a global variable as a placeholder for this reference.
2562       GlobalValue *&FwdRef =
2563           ForwardRefBlockAddresses.insert(std::make_pair(
2564                                               std::move(Fn),
2565                                               std::map<ValID, GlobalValue *>()))
2566               .first->second.insert(std::make_pair(std::move(Label), nullptr))
2567               .first->second;
2568       if (!FwdRef)
2569         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2570                                     GlobalValue::InternalLinkage, nullptr, "");
2571       ID.ConstantVal = FwdRef;
2572       ID.Kind = ValID::t_Constant;
2573       return false;
2574     }
2575
2576     // We found the function; now find the basic block.  Don't use PFS, since we
2577     // might be inside a constant expression.
2578     BasicBlock *BB;
2579     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2580       if (Label.Kind == ValID::t_LocalID)
2581         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2582       else
2583         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2584       if (!BB)
2585         return Error(Label.Loc, "referenced value is not a basic block");
2586     } else {
2587       if (Label.Kind == ValID::t_LocalID)
2588         return Error(Label.Loc, "cannot take address of numeric label after "
2589                                 "the function is defined");
2590       BB = dyn_cast_or_null<BasicBlock>(
2591           F->getValueSymbolTable().lookup(Label.StrVal));
2592       if (!BB)
2593         return Error(Label.Loc, "referenced value is not a basic block");
2594     }
2595
2596     ID.ConstantVal = BlockAddress::get(F, BB);
2597     ID.Kind = ValID::t_Constant;
2598     return false;
2599   }
2600
2601   case lltok::kw_trunc:
2602   case lltok::kw_zext:
2603   case lltok::kw_sext:
2604   case lltok::kw_fptrunc:
2605   case lltok::kw_fpext:
2606   case lltok::kw_bitcast:
2607   case lltok::kw_addrspacecast:
2608   case lltok::kw_uitofp:
2609   case lltok::kw_sitofp:
2610   case lltok::kw_fptoui:
2611   case lltok::kw_fptosi:
2612   case lltok::kw_inttoptr:
2613   case lltok::kw_ptrtoint: {
2614     unsigned Opc = Lex.getUIntVal();
2615     Type *DestTy = nullptr;
2616     Constant *SrcVal;
2617     Lex.Lex();
2618     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2619         ParseGlobalTypeAndValue(SrcVal) ||
2620         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2621         ParseType(DestTy) ||
2622         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2623       return true;
2624     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2625       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2626                    getTypeString(SrcVal->getType()) + "' to '" +
2627                    getTypeString(DestTy) + "'");
2628     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2629                                                  SrcVal, DestTy);
2630     ID.Kind = ValID::t_Constant;
2631     return false;
2632   }
2633   case lltok::kw_extractvalue: {
2634     Lex.Lex();
2635     Constant *Val;
2636     SmallVector<unsigned, 4> Indices;
2637     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2638         ParseGlobalTypeAndValue(Val) ||
2639         ParseIndexList(Indices) ||
2640         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2641       return true;
2642
2643     if (!Val->getType()->isAggregateType())
2644       return Error(ID.Loc, "extractvalue operand must be aggregate type");
2645     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2646       return Error(ID.Loc, "invalid indices for extractvalue");
2647     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2648     ID.Kind = ValID::t_Constant;
2649     return false;
2650   }
2651   case lltok::kw_insertvalue: {
2652     Lex.Lex();
2653     Constant *Val0, *Val1;
2654     SmallVector<unsigned, 4> Indices;
2655     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2656         ParseGlobalTypeAndValue(Val0) ||
2657         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2658         ParseGlobalTypeAndValue(Val1) ||
2659         ParseIndexList(Indices) ||
2660         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2661       return true;
2662     if (!Val0->getType()->isAggregateType())
2663       return Error(ID.Loc, "insertvalue operand must be aggregate type");
2664     Type *IndexedType =
2665         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2666     if (!IndexedType)
2667       return Error(ID.Loc, "invalid indices for insertvalue");
2668     if (IndexedType != Val1->getType())
2669       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2670                                getTypeString(Val1->getType()) +
2671                                "' instead of '" + getTypeString(IndexedType) +
2672                                "'");
2673     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2674     ID.Kind = ValID::t_Constant;
2675     return false;
2676   }
2677   case lltok::kw_icmp:
2678   case lltok::kw_fcmp: {
2679     unsigned PredVal, Opc = Lex.getUIntVal();
2680     Constant *Val0, *Val1;
2681     Lex.Lex();
2682     if (ParseCmpPredicate(PredVal, Opc) ||
2683         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2684         ParseGlobalTypeAndValue(Val0) ||
2685         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2686         ParseGlobalTypeAndValue(Val1) ||
2687         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2688       return true;
2689
2690     if (Val0->getType() != Val1->getType())
2691       return Error(ID.Loc, "compare operands must have the same type");
2692
2693     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2694
2695     if (Opc == Instruction::FCmp) {
2696       if (!Val0->getType()->isFPOrFPVectorTy())
2697         return Error(ID.Loc, "fcmp requires floating point operands");
2698       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2699     } else {
2700       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2701       if (!Val0->getType()->isIntOrIntVectorTy() &&
2702           !Val0->getType()->getScalarType()->isPointerTy())
2703         return Error(ID.Loc, "icmp requires pointer or integer operands");
2704       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2705     }
2706     ID.Kind = ValID::t_Constant;
2707     return false;
2708   }
2709
2710   // Binary Operators.
2711   case lltok::kw_add:
2712   case lltok::kw_fadd:
2713   case lltok::kw_sub:
2714   case lltok::kw_fsub:
2715   case lltok::kw_mul:
2716   case lltok::kw_fmul:
2717   case lltok::kw_udiv:
2718   case lltok::kw_sdiv:
2719   case lltok::kw_fdiv:
2720   case lltok::kw_urem:
2721   case lltok::kw_srem:
2722   case lltok::kw_frem:
2723   case lltok::kw_shl:
2724   case lltok::kw_lshr:
2725   case lltok::kw_ashr: {
2726     bool NUW = false;
2727     bool NSW = false;
2728     bool Exact = false;
2729     unsigned Opc = Lex.getUIntVal();
2730     Constant *Val0, *Val1;
2731     Lex.Lex();
2732     LocTy ModifierLoc = Lex.getLoc();
2733     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2734         Opc == Instruction::Mul || Opc == Instruction::Shl) {
2735       if (EatIfPresent(lltok::kw_nuw))
2736         NUW = true;
2737       if (EatIfPresent(lltok::kw_nsw)) {
2738         NSW = true;
2739         if (EatIfPresent(lltok::kw_nuw))
2740           NUW = true;
2741       }
2742     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2743                Opc == Instruction::LShr || Opc == Instruction::AShr) {
2744       if (EatIfPresent(lltok::kw_exact))
2745         Exact = true;
2746     }
2747     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2748         ParseGlobalTypeAndValue(Val0) ||
2749         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2750         ParseGlobalTypeAndValue(Val1) ||
2751         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2752       return true;
2753     if (Val0->getType() != Val1->getType())
2754       return Error(ID.Loc, "operands of constexpr must have same type");
2755     if (!Val0->getType()->isIntOrIntVectorTy()) {
2756       if (NUW)
2757         return Error(ModifierLoc, "nuw only applies to integer operations");
2758       if (NSW)
2759         return Error(ModifierLoc, "nsw only applies to integer operations");
2760     }
2761     // Check that the type is valid for the operator.
2762     switch (Opc) {
2763     case Instruction::Add:
2764     case Instruction::Sub:
2765     case Instruction::Mul:
2766     case Instruction::UDiv:
2767     case Instruction::SDiv:
2768     case Instruction::URem:
2769     case Instruction::SRem:
2770     case Instruction::Shl:
2771     case Instruction::AShr:
2772     case Instruction::LShr:
2773       if (!Val0->getType()->isIntOrIntVectorTy())
2774         return Error(ID.Loc, "constexpr requires integer operands");
2775       break;
2776     case Instruction::FAdd:
2777     case Instruction::FSub:
2778     case Instruction::FMul:
2779     case Instruction::FDiv:
2780     case Instruction::FRem:
2781       if (!Val0->getType()->isFPOrFPVectorTy())
2782         return Error(ID.Loc, "constexpr requires fp operands");
2783       break;
2784     default: llvm_unreachable("Unknown binary operator!");
2785     }
2786     unsigned Flags = 0;
2787     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2788     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2789     if (Exact) Flags |= PossiblyExactOperator::IsExact;
2790     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2791     ID.ConstantVal = C;
2792     ID.Kind = ValID::t_Constant;
2793     return false;
2794   }
2795
2796   // Logical Operations
2797   case lltok::kw_and:
2798   case lltok::kw_or:
2799   case lltok::kw_xor: {
2800     unsigned Opc = Lex.getUIntVal();
2801     Constant *Val0, *Val1;
2802     Lex.Lex();
2803     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2804         ParseGlobalTypeAndValue(Val0) ||
2805         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2806         ParseGlobalTypeAndValue(Val1) ||
2807         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2808       return true;
2809     if (Val0->getType() != Val1->getType())
2810       return Error(ID.Loc, "operands of constexpr must have same type");
2811     if (!Val0->getType()->isIntOrIntVectorTy())
2812       return Error(ID.Loc,
2813                    "constexpr requires integer or integer vector operands");
2814     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2815     ID.Kind = ValID::t_Constant;
2816     return false;
2817   }
2818
2819   case lltok::kw_getelementptr:
2820   case lltok::kw_shufflevector:
2821   case lltok::kw_insertelement:
2822   case lltok::kw_extractelement:
2823   case lltok::kw_select: {
2824     unsigned Opc = Lex.getUIntVal();
2825     SmallVector<Constant*, 16> Elts;
2826     bool InBounds = false;
2827     Type *Ty;
2828     Lex.Lex();
2829
2830     if (Opc == Instruction::GetElementPtr)
2831       InBounds = EatIfPresent(lltok::kw_inbounds);
2832
2833     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2834       return true;
2835
2836     LocTy ExplicitTypeLoc = Lex.getLoc();
2837     if (Opc == Instruction::GetElementPtr) {
2838       if (ParseType(Ty) ||
2839           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2840         return true;
2841     }
2842
2843     if (ParseGlobalValueVector(Elts) ||
2844         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2845       return true;
2846
2847     if (Opc == Instruction::GetElementPtr) {
2848       if (Elts.size() == 0 ||
2849           !Elts[0]->getType()->getScalarType()->isPointerTy())
2850         return Error(ID.Loc, "base of getelementptr must be a pointer");
2851
2852       Type *BaseType = Elts[0]->getType();
2853       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2854       if (Ty != BasePointerType->getElementType())
2855         return Error(
2856             ExplicitTypeLoc,
2857             "explicit pointee type doesn't match operand's pointee type");
2858
2859       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2860       for (Constant *Val : Indices) {
2861         Type *ValTy = Val->getType();
2862         if (!ValTy->getScalarType()->isIntegerTy())
2863           return Error(ID.Loc, "getelementptr index must be an integer");
2864         if (ValTy->isVectorTy() != BaseType->isVectorTy())
2865           return Error(ID.Loc, "getelementptr index type missmatch");
2866         if (ValTy->isVectorTy()) {
2867           unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2868           unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2869           if (ValNumEl != PtrNumEl)
2870             return Error(
2871                 ID.Loc,
2872                 "getelementptr vector index has a wrong number of elements");
2873         }
2874       }
2875
2876       SmallPtrSet<const Type*, 4> Visited;
2877       if (!Indices.empty() && !Ty->isSized(&Visited))
2878         return Error(ID.Loc, "base element of getelementptr must be sized");
2879
2880       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2881         return Error(ID.Loc, "invalid getelementptr indices");
2882       ID.ConstantVal =
2883           ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2884     } else if (Opc == Instruction::Select) {
2885       if (Elts.size() != 3)
2886         return Error(ID.Loc, "expected three operands to select");
2887       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2888                                                               Elts[2]))
2889         return Error(ID.Loc, Reason);
2890       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2891     } else if (Opc == Instruction::ShuffleVector) {
2892       if (Elts.size() != 3)
2893         return Error(ID.Loc, "expected three operands to shufflevector");
2894       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2895         return Error(ID.Loc, "invalid operands to shufflevector");
2896       ID.ConstantVal =
2897                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2898     } else if (Opc == Instruction::ExtractElement) {
2899       if (Elts.size() != 2)
2900         return Error(ID.Loc, "expected two operands to extractelement");
2901       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2902         return Error(ID.Loc, "invalid extractelement operands");
2903       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2904     } else {
2905       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2906       if (Elts.size() != 3)
2907       return Error(ID.Loc, "expected three operands to insertelement");
2908       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2909         return Error(ID.Loc, "invalid insertelement operands");
2910       ID.ConstantVal =
2911                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2912     }
2913
2914     ID.Kind = ValID::t_Constant;
2915     return false;
2916   }
2917   }
2918
2919   Lex.Lex();
2920   return false;
2921 }
2922
2923 /// ParseGlobalValue - Parse a global value with the specified type.
2924 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2925   C = nullptr;
2926   ValID ID;
2927   Value *V = nullptr;
2928   bool Parsed = ParseValID(ID) ||
2929                 ConvertValIDToValue(Ty, ID, V, nullptr);
2930   if (V && !(C = dyn_cast<Constant>(V)))
2931     return Error(ID.Loc, "global values must be constants");
2932   return Parsed;
2933 }
2934
2935 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2936   Type *Ty = nullptr;
2937   return ParseType(Ty) ||
2938          ParseGlobalValue(Ty, V);
2939 }
2940
2941 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2942   C = nullptr;
2943
2944   LocTy KwLoc = Lex.getLoc();
2945   if (!EatIfPresent(lltok::kw_comdat))
2946     return false;
2947
2948   if (EatIfPresent(lltok::lparen)) {
2949     if (Lex.getKind() != lltok::ComdatVar)
2950       return TokError("expected comdat variable");
2951     C = getComdat(Lex.getStrVal(), Lex.getLoc());
2952     Lex.Lex();
2953     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2954       return true;
2955   } else {
2956     if (GlobalName.empty())
2957       return TokError("comdat cannot be unnamed");
2958     C = getComdat(GlobalName, KwLoc);
2959   }
2960
2961   return false;
2962 }
2963
2964 /// ParseGlobalValueVector
2965 ///   ::= /*empty*/
2966 ///   ::= TypeAndValue (',' TypeAndValue)*
2967 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2968   // Empty list.
2969   if (Lex.getKind() == lltok::rbrace ||
2970       Lex.getKind() == lltok::rsquare ||
2971       Lex.getKind() == lltok::greater ||
2972       Lex.getKind() == lltok::rparen)
2973     return false;
2974
2975   Constant *C;
2976   if (ParseGlobalTypeAndValue(C)) return true;
2977   Elts.push_back(C);
2978
2979   while (EatIfPresent(lltok::comma)) {
2980     if (ParseGlobalTypeAndValue(C)) return true;
2981     Elts.push_back(C);
2982   }
2983
2984   return false;
2985 }
2986
2987 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2988   SmallVector<Metadata *, 16> Elts;
2989   if (ParseMDNodeVector(Elts))
2990     return true;
2991
2992   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2993   return false;
2994 }
2995
2996 /// MDNode:
2997 ///  ::= !{ ... }
2998 ///  ::= !7
2999 ///  ::= !DILocation(...)
3000 bool LLParser::ParseMDNode(MDNode *&N) {
3001   if (Lex.getKind() == lltok::MetadataVar)
3002     return ParseSpecializedMDNode(N);
3003
3004   return ParseToken(lltok::exclaim, "expected '!' here") ||
3005          ParseMDNodeTail(N);
3006 }
3007
3008 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3009   // !{ ... }
3010   if (Lex.getKind() == lltok::lbrace)
3011     return ParseMDTuple(N);
3012
3013   // !42
3014   return ParseMDNodeID(N);
3015 }
3016
3017 namespace {
3018
3019 /// Structure to represent an optional metadata field.
3020 template <class FieldTy> struct MDFieldImpl {
3021   typedef MDFieldImpl ImplTy;
3022   FieldTy Val;
3023   bool Seen;
3024
3025   void assign(FieldTy Val) {
3026     Seen = true;
3027     this->Val = std::move(Val);
3028   }
3029
3030   explicit MDFieldImpl(FieldTy Default)
3031       : Val(std::move(Default)), Seen(false) {}
3032 };
3033
3034 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3035   uint64_t Max;
3036
3037   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3038       : ImplTy(Default), Max(Max) {}
3039 };
3040 struct LineField : public MDUnsignedField {
3041   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3042 };
3043 struct ColumnField : public MDUnsignedField {
3044   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3045 };
3046 struct DwarfTagField : public MDUnsignedField {
3047   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3048   DwarfTagField(dwarf::Tag DefaultTag)
3049       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3050 };
3051 struct DwarfAttEncodingField : public MDUnsignedField {
3052   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3053 };
3054 struct DwarfVirtualityField : public MDUnsignedField {
3055   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3056 };
3057 struct DwarfLangField : public MDUnsignedField {
3058   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3059 };
3060
3061 struct DIFlagField : public MDUnsignedField {
3062   DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3063 };
3064
3065 struct MDSignedField : public MDFieldImpl<int64_t> {
3066   int64_t Min;
3067   int64_t Max;
3068
3069   MDSignedField(int64_t Default = 0)
3070       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3071   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3072       : ImplTy(Default), Min(Min), Max(Max) {}
3073 };
3074
3075 struct MDBoolField : public MDFieldImpl<bool> {
3076   MDBoolField(bool Default = false) : ImplTy(Default) {}
3077 };
3078 struct MDField : public MDFieldImpl<Metadata *> {
3079   bool AllowNull;
3080
3081   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3082 };
3083 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3084   MDConstant() : ImplTy(nullptr) {}
3085 };
3086 struct MDStringField : public MDFieldImpl<MDString *> {
3087   bool AllowEmpty;
3088   MDStringField(bool AllowEmpty = true)
3089       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3090 };
3091 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3092   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3093 };
3094
3095 } // end namespace
3096
3097 namespace llvm {
3098
3099 template <>
3100 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3101                             MDUnsignedField &Result) {
3102   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3103     return TokError("expected unsigned integer");
3104
3105   auto &U = Lex.getAPSIntVal();
3106   if (U.ugt(Result.Max))
3107     return TokError("value for '" + Name + "' too large, limit is " +
3108                     Twine(Result.Max));
3109   Result.assign(U.getZExtValue());
3110   assert(Result.Val <= Result.Max && "Expected value in range");
3111   Lex.Lex();
3112   return false;
3113 }
3114
3115 template <>
3116 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3117   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3118 }
3119 template <>
3120 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3121   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3122 }
3123
3124 template <>
3125 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3126   if (Lex.getKind() == lltok::APSInt)
3127     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3128
3129   if (Lex.getKind() != lltok::DwarfTag)
3130     return TokError("expected DWARF tag");
3131
3132   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3133   if (Tag == dwarf::DW_TAG_invalid)
3134     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3135   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3136
3137   Result.assign(Tag);
3138   Lex.Lex();
3139   return false;
3140 }
3141
3142 template <>
3143 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3144                             DwarfVirtualityField &Result) {
3145   if (Lex.getKind() == lltok::APSInt)
3146     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3147
3148   if (Lex.getKind() != lltok::DwarfVirtuality)
3149     return TokError("expected DWARF virtuality code");
3150
3151   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3152   if (!Virtuality)
3153     return TokError("invalid DWARF virtuality code" + Twine(" '") +
3154                     Lex.getStrVal() + "'");
3155   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3156   Result.assign(Virtuality);
3157   Lex.Lex();
3158   return false;
3159 }
3160
3161 template <>
3162 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3163   if (Lex.getKind() == lltok::APSInt)
3164     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3165
3166   if (Lex.getKind() != lltok::DwarfLang)
3167     return TokError("expected DWARF language");
3168
3169   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3170   if (!Lang)
3171     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3172                     "'");
3173   assert(Lang <= Result.Max && "Expected valid DWARF language");
3174   Result.assign(Lang);
3175   Lex.Lex();
3176   return false;
3177 }
3178
3179 template <>
3180 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3181                             DwarfAttEncodingField &Result) {
3182   if (Lex.getKind() == lltok::APSInt)
3183     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3184
3185   if (Lex.getKind() != lltok::DwarfAttEncoding)
3186     return TokError("expected DWARF type attribute encoding");
3187
3188   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3189   if (!Encoding)
3190     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3191                     Lex.getStrVal() + "'");
3192   assert(Encoding <= Result.Max && "Expected valid DWARF language");
3193   Result.assign(Encoding);
3194   Lex.Lex();
3195   return false;
3196 }
3197
3198 /// DIFlagField
3199 ///  ::= uint32
3200 ///  ::= DIFlagVector
3201 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3202 template <>
3203 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3204   assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3205
3206   // Parser for a single flag.
3207   auto parseFlag = [&](unsigned &Val) {
3208     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3209       return ParseUInt32(Val);
3210
3211     if (Lex.getKind() != lltok::DIFlag)
3212       return TokError("expected debug info flag");
3213
3214     Val = DINode::getFlag(Lex.getStrVal());
3215     if (!Val)
3216       return TokError(Twine("invalid debug info flag flag '") +
3217                       Lex.getStrVal() + "'");
3218     Lex.Lex();
3219     return false;
3220   };
3221
3222   // Parse the flags and combine them together.
3223   unsigned Combined = 0;
3224   do {
3225     unsigned Val;
3226     if (parseFlag(Val))
3227       return true;
3228     Combined |= Val;
3229   } while (EatIfPresent(lltok::bar));
3230
3231   Result.assign(Combined);
3232   return false;
3233 }
3234
3235 template <>
3236 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3237                             MDSignedField &Result) {
3238   if (Lex.getKind() != lltok::APSInt)
3239     return TokError("expected signed integer");
3240
3241   auto &S = Lex.getAPSIntVal();
3242   if (S < Result.Min)
3243     return TokError("value for '" + Name + "' too small, limit is " +
3244                     Twine(Result.Min));
3245   if (S > Result.Max)
3246     return TokError("value for '" + Name + "' too large, limit is " +
3247                     Twine(Result.Max));
3248   Result.assign(S.getExtValue());
3249   assert(Result.Val >= Result.Min && "Expected value in range");
3250   assert(Result.Val <= Result.Max && "Expected value in range");
3251   Lex.Lex();
3252   return false;
3253 }
3254
3255 template <>
3256 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3257   switch (Lex.getKind()) {
3258   default:
3259     return TokError("expected 'true' or 'false'");
3260   case lltok::kw_true:
3261     Result.assign(true);
3262     break;
3263   case lltok::kw_false:
3264     Result.assign(false);
3265     break;
3266   }
3267   Lex.Lex();
3268   return false;
3269 }
3270
3271 template <>
3272 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3273   if (Lex.getKind() == lltok::kw_null) {
3274     if (!Result.AllowNull)
3275       return TokError("'" + Name + "' cannot be null");
3276     Lex.Lex();
3277     Result.assign(nullptr);
3278     return false;
3279   }
3280
3281   Metadata *MD;
3282   if (ParseMetadata(MD, nullptr))
3283     return true;
3284
3285   Result.assign(MD);
3286   return false;
3287 }
3288
3289 template <>
3290 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3291   Metadata *MD;
3292   if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3293     return true;
3294
3295   Result.assign(cast<ConstantAsMetadata>(MD));
3296   return false;
3297 }
3298
3299 template <>
3300 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3301   LocTy ValueLoc = Lex.getLoc();
3302   std::string S;
3303   if (ParseStringConstant(S))
3304     return true;
3305
3306   if (!Result.AllowEmpty && S.empty())
3307     return Error(ValueLoc, "'" + Name + "' cannot be empty");
3308
3309   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3310   return false;
3311 }
3312
3313 template <>
3314 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3315   SmallVector<Metadata *, 4> MDs;
3316   if (ParseMDNodeVector(MDs))
3317     return true;
3318
3319   Result.assign(std::move(MDs));
3320   return false;
3321 }
3322
3323 } // end namespace llvm
3324
3325 template <class ParserTy>
3326 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3327   do {
3328     if (Lex.getKind() != lltok::LabelStr)
3329       return TokError("expected field label here");
3330
3331     if (parseField())
3332       return true;
3333   } while (EatIfPresent(lltok::comma));
3334
3335   return false;
3336 }
3337
3338 template <class ParserTy>
3339 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3340   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3341   Lex.Lex();
3342
3343   if (ParseToken(lltok::lparen, "expected '(' here"))
3344     return true;
3345   if (Lex.getKind() != lltok::rparen)
3346     if (ParseMDFieldsImplBody(parseField))
3347       return true;
3348
3349   ClosingLoc = Lex.getLoc();
3350   return ParseToken(lltok::rparen, "expected ')' here");
3351 }
3352
3353 template <class FieldTy>
3354 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3355   if (Result.Seen)
3356     return TokError("field '" + Name + "' cannot be specified more than once");
3357
3358   LocTy Loc = Lex.getLoc();
3359   Lex.Lex();
3360   return ParseMDField(Loc, Name, Result);
3361 }
3362
3363 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3364   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3365
3366 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
3367   if (Lex.getStrVal() == #CLASS)                                               \
3368     return Parse##CLASS(N, IsDistinct);
3369 #include "llvm/IR/Metadata.def"
3370
3371   return TokError("expected metadata type");
3372 }
3373
3374 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3375 #define NOP_FIELD(NAME, TYPE, INIT)
3376 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
3377   if (!NAME.Seen)                                                              \
3378     return Error(ClosingLoc, "missing required field '" #NAME "'");
3379 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
3380   if (Lex.getStrVal() == #NAME)                                                \
3381     return ParseMDField(#NAME, NAME);
3382 #define PARSE_MD_FIELDS()                                                      \
3383   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
3384   do {                                                                         \
3385     LocTy ClosingLoc;                                                          \
3386     if (ParseMDFieldsImpl([&]() -> bool {                                      \
3387       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
3388       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
3389     }, ClosingLoc))                                                            \
3390       return true;                                                             \
3391     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
3392   } while (false)
3393 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
3394   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3395
3396 /// ParseDILocationFields:
3397 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3398 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3399 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3400   OPTIONAL(line, LineField, );                                                 \
3401   OPTIONAL(column, ColumnField, );                                             \
3402   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3403   OPTIONAL(inlinedAt, MDField, );
3404   PARSE_MD_FIELDS();
3405 #undef VISIT_MD_FIELDS
3406
3407   Result = GET_OR_DISTINCT(
3408       DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3409   return false;
3410 }
3411
3412 /// ParseGenericDINode:
3413 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3414 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3415 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3416   REQUIRED(tag, DwarfTagField, );                                              \
3417   OPTIONAL(header, MDStringField, );                                           \
3418   OPTIONAL(operands, MDFieldList, );
3419   PARSE_MD_FIELDS();
3420 #undef VISIT_MD_FIELDS
3421
3422   Result = GET_OR_DISTINCT(GenericDINode,
3423                            (Context, tag.Val, header.Val, operands.Val));
3424   return false;
3425 }
3426
3427 /// ParseDISubrange:
3428 ///   ::= !DISubrange(count: 30, lowerBound: 2)
3429 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3430 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3431   REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX));                         \
3432   OPTIONAL(lowerBound, MDSignedField, );
3433   PARSE_MD_FIELDS();
3434 #undef VISIT_MD_FIELDS
3435
3436   Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3437   return false;
3438 }
3439
3440 /// ParseDIEnumerator:
3441 ///   ::= !DIEnumerator(value: 30, name: "SomeKind")
3442 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3443 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3444   REQUIRED(name, MDStringField, );                                             \
3445   REQUIRED(value, MDSignedField, );
3446   PARSE_MD_FIELDS();
3447 #undef VISIT_MD_FIELDS
3448
3449   Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3450   return false;
3451 }
3452
3453 /// ParseDIBasicType:
3454 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3455 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3456 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3457   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
3458   OPTIONAL(name, MDStringField, );                                             \
3459   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3460   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3461   OPTIONAL(encoding, DwarfAttEncodingField, );
3462   PARSE_MD_FIELDS();
3463 #undef VISIT_MD_FIELDS
3464
3465   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3466                                          align.Val, encoding.Val));
3467   return false;
3468 }
3469
3470 /// ParseDIDerivedType:
3471 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3472 ///                      line: 7, scope: !1, baseType: !2, size: 32,
3473 ///                      align: 32, offset: 0, flags: 0, extraData: !3)
3474 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3475 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3476   REQUIRED(tag, DwarfTagField, );                                              \
3477   OPTIONAL(name, MDStringField, );                                             \
3478   OPTIONAL(file, MDField, );                                                   \
3479   OPTIONAL(line, LineField, );                                                 \
3480   OPTIONAL(scope, MDField, );                                                  \
3481   REQUIRED(baseType, MDField, );                                               \
3482   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3483   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3484   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3485   OPTIONAL(flags, DIFlagField, );                                              \
3486   OPTIONAL(extraData, MDField, );
3487   PARSE_MD_FIELDS();
3488 #undef VISIT_MD_FIELDS
3489
3490   Result = GET_OR_DISTINCT(DIDerivedType,
3491                            (Context, tag.Val, name.Val, file.Val, line.Val,
3492                             scope.Val, baseType.Val, size.Val, align.Val,
3493                             offset.Val, flags.Val, extraData.Val));
3494   return false;
3495 }
3496
3497 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3498 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3499   REQUIRED(tag, DwarfTagField, );                                              \
3500   OPTIONAL(name, MDStringField, );                                             \
3501   OPTIONAL(file, MDField, );                                                   \
3502   OPTIONAL(line, LineField, );                                                 \
3503   OPTIONAL(scope, MDField, );                                                  \
3504   OPTIONAL(baseType, MDField, );                                               \
3505   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3506   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3507   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3508   OPTIONAL(flags, DIFlagField, );                                              \
3509   OPTIONAL(elements, MDField, );                                               \
3510   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
3511   OPTIONAL(vtableHolder, MDField, );                                           \
3512   OPTIONAL(templateParams, MDField, );                                         \
3513   OPTIONAL(identifier, MDStringField, );
3514   PARSE_MD_FIELDS();
3515 #undef VISIT_MD_FIELDS
3516
3517   Result = GET_OR_DISTINCT(
3518       DICompositeType,
3519       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3520        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3521        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3522   return false;
3523 }
3524
3525 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3526 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3527   OPTIONAL(flags, DIFlagField, );                                              \
3528   REQUIRED(types, MDField, );
3529   PARSE_MD_FIELDS();
3530 #undef VISIT_MD_FIELDS
3531
3532   Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3533   return false;
3534 }
3535
3536 /// ParseDIFileType:
3537 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3538 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3539 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3540   REQUIRED(filename, MDStringField, );                                         \
3541   REQUIRED(directory, MDStringField, );
3542   PARSE_MD_FIELDS();
3543 #undef VISIT_MD_FIELDS
3544
3545   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3546   return false;
3547 }
3548
3549 /// ParseDICompileUnit:
3550 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3551 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
3552 ///                      splitDebugFilename: "abc.debug", emissionKind: 1,
3553 ///                      enums: !1, retainedTypes: !2, subprograms: !3,
3554 ///                      globals: !4, imports: !5, dwoId: 0x0abcd)
3555 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3556 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3557   REQUIRED(language, DwarfLangField, );                                        \
3558   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
3559   OPTIONAL(producer, MDStringField, );                                         \
3560   OPTIONAL(isOptimized, MDBoolField, );                                        \
3561   OPTIONAL(flags, MDStringField, );                                            \
3562   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
3563   OPTIONAL(splitDebugFilename, MDStringField, );                               \
3564   OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX));                    \
3565   OPTIONAL(enums, MDField, );                                                  \
3566   OPTIONAL(retainedTypes, MDField, );                                          \
3567   OPTIONAL(subprograms, MDField, );                                            \
3568   OPTIONAL(globals, MDField, );                                                \
3569   OPTIONAL(imports, MDField, );                                                \
3570   OPTIONAL(dwoId, MDUnsignedField, );
3571   PARSE_MD_FIELDS();
3572 #undef VISIT_MD_FIELDS
3573
3574   Result = GET_OR_DISTINCT(DICompileUnit,
3575                            (Context, language.Val, file.Val, producer.Val,
3576                             isOptimized.Val, flags.Val, runtimeVersion.Val,
3577                             splitDebugFilename.Val, emissionKind.Val, enums.Val,
3578                             retainedTypes.Val, subprograms.Val, globals.Val,
3579                             imports.Val, dwoId.Val));
3580   return false;
3581 }
3582
3583 /// ParseDISubprogram:
3584 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3585 ///                     file: !1, line: 7, type: !2, isLocal: false,
3586 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
3587 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
3588 ///                     virtualIndex: 10, flags: 11,
3589 ///                     isOptimized: false, function: void ()* @_Z3foov,
3590 ///                     templateParams: !4, declaration: !5, variables: !6)
3591 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3592 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3593   OPTIONAL(scope, MDField, );                                                  \
3594   OPTIONAL(name, MDStringField, );                                             \
3595   OPTIONAL(linkageName, MDStringField, );                                      \
3596   OPTIONAL(file, MDField, );                                                   \
3597   OPTIONAL(line, LineField, );                                                 \
3598   OPTIONAL(type, MDField, );                                                   \
3599   OPTIONAL(isLocal, MDBoolField, );                                            \
3600   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3601   OPTIONAL(scopeLine, LineField, );                                            \
3602   OPTIONAL(containingType, MDField, );                                         \
3603   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
3604   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
3605   OPTIONAL(flags, DIFlagField, );                                              \
3606   OPTIONAL(isOptimized, MDBoolField, );                                        \
3607   OPTIONAL(function, MDConstant, );                                            \
3608   OPTIONAL(templateParams, MDField, );                                         \
3609   OPTIONAL(declaration, MDField, );                                            \
3610   OPTIONAL(variables, MDField, );
3611   PARSE_MD_FIELDS();
3612 #undef VISIT_MD_FIELDS
3613
3614   Result = GET_OR_DISTINCT(
3615       DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3616                      line.Val, type.Val, isLocal.Val, isDefinition.Val,
3617                      scopeLine.Val, containingType.Val, virtuality.Val,
3618                      virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3619                      templateParams.Val, declaration.Val, variables.Val));
3620   return false;
3621 }
3622
3623 /// ParseDILexicalBlock:
3624 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3625 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3626 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3627   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3628   OPTIONAL(file, MDField, );                                                   \
3629   OPTIONAL(line, LineField, );                                                 \
3630   OPTIONAL(column, ColumnField, );
3631   PARSE_MD_FIELDS();
3632 #undef VISIT_MD_FIELDS
3633
3634   Result = GET_OR_DISTINCT(
3635       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3636   return false;
3637 }
3638
3639 /// ParseDILexicalBlockFile:
3640 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3641 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3642 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3643   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3644   OPTIONAL(file, MDField, );                                                   \
3645   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3646   PARSE_MD_FIELDS();
3647 #undef VISIT_MD_FIELDS
3648
3649   Result = GET_OR_DISTINCT(DILexicalBlockFile,
3650                            (Context, scope.Val, file.Val, discriminator.Val));
3651   return false;
3652 }
3653
3654 /// ParseDINamespace:
3655 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3656 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3657 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3658   REQUIRED(scope, MDField, );                                                  \
3659   OPTIONAL(file, MDField, );                                                   \
3660   OPTIONAL(name, MDStringField, );                                             \
3661   OPTIONAL(line, LineField, );
3662   PARSE_MD_FIELDS();
3663 #undef VISIT_MD_FIELDS
3664
3665   Result = GET_OR_DISTINCT(DINamespace,
3666                            (Context, scope.Val, file.Val, name.Val, line.Val));
3667   return false;
3668 }
3669
3670 /// ParseDITemplateTypeParameter:
3671 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3672 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3673 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3674   OPTIONAL(name, MDStringField, );                                             \
3675   REQUIRED(type, MDField, );
3676   PARSE_MD_FIELDS();
3677 #undef VISIT_MD_FIELDS
3678
3679   Result =
3680       GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3681   return false;
3682 }
3683
3684 /// ParseDITemplateValueParameter:
3685 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3686 ///                                 name: "V", type: !1, value: i32 7)
3687 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3688 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3689   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
3690   OPTIONAL(name, MDStringField, );                                             \
3691   OPTIONAL(type, MDField, );                                                   \
3692   REQUIRED(value, MDField, );
3693   PARSE_MD_FIELDS();
3694 #undef VISIT_MD_FIELDS
3695
3696   Result = GET_OR_DISTINCT(DITemplateValueParameter,
3697                            (Context, tag.Val, name.Val, type.Val, value.Val));
3698   return false;
3699 }
3700
3701 /// ParseDIGlobalVariable:
3702 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3703 ///                         file: !1, line: 7, type: !2, isLocal: false,
3704 ///                         isDefinition: true, variable: i32* @foo,
3705 ///                         declaration: !3)
3706 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3707 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3708   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
3709   OPTIONAL(scope, MDField, );                                                  \
3710   OPTIONAL(linkageName, MDStringField, );                                      \
3711   OPTIONAL(file, MDField, );                                                   \
3712   OPTIONAL(line, LineField, );                                                 \
3713   OPTIONAL(type, MDField, );                                                   \
3714   OPTIONAL(isLocal, MDBoolField, );                                            \
3715   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3716   OPTIONAL(variable, MDConstant, );                                            \
3717   OPTIONAL(declaration, MDField, );
3718   PARSE_MD_FIELDS();
3719 #undef VISIT_MD_FIELDS
3720
3721   Result = GET_OR_DISTINCT(DIGlobalVariable,
3722                            (Context, scope.Val, name.Val, linkageName.Val,
3723                             file.Val, line.Val, type.Val, isLocal.Val,
3724                             isDefinition.Val, variable.Val, declaration.Val));
3725   return false;
3726 }
3727
3728 /// ParseDILocalVariable:
3729 ///   ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3730 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7)
3731 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3732 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3733   REQUIRED(tag, DwarfTagField, );                                              \
3734   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3735   OPTIONAL(name, MDStringField, );                                             \
3736   OPTIONAL(file, MDField, );                                                   \
3737   OPTIONAL(line, LineField, );                                                 \
3738   OPTIONAL(type, MDField, );                                                   \
3739   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
3740   OPTIONAL(flags, DIFlagField, );
3741   PARSE_MD_FIELDS();
3742 #undef VISIT_MD_FIELDS
3743
3744   Result = GET_OR_DISTINCT(DILocalVariable,
3745                            (Context, tag.Val, scope.Val, name.Val, file.Val,
3746                             line.Val, type.Val, arg.Val, flags.Val));
3747   return false;
3748 }
3749
3750 /// ParseDIExpression:
3751 ///   ::= !DIExpression(0, 7, -1)
3752 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3753   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3754   Lex.Lex();
3755
3756   if (ParseToken(lltok::lparen, "expected '(' here"))
3757     return true;
3758
3759   SmallVector<uint64_t, 8> Elements;
3760   if (Lex.getKind() != lltok::rparen)
3761     do {
3762       if (Lex.getKind() == lltok::DwarfOp) {
3763         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3764           Lex.Lex();
3765           Elements.push_back(Op);
3766           continue;
3767         }
3768         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3769       }
3770
3771       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3772         return TokError("expected unsigned integer");
3773
3774       auto &U = Lex.getAPSIntVal();
3775       if (U.ugt(UINT64_MAX))
3776         return TokError("element too large, limit is " + Twine(UINT64_MAX));
3777       Elements.push_back(U.getZExtValue());
3778       Lex.Lex();
3779     } while (EatIfPresent(lltok::comma));
3780
3781   if (ParseToken(lltok::rparen, "expected ')' here"))
3782     return true;
3783
3784   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3785   return false;
3786 }
3787
3788 /// ParseDIObjCProperty:
3789 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3790 ///                       getter: "getFoo", attributes: 7, type: !2)
3791 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3792 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3793   OPTIONAL(name, MDStringField, );                                             \
3794   OPTIONAL(file, MDField, );                                                   \
3795   OPTIONAL(line, LineField, );                                                 \
3796   OPTIONAL(setter, MDStringField, );                                           \
3797   OPTIONAL(getter, MDStringField, );                                           \
3798   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
3799   OPTIONAL(type, MDField, );
3800   PARSE_MD_FIELDS();
3801 #undef VISIT_MD_FIELDS
3802
3803   Result = GET_OR_DISTINCT(DIObjCProperty,
3804                            (Context, name.Val, file.Val, line.Val, setter.Val,
3805                             getter.Val, attributes.Val, type.Val));
3806   return false;
3807 }
3808
3809 /// ParseDIImportedEntity:
3810 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3811 ///                         line: 7, name: "foo")
3812 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3813 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3814   REQUIRED(tag, DwarfTagField, );                                              \
3815   REQUIRED(scope, MDField, );                                                  \
3816   OPTIONAL(entity, MDField, );                                                 \
3817   OPTIONAL(line, LineField, );                                                 \
3818   OPTIONAL(name, MDStringField, );
3819   PARSE_MD_FIELDS();
3820 #undef VISIT_MD_FIELDS
3821
3822   Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3823                                               entity.Val, line.Val, name.Val));
3824   return false;
3825 }
3826
3827 #undef PARSE_MD_FIELD
3828 #undef NOP_FIELD
3829 #undef REQUIRE_FIELD
3830 #undef DECLARE_FIELD
3831
3832 /// ParseMetadataAsValue
3833 ///  ::= metadata i32 %local
3834 ///  ::= metadata i32 @global
3835 ///  ::= metadata i32 7
3836 ///  ::= metadata !0
3837 ///  ::= metadata !{...}
3838 ///  ::= metadata !"string"
3839 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3840   // Note: the type 'metadata' has already been parsed.
3841   Metadata *MD;
3842   if (ParseMetadata(MD, &PFS))
3843     return true;
3844
3845   V = MetadataAsValue::get(Context, MD);
3846   return false;
3847 }
3848
3849 /// ParseValueAsMetadata
3850 ///  ::= i32 %local
3851 ///  ::= i32 @global
3852 ///  ::= i32 7
3853 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3854                                     PerFunctionState *PFS) {
3855   Type *Ty;
3856   LocTy Loc;
3857   if (ParseType(Ty, TypeMsg, Loc))
3858     return true;
3859   if (Ty->isMetadataTy())
3860     return Error(Loc, "invalid metadata-value-metadata roundtrip");
3861
3862   Value *V;
3863   if (ParseValue(Ty, V, PFS))
3864     return true;
3865
3866   MD = ValueAsMetadata::get(V);
3867   return false;
3868 }
3869
3870 /// ParseMetadata
3871 ///  ::= i32 %local
3872 ///  ::= i32 @global
3873 ///  ::= i32 7
3874 ///  ::= !42
3875 ///  ::= !{...}
3876 ///  ::= !"string"
3877 ///  ::= !DILocation(...)
3878 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3879   if (Lex.getKind() == lltok::MetadataVar) {
3880     MDNode *N;
3881     if (ParseSpecializedMDNode(N))
3882       return true;
3883     MD = N;
3884     return false;
3885   }
3886
3887   // ValueAsMetadata:
3888   // <type> <value>
3889   if (Lex.getKind() != lltok::exclaim)
3890     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3891
3892   // '!'.
3893   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3894   Lex.Lex();
3895
3896   // MDString:
3897   //   ::= '!' STRINGCONSTANT
3898   if (Lex.getKind() == lltok::StringConstant) {
3899     MDString *S;
3900     if (ParseMDString(S))
3901       return true;
3902     MD = S;
3903     return false;
3904   }
3905
3906   // MDNode:
3907   // !{ ... }
3908   // !7
3909   MDNode *N;
3910   if (ParseMDNodeTail(N))
3911     return true;
3912   MD = N;
3913   return false;
3914 }
3915
3916
3917 //===----------------------------------------------------------------------===//
3918 // Function Parsing.
3919 //===----------------------------------------------------------------------===//
3920
3921 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3922                                    PerFunctionState *PFS) {
3923   if (Ty->isFunctionTy())
3924     return Error(ID.Loc, "functions are not values, refer to them as pointers");
3925
3926   switch (ID.Kind) {
3927   case ValID::t_LocalID:
3928     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3929     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3930     return V == nullptr;
3931   case ValID::t_LocalName:
3932     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3933     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3934     return V == nullptr;
3935   case ValID::t_InlineAsm: {
3936     PointerType *PTy = dyn_cast<PointerType>(Ty);
3937     FunctionType *FTy =
3938       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3939     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3940       return Error(ID.Loc, "invalid type for inline asm constraint string");
3941     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3942                        (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3943     return false;
3944   }
3945   case ValID::t_GlobalName:
3946     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3947     return V == nullptr;
3948   case ValID::t_GlobalID:
3949     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3950     return V == nullptr;
3951   case ValID::t_APSInt:
3952     if (!Ty->isIntegerTy())
3953       return Error(ID.Loc, "integer constant must have integer type");
3954     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3955     V = ConstantInt::get(Context, ID.APSIntVal);
3956     return false;
3957   case ValID::t_APFloat:
3958     if (!Ty->isFloatingPointTy() ||
3959         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3960       return Error(ID.Loc, "floating point constant invalid for type");
3961
3962     // The lexer has no type info, so builds all half, float, and double FP
3963     // constants as double.  Fix this here.  Long double does not need this.
3964     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3965       bool Ignored;
3966       if (Ty->isHalfTy())
3967         ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3968                               &Ignored);
3969       else if (Ty->isFloatTy())
3970         ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3971                               &Ignored);
3972     }
3973     V = ConstantFP::get(Context, ID.APFloatVal);
3974
3975     if (V->getType() != Ty)
3976       return Error(ID.Loc, "floating point constant does not have type '" +
3977                    getTypeString(Ty) + "'");
3978
3979     return false;
3980   case ValID::t_Null:
3981     if (!Ty->isPointerTy())
3982       return Error(ID.Loc, "null must be a pointer type");
3983     V = ConstantPointerNull::get(cast<PointerType>(Ty));
3984     return false;
3985   case ValID::t_Undef:
3986     // FIXME: LabelTy should not be a first-class type.
3987     if (!Ty->isFirstClassType() || Ty->isLabelTy())
3988       return Error(ID.Loc, "invalid type for undef constant");
3989     V = UndefValue::get(Ty);
3990     return false;
3991   case ValID::t_EmptyArray:
3992     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3993       return Error(ID.Loc, "invalid empty array initializer");
3994     V = UndefValue::get(Ty);
3995     return false;
3996   case ValID::t_Zero:
3997     // FIXME: LabelTy should not be a first-class type.
3998     if (!Ty->isFirstClassType() || Ty->isLabelTy())
3999       return Error(ID.Loc, "invalid type for null constant");
4000     V = Constant::getNullValue(Ty);
4001     return false;
4002   case ValID::t_Constant:
4003     if (ID.ConstantVal->getType() != Ty)
4004       return Error(ID.Loc, "constant expression type mismatch");
4005
4006     V = ID.ConstantVal;
4007     return false;
4008   case ValID::t_ConstantStruct:
4009   case ValID::t_PackedConstantStruct:
4010     if (StructType *ST = dyn_cast<StructType>(Ty)) {
4011       if (ST->getNumElements() != ID.UIntVal)
4012         return Error(ID.Loc,
4013                      "initializer with struct type has wrong # elements");
4014       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4015         return Error(ID.Loc, "packed'ness of initializer and type don't match");
4016
4017       // Verify that the elements are compatible with the structtype.
4018       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4019         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4020           return Error(ID.Loc, "element " + Twine(i) +
4021                     " of struct initializer doesn't match struct element type");
4022
4023       V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4024                                                ID.UIntVal));
4025     } else
4026       return Error(ID.Loc, "constant expression type mismatch");
4027     return false;
4028   }
4029   llvm_unreachable("Invalid ValID");
4030 }
4031
4032 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4033   V = nullptr;
4034   ValID ID;
4035   return ParseValID(ID, PFS) ||
4036          ConvertValIDToValue(Ty, ID, V, PFS);
4037 }
4038
4039 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4040   Type *Ty = nullptr;
4041   return ParseType(Ty) ||
4042          ParseValue(Ty, V, PFS);
4043 }
4044
4045 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4046                                       PerFunctionState &PFS) {
4047   Value *V;
4048   Loc = Lex.getLoc();
4049   if (ParseTypeAndValue(V, PFS)) return true;
4050   if (!isa<BasicBlock>(V))
4051     return Error(Loc, "expected a basic block");
4052   BB = cast<BasicBlock>(V);
4053   return false;
4054 }
4055
4056
4057 /// FunctionHeader
4058 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4059 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4060 ///       OptionalAlign OptGC OptionalPrefix OptionalPrologue
4061 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4062   // Parse the linkage.
4063   LocTy LinkageLoc = Lex.getLoc();
4064   unsigned Linkage;
4065
4066   unsigned Visibility;
4067   unsigned DLLStorageClass;
4068   AttrBuilder RetAttrs;
4069   unsigned CC;
4070   Type *RetType = nullptr;
4071   LocTy RetTypeLoc = Lex.getLoc();
4072   if (ParseOptionalLinkage(Linkage) ||
4073       ParseOptionalVisibility(Visibility) ||
4074       ParseOptionalDLLStorageClass(DLLStorageClass) ||
4075       ParseOptionalCallingConv(CC) ||
4076       ParseOptionalReturnAttrs(RetAttrs) ||
4077       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4078     return true;
4079
4080   // Verify that the linkage is ok.
4081   switch ((GlobalValue::LinkageTypes)Linkage) {
4082   case GlobalValue::ExternalLinkage:
4083     break; // always ok.
4084   case GlobalValue::ExternalWeakLinkage:
4085     if (isDefine)
4086       return Error(LinkageLoc, "invalid linkage for function definition");
4087     break;
4088   case GlobalValue::PrivateLinkage:
4089   case GlobalValue::InternalLinkage:
4090   case GlobalValue::AvailableExternallyLinkage:
4091   case GlobalValue::LinkOnceAnyLinkage:
4092   case GlobalValue::LinkOnceODRLinkage:
4093   case GlobalValue::WeakAnyLinkage:
4094   case GlobalValue::WeakODRLinkage:
4095     if (!isDefine)
4096       return Error(LinkageLoc, "invalid linkage for function declaration");
4097     break;
4098   case GlobalValue::AppendingLinkage:
4099   case GlobalValue::CommonLinkage:
4100     return Error(LinkageLoc, "invalid function linkage type");
4101   }
4102
4103   if (!isValidVisibilityForLinkage(Visibility, Linkage))
4104     return Error(LinkageLoc,
4105                  "symbol with local linkage must have default visibility");
4106
4107   if (!FunctionType::isValidReturnType(RetType))
4108     return Error(RetTypeLoc, "invalid function return type");
4109
4110   LocTy NameLoc = Lex.getLoc();
4111
4112   std::string FunctionName;
4113   if (Lex.getKind() == lltok::GlobalVar) {
4114     FunctionName = Lex.getStrVal();
4115   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
4116     unsigned NameID = Lex.getUIntVal();
4117
4118     if (NameID != NumberedVals.size())
4119       return TokError("function expected to be numbered '%" +
4120                       Twine(NumberedVals.size()) + "'");
4121   } else {
4122     return TokError("expected function name");
4123   }
4124
4125   Lex.Lex();
4126
4127   if (Lex.getKind() != lltok::lparen)
4128     return TokError("expected '(' in function argument list");
4129
4130   SmallVector<ArgInfo, 8> ArgList;
4131   bool isVarArg;
4132   AttrBuilder FuncAttrs;
4133   std::vector<unsigned> FwdRefAttrGrps;
4134   LocTy BuiltinLoc;
4135   std::string Section;
4136   unsigned Alignment;
4137   std::string GC;
4138   bool UnnamedAddr;
4139   LocTy UnnamedAddrLoc;
4140   Constant *Prefix = nullptr;
4141   Constant *Prologue = nullptr;
4142   Comdat *C;
4143
4144   if (ParseArgumentList(ArgList, isVarArg) ||
4145       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4146                          &UnnamedAddrLoc) ||
4147       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4148                                  BuiltinLoc) ||
4149       (EatIfPresent(lltok::kw_section) &&
4150        ParseStringConstant(Section)) ||
4151       parseOptionalComdat(FunctionName, C) ||
4152       ParseOptionalAlignment(Alignment) ||
4153       (EatIfPresent(lltok::kw_gc) &&
4154        ParseStringConstant(GC)) ||
4155       (EatIfPresent(lltok::kw_prefix) &&
4156        ParseGlobalTypeAndValue(Prefix)) ||
4157       (EatIfPresent(lltok::kw_prologue) &&
4158        ParseGlobalTypeAndValue(Prologue)))
4159     return true;
4160
4161   if (FuncAttrs.contains(Attribute::Builtin))
4162     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4163
4164   // If the alignment was parsed as an attribute, move to the alignment field.
4165   if (FuncAttrs.hasAlignmentAttr()) {
4166     Alignment = FuncAttrs.getAlignment();
4167     FuncAttrs.removeAttribute(Attribute::Alignment);
4168   }
4169
4170   // Okay, if we got here, the function is syntactically valid.  Convert types
4171   // and do semantic checks.
4172   std::vector<Type*> ParamTypeList;
4173   SmallVector<AttributeSet, 8> Attrs;
4174
4175   if (RetAttrs.hasAttributes())
4176     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4177                                       AttributeSet::ReturnIndex,
4178                                       RetAttrs));
4179
4180   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4181     ParamTypeList.push_back(ArgList[i].Ty);
4182     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4183       AttrBuilder B(ArgList[i].Attrs, i + 1);
4184       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4185     }
4186   }
4187
4188   if (FuncAttrs.hasAttributes())
4189     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4190                                       AttributeSet::FunctionIndex,
4191                                       FuncAttrs));
4192
4193   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4194
4195   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4196     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4197
4198   FunctionType *FT =
4199     FunctionType::get(RetType, ParamTypeList, isVarArg);
4200   PointerType *PFT = PointerType::getUnqual(FT);
4201
4202   Fn = nullptr;
4203   if (!FunctionName.empty()) {
4204     // If this was a definition of a forward reference, remove the definition
4205     // from the forward reference table and fill in the forward ref.
4206     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4207       ForwardRefVals.find(FunctionName);
4208     if (FRVI != ForwardRefVals.end()) {
4209       Fn = M->getFunction(FunctionName);
4210       if (!Fn)
4211         return Error(FRVI->second.second, "invalid forward reference to "
4212                      "function as global value!");
4213       if (Fn->getType() != PFT)
4214         return Error(FRVI->second.second, "invalid forward reference to "
4215                      "function '" + FunctionName + "' with wrong type!");
4216
4217       ForwardRefVals.erase(FRVI);
4218     } else if ((Fn = M->getFunction(FunctionName))) {
4219       // Reject redefinitions.
4220       return Error(NameLoc, "invalid redefinition of function '" +
4221                    FunctionName + "'");
4222     } else if (M->getNamedValue(FunctionName)) {
4223       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4224     }
4225
4226   } else {
4227     // If this is a definition of a forward referenced function, make sure the
4228     // types agree.
4229     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4230       = ForwardRefValIDs.find(NumberedVals.size());
4231     if (I != ForwardRefValIDs.end()) {
4232       Fn = cast<Function>(I->second.first);
4233       if (Fn->getType() != PFT)
4234         return Error(NameLoc, "type of definition and forward reference of '@" +
4235                      Twine(NumberedVals.size()) + "' disagree");
4236       ForwardRefValIDs.erase(I);
4237     }
4238   }
4239
4240   if (!Fn)
4241     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4242   else // Move the forward-reference to the correct spot in the module.
4243     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4244
4245   if (FunctionName.empty())
4246     NumberedVals.push_back(Fn);
4247
4248   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4249   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4250   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4251   Fn->setCallingConv(CC);
4252   Fn->setAttributes(PAL);
4253   Fn->setUnnamedAddr(UnnamedAddr);
4254   Fn->setAlignment(Alignment);
4255   Fn->setSection(Section);
4256   Fn->setComdat(C);
4257   if (!GC.empty()) Fn->setGC(GC.c_str());
4258   Fn->setPrefixData(Prefix);
4259   Fn->setPrologueData(Prologue);
4260   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4261
4262   // Add all of the arguments we parsed to the function.
4263   Function::arg_iterator ArgIt = Fn->arg_begin();
4264   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4265     // If the argument has a name, insert it into the argument symbol table.
4266     if (ArgList[i].Name.empty()) continue;
4267
4268     // Set the name, if it conflicted, it will be auto-renamed.
4269     ArgIt->setName(ArgList[i].Name);
4270
4271     if (ArgIt->getName() != ArgList[i].Name)
4272       return Error(ArgList[i].Loc, "redefinition of argument '%" +
4273                    ArgList[i].Name + "'");
4274   }
4275
4276   if (isDefine)
4277     return false;
4278
4279   // Check the declaration has no block address forward references.
4280   ValID ID;
4281   if (FunctionName.empty()) {
4282     ID.Kind = ValID::t_GlobalID;
4283     ID.UIntVal = NumberedVals.size() - 1;
4284   } else {
4285     ID.Kind = ValID::t_GlobalName;
4286     ID.StrVal = FunctionName;
4287   }
4288   auto Blocks = ForwardRefBlockAddresses.find(ID);
4289   if (Blocks != ForwardRefBlockAddresses.end())
4290     return Error(Blocks->first.Loc,
4291                  "cannot take blockaddress inside a declaration");
4292   return false;
4293 }
4294
4295 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4296   ValID ID;
4297   if (FunctionNumber == -1) {
4298     ID.Kind = ValID::t_GlobalName;
4299     ID.StrVal = F.getName();
4300   } else {
4301     ID.Kind = ValID::t_GlobalID;
4302     ID.UIntVal = FunctionNumber;
4303   }
4304
4305   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4306   if (Blocks == P.ForwardRefBlockAddresses.end())
4307     return false;
4308
4309   for (const auto &I : Blocks->second) {
4310     const ValID &BBID = I.first;
4311     GlobalValue *GV = I.second;
4312
4313     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4314            "Expected local id or name");
4315     BasicBlock *BB;
4316     if (BBID.Kind == ValID::t_LocalName)
4317       BB = GetBB(BBID.StrVal, BBID.Loc);
4318     else
4319       BB = GetBB(BBID.UIntVal, BBID.Loc);
4320     if (!BB)
4321       return P.Error(BBID.Loc, "referenced value is not a basic block");
4322
4323     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4324     GV->eraseFromParent();
4325   }
4326
4327   P.ForwardRefBlockAddresses.erase(Blocks);
4328   return false;
4329 }
4330
4331 /// ParseFunctionBody
4332 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
4333 bool LLParser::ParseFunctionBody(Function &Fn) {
4334   if (Lex.getKind() != lltok::lbrace)
4335     return TokError("expected '{' in function body");
4336   Lex.Lex();  // eat the {.
4337
4338   int FunctionNumber = -1;
4339   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4340
4341   PerFunctionState PFS(*this, Fn, FunctionNumber);
4342
4343   // Resolve block addresses and allow basic blocks to be forward-declared
4344   // within this function.
4345   if (PFS.resolveForwardRefBlockAddresses())
4346     return true;
4347   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4348
4349   // We need at least one basic block.
4350   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4351     return TokError("function body requires at least one basic block");
4352
4353   while (Lex.getKind() != lltok::rbrace &&
4354          Lex.getKind() != lltok::kw_uselistorder)
4355     if (ParseBasicBlock(PFS)) return true;
4356
4357   while (Lex.getKind() != lltok::rbrace)
4358     if (ParseUseListOrder(&PFS))
4359       return true;
4360
4361   // Eat the }.
4362   Lex.Lex();
4363
4364   // Verify function is ok.
4365   return PFS.FinishFunction();
4366 }
4367
4368 /// ParseBasicBlock
4369 ///   ::= LabelStr? Instruction*
4370 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4371   // If this basic block starts out with a name, remember it.
4372   std::string Name;
4373   LocTy NameLoc = Lex.getLoc();
4374   if (Lex.getKind() == lltok::LabelStr) {
4375     Name = Lex.getStrVal();
4376     Lex.Lex();
4377   }
4378
4379   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4380   if (!BB)
4381     return Error(NameLoc,
4382                  "unable to create block named '" + Name + "'");
4383
4384   std::string NameStr;
4385
4386   // Parse the instructions in this block until we get a terminator.
4387   Instruction *Inst;
4388   do {
4389     // This instruction may have three possibilities for a name: a) none
4390     // specified, b) name specified "%foo =", c) number specified: "%4 =".
4391     LocTy NameLoc = Lex.getLoc();
4392     int NameID = -1;
4393     NameStr = "";
4394
4395     if (Lex.getKind() == lltok::LocalVarID) {
4396       NameID = Lex.getUIntVal();
4397       Lex.Lex();
4398       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4399         return true;
4400     } else if (Lex.getKind() == lltok::LocalVar) {
4401       NameStr = Lex.getStrVal();
4402       Lex.Lex();
4403       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4404         return true;
4405     }
4406
4407     switch (ParseInstruction(Inst, BB, PFS)) {
4408     default: llvm_unreachable("Unknown ParseInstruction result!");
4409     case InstError: return true;
4410     case InstNormal:
4411       BB->getInstList().push_back(Inst);
4412
4413       // With a normal result, we check to see if the instruction is followed by
4414       // a comma and metadata.
4415       if (EatIfPresent(lltok::comma))
4416         if (ParseInstructionMetadata(*Inst))
4417           return true;
4418       break;
4419     case InstExtraComma:
4420       BB->getInstList().push_back(Inst);
4421
4422       // If the instruction parser ate an extra comma at the end of it, it
4423       // *must* be followed by metadata.
4424       if (ParseInstructionMetadata(*Inst))
4425         return true;
4426       break;
4427     }
4428
4429     // Set the name on the instruction.
4430     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4431   } while (!isa<TerminatorInst>(Inst));
4432
4433   return false;
4434 }
4435
4436 //===----------------------------------------------------------------------===//
4437 // Instruction Parsing.
4438 //===----------------------------------------------------------------------===//
4439
4440 /// ParseInstruction - Parse one of the many different instructions.
4441 ///
4442 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4443                                PerFunctionState &PFS) {
4444   lltok::Kind Token = Lex.getKind();
4445   if (Token == lltok::Eof)
4446     return TokError("found end of file when expecting more instructions");
4447   LocTy Loc = Lex.getLoc();
4448   unsigned KeywordVal = Lex.getUIntVal();
4449   Lex.Lex();  // Eat the keyword.
4450
4451   switch (Token) {
4452   default:                    return Error(Loc, "expected instruction opcode");
4453   // Terminator Instructions.
4454   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4455   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
4456   case lltok::kw_br:          return ParseBr(Inst, PFS);
4457   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
4458   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
4459   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
4460   case lltok::kw_resume:      return ParseResume(Inst, PFS);
4461   // Binary Operators.
4462   case lltok::kw_add:
4463   case lltok::kw_sub:
4464   case lltok::kw_mul:
4465   case lltok::kw_shl: {
4466     bool NUW = EatIfPresent(lltok::kw_nuw);
4467     bool NSW = EatIfPresent(lltok::kw_nsw);
4468     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4469
4470     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4471
4472     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4473     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4474     return false;
4475   }
4476   case lltok::kw_fadd:
4477   case lltok::kw_fsub:
4478   case lltok::kw_fmul:
4479   case lltok::kw_fdiv:
4480   case lltok::kw_frem: {
4481     FastMathFlags FMF = EatFastMathFlagsIfPresent();
4482     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4483     if (Res != 0)
4484       return Res;
4485     if (FMF.any())
4486       Inst->setFastMathFlags(FMF);
4487     return 0;
4488   }
4489
4490   case lltok::kw_sdiv:
4491   case lltok::kw_udiv:
4492   case lltok::kw_lshr:
4493   case lltok::kw_ashr: {
4494     bool Exact = EatIfPresent(lltok::kw_exact);
4495
4496     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4497     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4498     return false;
4499   }
4500
4501   case lltok::kw_urem:
4502   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4503   case lltok::kw_and:
4504   case lltok::kw_or:
4505   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
4506   case lltok::kw_icmp:
4507   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
4508   // Casts.
4509   case lltok::kw_trunc:
4510   case lltok::kw_zext:
4511   case lltok::kw_sext:
4512   case lltok::kw_fptrunc:
4513   case lltok::kw_fpext:
4514   case lltok::kw_bitcast:
4515   case lltok::kw_addrspacecast:
4516   case lltok::kw_uitofp:
4517   case lltok::kw_sitofp:
4518   case lltok::kw_fptoui:
4519   case lltok::kw_fptosi:
4520   case lltok::kw_inttoptr:
4521   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
4522   // Other.
4523   case lltok::kw_select:         return ParseSelect(Inst, PFS);
4524   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
4525   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4526   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
4527   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
4528   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
4529   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
4530   // Call.
4531   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
4532   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4533   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4534   // Memory.
4535   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
4536   case lltok::kw_load:           return ParseLoad(Inst, PFS);
4537   case lltok::kw_store:          return ParseStore(Inst, PFS);
4538   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
4539   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
4540   case lltok::kw_fence:          return ParseFence(Inst, PFS);
4541   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4542   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
4543   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
4544   }
4545 }
4546
4547 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4548 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4549   if (Opc == Instruction::FCmp) {
4550     switch (Lex.getKind()) {
4551     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4552     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4553     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4554     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4555     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4556     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4557     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4558     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4559     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4560     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4561     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4562     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4563     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4564     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4565     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4566     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4567     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4568     }
4569   } else {
4570     switch (Lex.getKind()) {
4571     default: return TokError("expected icmp predicate (e.g. 'eq')");
4572     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
4573     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
4574     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4575     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4576     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4577     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4578     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4579     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4580     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4581     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4582     }
4583   }
4584   Lex.Lex();
4585   return false;
4586 }
4587
4588 //===----------------------------------------------------------------------===//
4589 // Terminator Instructions.
4590 //===----------------------------------------------------------------------===//
4591
4592 /// ParseRet - Parse a return instruction.
4593 ///   ::= 'ret' void (',' !dbg, !1)*
4594 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
4595 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4596                         PerFunctionState &PFS) {
4597   SMLoc TypeLoc = Lex.getLoc();
4598   Type *Ty = nullptr;
4599   if (ParseType(Ty, true /*void allowed*/)) return true;
4600
4601   Type *ResType = PFS.getFunction().getReturnType();
4602
4603   if (Ty->isVoidTy()) {
4604     if (!ResType->isVoidTy())
4605       return Error(TypeLoc, "value doesn't match function result type '" +
4606                    getTypeString(ResType) + "'");
4607
4608     Inst = ReturnInst::Create(Context);
4609     return false;
4610   }
4611
4612   Value *RV;
4613   if (ParseValue(Ty, RV, PFS)) return true;
4614
4615   if (ResType != RV->getType())
4616     return Error(TypeLoc, "value doesn't match function result type '" +
4617                  getTypeString(ResType) + "'");
4618
4619   Inst = ReturnInst::Create(Context, RV);
4620   return false;
4621 }
4622
4623
4624 /// ParseBr
4625 ///   ::= 'br' TypeAndValue
4626 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4627 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4628   LocTy Loc, Loc2;
4629   Value *Op0;
4630   BasicBlock *Op1, *Op2;
4631   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4632
4633   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4634     Inst = BranchInst::Create(BB);
4635     return false;
4636   }
4637
4638   if (Op0->getType() != Type::getInt1Ty(Context))
4639     return Error(Loc, "branch condition must have 'i1' type");
4640
4641   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4642       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4643       ParseToken(lltok::comma, "expected ',' after true destination") ||
4644       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4645     return true;
4646
4647   Inst = BranchInst::Create(Op1, Op2, Op0);
4648   return false;
4649 }
4650
4651 /// ParseSwitch
4652 ///  Instruction
4653 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4654 ///  JumpTable
4655 ///    ::= (TypeAndValue ',' TypeAndValue)*
4656 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4657   LocTy CondLoc, BBLoc;
4658   Value *Cond;
4659   BasicBlock *DefaultBB;
4660   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4661       ParseToken(lltok::comma, "expected ',' after switch condition") ||
4662       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4663       ParseToken(lltok::lsquare, "expected '[' with switch table"))
4664     return true;
4665
4666   if (!Cond->getType()->isIntegerTy())
4667     return Error(CondLoc, "switch condition must have integer type");
4668
4669   // Parse the jump table pairs.
4670   SmallPtrSet<Value*, 32> SeenCases;
4671   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4672   while (Lex.getKind() != lltok::rsquare) {
4673     Value *Constant;
4674     BasicBlock *DestBB;
4675
4676     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4677         ParseToken(lltok::comma, "expected ',' after case value") ||
4678         ParseTypeAndBasicBlock(DestBB, PFS))
4679       return true;
4680
4681     if (!SeenCases.insert(Constant).second)
4682       return Error(CondLoc, "duplicate case value in switch");
4683     if (!isa<ConstantInt>(Constant))
4684       return Error(CondLoc, "case value is not a constant integer");
4685
4686     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4687   }
4688
4689   Lex.Lex();  // Eat the ']'.
4690
4691   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4692   for (unsigned i = 0, e = Table.size(); i != e; ++i)
4693     SI->addCase(Table[i].first, Table[i].second);
4694   Inst = SI;
4695   return false;
4696 }
4697
4698 /// ParseIndirectBr
4699 ///  Instruction
4700 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4701 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4702   LocTy AddrLoc;
4703   Value *Address;
4704   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4705       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4706       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4707     return true;
4708
4709   if (!Address->getType()->isPointerTy())
4710     return Error(AddrLoc, "indirectbr address must have pointer type");
4711
4712   // Parse the destination list.
4713   SmallVector<BasicBlock*, 16> DestList;
4714
4715   if (Lex.getKind() != lltok::rsquare) {
4716     BasicBlock *DestBB;
4717     if (ParseTypeAndBasicBlock(DestBB, PFS))
4718       return true;
4719     DestList.push_back(DestBB);
4720
4721     while (EatIfPresent(lltok::comma)) {
4722       if (ParseTypeAndBasicBlock(DestBB, PFS))
4723         return true;
4724       DestList.push_back(DestBB);
4725     }
4726   }
4727
4728   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4729     return true;
4730
4731   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4732   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4733     IBI->addDestination(DestList[i]);
4734   Inst = IBI;
4735   return false;
4736 }
4737
4738
4739 /// ParseInvoke
4740 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4741 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4742 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4743   LocTy CallLoc = Lex.getLoc();
4744   AttrBuilder RetAttrs, FnAttrs;
4745   std::vector<unsigned> FwdRefAttrGrps;
4746   LocTy NoBuiltinLoc;
4747   unsigned CC;
4748   Type *RetType = nullptr;
4749   LocTy RetTypeLoc;
4750   ValID CalleeID;
4751   SmallVector<ParamInfo, 16> ArgList;
4752
4753   BasicBlock *NormalBB, *UnwindBB;
4754   if (ParseOptionalCallingConv(CC) ||
4755       ParseOptionalReturnAttrs(RetAttrs) ||
4756       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4757       ParseValID(CalleeID) ||
4758       ParseParameterList(ArgList, PFS) ||
4759       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4760                                  NoBuiltinLoc) ||
4761       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4762       ParseTypeAndBasicBlock(NormalBB, PFS) ||
4763       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4764       ParseTypeAndBasicBlock(UnwindBB, PFS))
4765     return true;
4766
4767   // If RetType is a non-function pointer type, then this is the short syntax
4768   // for the call, which means that RetType is just the return type.  Infer the
4769   // rest of the function argument types from the arguments that are present.
4770   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4771   if (!Ty) {
4772     // Pull out the types of all of the arguments...
4773     std::vector<Type*> ParamTypes;
4774     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4775       ParamTypes.push_back(ArgList[i].V->getType());
4776
4777     if (!FunctionType::isValidReturnType(RetType))
4778       return Error(RetTypeLoc, "Invalid result type for LLVM function");
4779
4780     Ty = FunctionType::get(RetType, ParamTypes, false);
4781   }
4782
4783   // Look up the callee.
4784   Value *Callee;
4785   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4786     return true;
4787
4788   // Set up the Attribute for the function.
4789   SmallVector<AttributeSet, 8> Attrs;
4790   if (RetAttrs.hasAttributes())
4791     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4792                                       AttributeSet::ReturnIndex,
4793                                       RetAttrs));
4794
4795   SmallVector<Value*, 8> Args;
4796
4797   // Loop through FunctionType's arguments and ensure they are specified
4798   // correctly.  Also, gather any parameter attributes.
4799   FunctionType::param_iterator I = Ty->param_begin();
4800   FunctionType::param_iterator E = Ty->param_end();
4801   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4802     Type *ExpectedTy = nullptr;
4803     if (I != E) {
4804       ExpectedTy = *I++;
4805     } else if (!Ty->isVarArg()) {
4806       return Error(ArgList[i].Loc, "too many arguments specified");
4807     }
4808
4809     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4810       return Error(ArgList[i].Loc, "argument is not of expected type '" +
4811                    getTypeString(ExpectedTy) + "'");
4812     Args.push_back(ArgList[i].V);
4813     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4814       AttrBuilder B(ArgList[i].Attrs, i + 1);
4815       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4816     }
4817   }
4818
4819   if (I != E)
4820     return Error(CallLoc, "not enough parameters specified for call");
4821
4822   if (FnAttrs.hasAttributes()) {
4823     if (FnAttrs.hasAlignmentAttr())
4824       return Error(CallLoc, "invoke instructions may not have an alignment");
4825
4826     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4827                                       AttributeSet::FunctionIndex,
4828                                       FnAttrs));
4829   }
4830
4831   // Finish off the Attribute and check them
4832   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4833
4834   InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4835   II->setCallingConv(CC);
4836   II->setAttributes(PAL);
4837   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4838   Inst = II;
4839   return false;
4840 }
4841
4842 /// ParseResume
4843 ///   ::= 'resume' TypeAndValue
4844 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4845   Value *Exn; LocTy ExnLoc;
4846   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4847     return true;
4848
4849   ResumeInst *RI = ResumeInst::Create(Exn);
4850   Inst = RI;
4851   return false;
4852 }
4853
4854 //===----------------------------------------------------------------------===//
4855 // Binary Operators.
4856 //===----------------------------------------------------------------------===//
4857
4858 /// ParseArithmetic
4859 ///  ::= ArithmeticOps TypeAndValue ',' Value
4860 ///
4861 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
4862 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4863 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4864                                unsigned Opc, unsigned OperandType) {
4865   LocTy Loc; Value *LHS, *RHS;
4866   if (ParseTypeAndValue(LHS, Loc, PFS) ||
4867       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4868       ParseValue(LHS->getType(), RHS, PFS))
4869     return true;
4870
4871   bool Valid;
4872   switch (OperandType) {
4873   default: llvm_unreachable("Unknown operand type!");
4874   case 0: // int or FP.
4875     Valid = LHS->getType()->isIntOrIntVectorTy() ||
4876             LHS->getType()->isFPOrFPVectorTy();
4877     break;
4878   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4879   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4880   }
4881
4882   if (!Valid)
4883     return Error(Loc, "invalid operand type for instruction");
4884
4885   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4886   return false;
4887 }
4888
4889 /// ParseLogical
4890 ///  ::= ArithmeticOps TypeAndValue ',' Value {
4891 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4892                             unsigned Opc) {
4893   LocTy Loc; Value *LHS, *RHS;
4894   if (ParseTypeAndValue(LHS, Loc, PFS) ||
4895       ParseToken(lltok::comma, "expected ',' in logical operation") ||
4896       ParseValue(LHS->getType(), RHS, PFS))
4897     return true;
4898
4899   if (!LHS->getType()->isIntOrIntVectorTy())
4900     return Error(Loc,"instruction requires integer or integer vector operands");
4901
4902   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4903   return false;
4904 }
4905
4906
4907 /// ParseCompare
4908 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
4909 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
4910 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4911                             unsigned Opc) {
4912   // Parse the integer/fp comparison predicate.
4913   LocTy Loc;
4914   unsigned Pred;
4915   Value *LHS, *RHS;
4916   if (ParseCmpPredicate(Pred, Opc) ||
4917       ParseTypeAndValue(LHS, Loc, PFS) ||
4918       ParseToken(lltok::comma, "expected ',' after compare value") ||
4919       ParseValue(LHS->getType(), RHS, PFS))
4920     return true;
4921
4922   if (Opc == Instruction::FCmp) {
4923     if (!LHS->getType()->isFPOrFPVectorTy())
4924       return Error(Loc, "fcmp requires floating point operands");
4925     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4926   } else {
4927     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4928     if (!LHS->getType()->isIntOrIntVectorTy() &&
4929         !LHS->getType()->getScalarType()->isPointerTy())
4930       return Error(Loc, "icmp requires integer operands");
4931     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4932   }
4933   return false;
4934 }
4935
4936 //===----------------------------------------------------------------------===//
4937 // Other Instructions.
4938 //===----------------------------------------------------------------------===//
4939
4940
4941 /// ParseCast
4942 ///   ::= CastOpc TypeAndValue 'to' Type
4943 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4944                          unsigned Opc) {
4945   LocTy Loc;
4946   Value *Op;
4947   Type *DestTy = nullptr;
4948   if (ParseTypeAndValue(Op, Loc, PFS) ||
4949       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4950       ParseType(DestTy))
4951     return true;
4952
4953   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4954     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4955     return Error(Loc, "invalid cast opcode for cast from '" +
4956                  getTypeString(Op->getType()) + "' to '" +
4957                  getTypeString(DestTy) + "'");
4958   }
4959   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4960   return false;
4961 }
4962
4963 /// ParseSelect
4964 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4965 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4966   LocTy Loc;
4967   Value *Op0, *Op1, *Op2;
4968   if (ParseTypeAndValue(Op0, Loc, PFS) ||
4969       ParseToken(lltok::comma, "expected ',' after select condition") ||
4970       ParseTypeAndValue(Op1, PFS) ||
4971       ParseToken(lltok::comma, "expected ',' after select value") ||
4972       ParseTypeAndValue(Op2, PFS))
4973     return true;
4974
4975   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4976     return Error(Loc, Reason);
4977
4978   Inst = SelectInst::Create(Op0, Op1, Op2);
4979   return false;
4980 }
4981
4982 /// ParseVA_Arg
4983 ///   ::= 'va_arg' TypeAndValue ',' Type
4984 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4985   Value *Op;
4986   Type *EltTy = nullptr;
4987   LocTy TypeLoc;
4988   if (ParseTypeAndValue(Op, PFS) ||
4989       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4990       ParseType(EltTy, TypeLoc))
4991     return true;
4992
4993   if (!EltTy->isFirstClassType())
4994     return Error(TypeLoc, "va_arg requires operand with first class type");
4995
4996   Inst = new VAArgInst(Op, EltTy);
4997   return false;
4998 }
4999
5000 /// ParseExtractElement
5001 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
5002 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5003   LocTy Loc;
5004   Value *Op0, *Op1;
5005   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5006       ParseToken(lltok::comma, "expected ',' after extract value") ||
5007       ParseTypeAndValue(Op1, PFS))
5008     return true;
5009
5010   if (!ExtractElementInst::isValidOperands(Op0, Op1))
5011     return Error(Loc, "invalid extractelement operands");
5012
5013   Inst = ExtractElementInst::Create(Op0, Op1);
5014   return false;
5015 }
5016
5017 /// ParseInsertElement
5018 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5019 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5020   LocTy Loc;
5021   Value *Op0, *Op1, *Op2;
5022   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5023       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5024       ParseTypeAndValue(Op1, PFS) ||
5025       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5026       ParseTypeAndValue(Op2, PFS))
5027     return true;
5028
5029   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5030     return Error(Loc, "invalid insertelement operands");
5031
5032   Inst = InsertElementInst::Create(Op0, Op1, Op2);
5033   return false;
5034 }
5035
5036 /// ParseShuffleVector
5037 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5038 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5039   LocTy Loc;
5040   Value *Op0, *Op1, *Op2;
5041   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5042       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5043       ParseTypeAndValue(Op1, PFS) ||
5044       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5045       ParseTypeAndValue(Op2, PFS))
5046     return true;
5047
5048   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5049     return Error(Loc, "invalid shufflevector operands");
5050
5051   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5052   return false;
5053 }
5054
5055 /// ParsePHI
5056 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5057 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5058   Type *Ty = nullptr;  LocTy TypeLoc;
5059   Value *Op0, *Op1;
5060
5061   if (ParseType(Ty, TypeLoc) ||
5062       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5063       ParseValue(Ty, Op0, PFS) ||
5064       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5065       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5066       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5067     return true;
5068
5069   bool AteExtraComma = false;
5070   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5071   while (1) {
5072     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5073
5074     if (!EatIfPresent(lltok::comma))
5075       break;
5076
5077     if (Lex.getKind() == lltok::MetadataVar) {
5078       AteExtraComma = true;
5079       break;
5080     }
5081
5082     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5083         ParseValue(Ty, Op0, PFS) ||
5084         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5085         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5086         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5087       return true;
5088   }
5089
5090   if (!Ty->isFirstClassType())
5091     return Error(TypeLoc, "phi node must have first class type");
5092
5093   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5094   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5095     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5096   Inst = PN;
5097   return AteExtraComma ? InstExtraComma : InstNormal;
5098 }
5099
5100 /// ParseLandingPad
5101 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5102 /// Clause
5103 ///   ::= 'catch' TypeAndValue
5104 ///   ::= 'filter'
5105 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5106 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5107   Type *Ty = nullptr; LocTy TyLoc;
5108   Value *PersFn; LocTy PersFnLoc;
5109
5110   if (ParseType(Ty, TyLoc) ||
5111       ParseToken(lltok::kw_personality, "expected 'personality'") ||
5112       ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5113     return true;
5114
5115   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
5116   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5117
5118   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5119     LandingPadInst::ClauseType CT;
5120     if (EatIfPresent(lltok::kw_catch))
5121       CT = LandingPadInst::Catch;
5122     else if (EatIfPresent(lltok::kw_filter))
5123       CT = LandingPadInst::Filter;
5124     else
5125       return TokError("expected 'catch' or 'filter' clause type");
5126
5127     Value *V;
5128     LocTy VLoc;
5129     if (ParseTypeAndValue(V, VLoc, PFS))
5130       return true;
5131
5132     // A 'catch' type expects a non-array constant. A filter clause expects an
5133     // array constant.
5134     if (CT == LandingPadInst::Catch) {
5135       if (isa<ArrayType>(V->getType()))
5136         Error(VLoc, "'catch' clause has an invalid type");
5137     } else {
5138       if (!isa<ArrayType>(V->getType()))
5139         Error(VLoc, "'filter' clause has an invalid type");
5140     }
5141
5142     Constant *CV = dyn_cast<Constant>(V);
5143     if (!CV)
5144       return Error(VLoc, "clause argument must be a constant");
5145     LP->addClause(CV);
5146   }
5147
5148   Inst = LP.release();
5149   return false;
5150 }
5151
5152 /// ParseCall
5153 ///   ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5154 ///       ParameterList OptionalAttrs
5155 ///   ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5156 ///       ParameterList OptionalAttrs
5157 ///   ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5158 ///       ParameterList OptionalAttrs
5159 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5160                          CallInst::TailCallKind TCK) {
5161   AttrBuilder RetAttrs, FnAttrs;
5162   std::vector<unsigned> FwdRefAttrGrps;
5163   LocTy BuiltinLoc;
5164   unsigned CC;
5165   Type *RetType = nullptr;
5166   LocTy RetTypeLoc;
5167   ValID CalleeID;
5168   SmallVector<ParamInfo, 16> ArgList;
5169   LocTy CallLoc = Lex.getLoc();
5170
5171   if ((TCK != CallInst::TCK_None &&
5172        ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5173       ParseOptionalCallingConv(CC) ||
5174       ParseOptionalReturnAttrs(RetAttrs) ||
5175       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5176       ParseValID(CalleeID) ||
5177       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5178                          PFS.getFunction().isVarArg()) ||
5179       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5180                                  BuiltinLoc))
5181     return true;
5182
5183   // If RetType is a non-function pointer type, then this is the short syntax
5184   // for the call, which means that RetType is just the return type.  Infer the
5185   // rest of the function argument types from the arguments that are present.
5186   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5187   if (!Ty) {
5188     // Pull out the types of all of the arguments...
5189     std::vector<Type*> ParamTypes;
5190     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5191       ParamTypes.push_back(ArgList[i].V->getType());
5192
5193     if (!FunctionType::isValidReturnType(RetType))
5194       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5195
5196     Ty = FunctionType::get(RetType, ParamTypes, false);
5197   }
5198
5199   // Look up the callee.
5200   Value *Callee;
5201   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5202     return true;
5203
5204   // Set up the Attribute for the function.
5205   SmallVector<AttributeSet, 8> Attrs;
5206   if (RetAttrs.hasAttributes())
5207     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5208                                       AttributeSet::ReturnIndex,
5209                                       RetAttrs));
5210
5211   SmallVector<Value*, 8> Args;
5212
5213   // Loop through FunctionType's arguments and ensure they are specified
5214   // correctly.  Also, gather any parameter attributes.
5215   FunctionType::param_iterator I = Ty->param_begin();
5216   FunctionType::param_iterator E = Ty->param_end();
5217   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5218     Type *ExpectedTy = nullptr;
5219     if (I != E) {
5220       ExpectedTy = *I++;
5221     } else if (!Ty->isVarArg()) {
5222       return Error(ArgList[i].Loc, "too many arguments specified");
5223     }
5224
5225     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5226       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5227                    getTypeString(ExpectedTy) + "'");
5228     Args.push_back(ArgList[i].V);
5229     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5230       AttrBuilder B(ArgList[i].Attrs, i + 1);
5231       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5232     }
5233   }
5234
5235   if (I != E)
5236     return Error(CallLoc, "not enough parameters specified for call");
5237
5238   if (FnAttrs.hasAttributes()) {
5239     if (FnAttrs.hasAlignmentAttr())
5240       return Error(CallLoc, "call instructions may not have an alignment");
5241
5242     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5243                                       AttributeSet::FunctionIndex,
5244                                       FnAttrs));
5245   }
5246
5247   // Finish off the Attribute and check them
5248   AttributeSet PAL = AttributeSet::get(Context, Attrs);
5249
5250   CallInst *CI = CallInst::Create(Ty, Callee, Args);
5251   CI->setTailCallKind(TCK);
5252   CI->setCallingConv(CC);
5253   CI->setAttributes(PAL);
5254   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5255   Inst = CI;
5256   return false;
5257 }
5258
5259 //===----------------------------------------------------------------------===//
5260 // Memory Instructions.
5261 //===----------------------------------------------------------------------===//
5262
5263 /// ParseAlloc
5264 ///   ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5265 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5266   Value *Size = nullptr;
5267   LocTy SizeLoc, TyLoc;
5268   unsigned Alignment = 0;
5269   Type *Ty = nullptr;
5270
5271   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5272
5273   if (ParseType(Ty, TyLoc)) return true;
5274
5275   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5276     return Error(TyLoc, "invalid type for alloca");
5277
5278   bool AteExtraComma = false;
5279   if (EatIfPresent(lltok::comma)) {
5280     if (Lex.getKind() == lltok::kw_align) {
5281       if (ParseOptionalAlignment(Alignment)) return true;
5282     } else if (Lex.getKind() == lltok::MetadataVar) {
5283       AteExtraComma = true;
5284     } else {
5285       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5286           ParseOptionalCommaAlign(Alignment, AteExtraComma))
5287         return true;
5288     }
5289   }
5290
5291   if (Size && !Size->getType()->isIntegerTy())
5292     return Error(SizeLoc, "element count must have integer type");
5293
5294   AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5295   AI->setUsedWithInAlloca(IsInAlloca);
5296   Inst = AI;
5297   return AteExtraComma ? InstExtraComma : InstNormal;
5298 }
5299
5300 /// ParseLoad
5301 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5302 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
5303 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5304 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5305   Value *Val; LocTy Loc;
5306   unsigned Alignment = 0;
5307   bool AteExtraComma = false;
5308   bool isAtomic = false;
5309   AtomicOrdering Ordering = NotAtomic;
5310   SynchronizationScope Scope = CrossThread;
5311
5312   if (Lex.getKind() == lltok::kw_atomic) {
5313     isAtomic = true;
5314     Lex.Lex();
5315   }
5316
5317   bool isVolatile = false;
5318   if (Lex.getKind() == lltok::kw_volatile) {
5319     isVolatile = true;
5320     Lex.Lex();
5321   }
5322
5323   Type *Ty;
5324   LocTy ExplicitTypeLoc = Lex.getLoc();
5325   if (ParseType(Ty) ||
5326       ParseToken(lltok::comma, "expected comma after load's type") ||
5327       ParseTypeAndValue(Val, Loc, PFS) ||
5328       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5329       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5330     return true;
5331
5332   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5333     return Error(Loc, "load operand must be a pointer to a first class type");
5334   if (isAtomic && !Alignment)
5335     return Error(Loc, "atomic load must have explicit non-zero alignment");
5336   if (Ordering == Release || Ordering == AcquireRelease)
5337     return Error(Loc, "atomic load cannot use Release ordering");
5338
5339   if (Ty != cast<PointerType>(Val->getType())->getElementType())
5340     return Error(ExplicitTypeLoc,
5341                  "explicit pointee type doesn't match operand's pointee type");
5342
5343   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5344   return AteExtraComma ? InstExtraComma : InstNormal;
5345 }
5346
5347 /// ParseStore
5348
5349 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5350 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5351 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5352 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5353   Value *Val, *Ptr; LocTy Loc, PtrLoc;
5354   unsigned Alignment = 0;
5355   bool AteExtraComma = false;
5356   bool isAtomic = false;
5357   AtomicOrdering Ordering = NotAtomic;
5358   SynchronizationScope Scope = CrossThread;
5359
5360   if (Lex.getKind() == lltok::kw_atomic) {
5361     isAtomic = true;
5362     Lex.Lex();
5363   }
5364
5365   bool isVolatile = false;
5366   if (Lex.getKind() == lltok::kw_volatile) {
5367     isVolatile = true;
5368     Lex.Lex();
5369   }
5370
5371   if (ParseTypeAndValue(Val, Loc, PFS) ||
5372       ParseToken(lltok::comma, "expected ',' after store operand") ||
5373       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5374       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5375       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5376     return true;
5377
5378   if (!Ptr->getType()->isPointerTy())
5379     return Error(PtrLoc, "store operand must be a pointer");
5380   if (!Val->getType()->isFirstClassType())
5381     return Error(Loc, "store operand must be a first class value");
5382   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5383     return Error(Loc, "stored value and pointer type do not match");
5384   if (isAtomic && !Alignment)
5385     return Error(Loc, "atomic store must have explicit non-zero alignment");
5386   if (Ordering == Acquire || Ordering == AcquireRelease)
5387     return Error(Loc, "atomic store cannot use Acquire ordering");
5388
5389   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5390   return AteExtraComma ? InstExtraComma : InstNormal;
5391 }
5392
5393 /// ParseCmpXchg
5394 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5395 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5396 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5397   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5398   bool AteExtraComma = false;
5399   AtomicOrdering SuccessOrdering = NotAtomic;
5400   AtomicOrdering FailureOrdering = NotAtomic;
5401   SynchronizationScope Scope = CrossThread;
5402   bool isVolatile = false;
5403   bool isWeak = false;
5404
5405   if (EatIfPresent(lltok::kw_weak))
5406     isWeak = true;
5407
5408   if (EatIfPresent(lltok::kw_volatile))
5409     isVolatile = true;
5410
5411   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5412       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5413       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5414       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5415       ParseTypeAndValue(New, NewLoc, PFS) ||
5416       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5417       ParseOrdering(FailureOrdering))
5418     return true;
5419
5420   if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5421     return TokError("cmpxchg cannot be unordered");
5422   if (SuccessOrdering < FailureOrdering)
5423     return TokError("cmpxchg must be at least as ordered on success as failure");
5424   if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5425     return TokError("cmpxchg failure ordering cannot include release semantics");
5426   if (!Ptr->getType()->isPointerTy())
5427     return Error(PtrLoc, "cmpxchg operand must be a pointer");
5428   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5429     return Error(CmpLoc, "compare value and pointer type do not match");
5430   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5431     return Error(NewLoc, "new value and pointer type do not match");
5432   if (!New->getType()->isIntegerTy())
5433     return Error(NewLoc, "cmpxchg operand must be an integer");
5434   unsigned Size = New->getType()->getPrimitiveSizeInBits();
5435   if (Size < 8 || (Size & (Size - 1)))
5436     return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5437                          " integer");
5438
5439   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5440       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5441   CXI->setVolatile(isVolatile);
5442   CXI->setWeak(isWeak);
5443   Inst = CXI;
5444   return AteExtraComma ? InstExtraComma : InstNormal;
5445 }
5446
5447 /// ParseAtomicRMW
5448 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5449 ///       'singlethread'? AtomicOrdering
5450 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5451   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5452   bool AteExtraComma = false;
5453   AtomicOrdering Ordering = NotAtomic;
5454   SynchronizationScope Scope = CrossThread;
5455   bool isVolatile = false;
5456   AtomicRMWInst::BinOp Operation;
5457
5458   if (EatIfPresent(lltok::kw_volatile))
5459     isVolatile = true;
5460
5461   switch (Lex.getKind()) {
5462   default: return TokError("expected binary operation in atomicrmw");
5463   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5464   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5465   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5466   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5467   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5468   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5469   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5470   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5471   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5472   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5473   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5474   }
5475   Lex.Lex();  // Eat the operation.
5476
5477   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5478       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5479       ParseTypeAndValue(Val, ValLoc, PFS) ||
5480       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5481     return true;
5482
5483   if (Ordering == Unordered)
5484     return TokError("atomicrmw cannot be unordered");
5485   if (!Ptr->getType()->isPointerTy())
5486     return Error(PtrLoc, "atomicrmw operand must be a pointer");
5487   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5488     return Error(ValLoc, "atomicrmw value and pointer type do not match");
5489   if (!Val->getType()->isIntegerTy())
5490     return Error(ValLoc, "atomicrmw operand must be an integer");
5491   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5492   if (Size < 8 || (Size & (Size - 1)))
5493     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5494                          " integer");
5495
5496   AtomicRMWInst *RMWI =
5497     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5498   RMWI->setVolatile(isVolatile);
5499   Inst = RMWI;
5500   return AteExtraComma ? InstExtraComma : InstNormal;
5501 }
5502
5503 /// ParseFence
5504 ///   ::= 'fence' 'singlethread'? AtomicOrdering
5505 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5506   AtomicOrdering Ordering = NotAtomic;
5507   SynchronizationScope Scope = CrossThread;
5508   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5509     return true;
5510
5511   if (Ordering == Unordered)
5512     return TokError("fence cannot be unordered");
5513   if (Ordering == Monotonic)
5514     return TokError("fence cannot be monotonic");
5515
5516   Inst = new FenceInst(Context, Ordering, Scope);
5517   return InstNormal;
5518 }
5519
5520 /// ParseGetElementPtr
5521 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5522 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5523   Value *Ptr = nullptr;
5524   Value *Val = nullptr;
5525   LocTy Loc, EltLoc;
5526
5527   bool InBounds = EatIfPresent(lltok::kw_inbounds);
5528
5529   Type *Ty = nullptr;
5530   LocTy ExplicitTypeLoc = Lex.getLoc();
5531   if (ParseType(Ty) ||
5532       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5533       ParseTypeAndValue(Ptr, Loc, PFS))
5534     return true;
5535
5536   Type *BaseType = Ptr->getType();
5537   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5538   if (!BasePointerType)
5539     return Error(Loc, "base of getelementptr must be a pointer");
5540
5541   if (Ty != BasePointerType->getElementType())
5542     return Error(ExplicitTypeLoc,
5543                  "explicit pointee type doesn't match operand's pointee type");
5544
5545   SmallVector<Value*, 16> Indices;
5546   bool AteExtraComma = false;
5547   while (EatIfPresent(lltok::comma)) {
5548     if (Lex.getKind() == lltok::MetadataVar) {
5549       AteExtraComma = true;
5550       break;
5551     }
5552     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5553     if (!Val->getType()->getScalarType()->isIntegerTy())
5554       return Error(EltLoc, "getelementptr index must be an integer");
5555     if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5556       return Error(EltLoc, "getelementptr index type missmatch");
5557     if (Val->getType()->isVectorTy()) {
5558       unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5559       unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5560       if (ValNumEl != PtrNumEl)
5561         return Error(EltLoc,
5562           "getelementptr vector index has a wrong number of elements");
5563     }
5564     Indices.push_back(Val);
5565   }
5566
5567   SmallPtrSet<const Type*, 4> Visited;
5568   if (!Indices.empty() && !Ty->isSized(&Visited))
5569     return Error(Loc, "base element of getelementptr must be sized");
5570
5571   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5572     return Error(Loc, "invalid getelementptr indices");
5573   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5574   if (InBounds)
5575     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5576   return AteExtraComma ? InstExtraComma : InstNormal;
5577 }
5578
5579 /// ParseExtractValue
5580 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
5581 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5582   Value *Val; LocTy Loc;
5583   SmallVector<unsigned, 4> Indices;
5584   bool AteExtraComma;
5585   if (ParseTypeAndValue(Val, Loc, PFS) ||
5586       ParseIndexList(Indices, AteExtraComma))
5587     return true;
5588
5589   if (!Val->getType()->isAggregateType())
5590     return Error(Loc, "extractvalue operand must be aggregate type");
5591
5592   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5593     return Error(Loc, "invalid indices for extractvalue");
5594   Inst = ExtractValueInst::Create(Val, Indices);
5595   return AteExtraComma ? InstExtraComma : InstNormal;
5596 }
5597
5598 /// ParseInsertValue
5599 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5600 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5601   Value *Val0, *Val1; LocTy Loc0, Loc1;
5602   SmallVector<unsigned, 4> Indices;
5603   bool AteExtraComma;
5604   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5605       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5606       ParseTypeAndValue(Val1, Loc1, PFS) ||
5607       ParseIndexList(Indices, AteExtraComma))
5608     return true;
5609
5610   if (!Val0->getType()->isAggregateType())
5611     return Error(Loc0, "insertvalue operand must be aggregate type");
5612
5613   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5614   if (!IndexedType)
5615     return Error(Loc0, "invalid indices for insertvalue");
5616   if (IndexedType != Val1->getType())
5617     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5618                            getTypeString(Val1->getType()) + "' instead of '" +
5619                            getTypeString(IndexedType) + "'");
5620   Inst = InsertValueInst::Create(Val0, Val1, Indices);
5621   return AteExtraComma ? InstExtraComma : InstNormal;
5622 }
5623
5624 //===----------------------------------------------------------------------===//
5625 // Embedded metadata.
5626 //===----------------------------------------------------------------------===//
5627
5628 /// ParseMDNodeVector
5629 ///   ::= { Element (',' Element)* }
5630 /// Element
5631 ///   ::= 'null' | TypeAndValue
5632 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5633   if (ParseToken(lltok::lbrace, "expected '{' here"))
5634     return true;
5635
5636   // Check for an empty list.
5637   if (EatIfPresent(lltok::rbrace))
5638     return false;
5639
5640   do {
5641     // Null is a special case since it is typeless.
5642     if (EatIfPresent(lltok::kw_null)) {
5643       Elts.push_back(nullptr);
5644       continue;
5645     }
5646
5647     Metadata *MD;
5648     if (ParseMetadata(MD, nullptr))
5649       return true;
5650     Elts.push_back(MD);
5651   } while (EatIfPresent(lltok::comma));
5652
5653   return ParseToken(lltok::rbrace, "expected end of metadata node");
5654 }
5655
5656 //===----------------------------------------------------------------------===//
5657 // Use-list order directives.
5658 //===----------------------------------------------------------------------===//
5659 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5660                                 SMLoc Loc) {
5661   if (V->use_empty())
5662     return Error(Loc, "value has no uses");
5663
5664   unsigned NumUses = 0;
5665   SmallDenseMap<const Use *, unsigned, 16> Order;
5666   for (const Use &U : V->uses()) {
5667     if (++NumUses > Indexes.size())
5668       break;
5669     Order[&U] = Indexes[NumUses - 1];
5670   }
5671   if (NumUses < 2)
5672     return Error(Loc, "value only has one use");
5673   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5674     return Error(Loc, "wrong number of indexes, expected " +
5675                           Twine(std::distance(V->use_begin(), V->use_end())));
5676
5677   V->sortUseList([&](const Use &L, const Use &R) {
5678     return Order.lookup(&L) < Order.lookup(&R);
5679   });
5680   return false;
5681 }
5682
5683 /// ParseUseListOrderIndexes
5684 ///   ::= '{' uint32 (',' uint32)+ '}'
5685 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5686   SMLoc Loc = Lex.getLoc();
5687   if (ParseToken(lltok::lbrace, "expected '{' here"))
5688     return true;
5689   if (Lex.getKind() == lltok::rbrace)
5690     return Lex.Error("expected non-empty list of uselistorder indexes");
5691
5692   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
5693   // indexes should be distinct numbers in the range [0, size-1], and should
5694   // not be in order.
5695   unsigned Offset = 0;
5696   unsigned Max = 0;
5697   bool IsOrdered = true;
5698   assert(Indexes.empty() && "Expected empty order vector");
5699   do {
5700     unsigned Index;
5701     if (ParseUInt32(Index))
5702       return true;
5703
5704     // Update consistency checks.
5705     Offset += Index - Indexes.size();
5706     Max = std::max(Max, Index);
5707     IsOrdered &= Index == Indexes.size();
5708
5709     Indexes.push_back(Index);
5710   } while (EatIfPresent(lltok::comma));
5711
5712   if (ParseToken(lltok::rbrace, "expected '}' here"))
5713     return true;
5714
5715   if (Indexes.size() < 2)
5716     return Error(Loc, "expected >= 2 uselistorder indexes");
5717   if (Offset != 0 || Max >= Indexes.size())
5718     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5719   if (IsOrdered)
5720     return Error(Loc, "expected uselistorder indexes to change the order");
5721
5722   return false;
5723 }
5724
5725 /// ParseUseListOrder
5726 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5727 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5728   SMLoc Loc = Lex.getLoc();
5729   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5730     return true;
5731
5732   Value *V;
5733   SmallVector<unsigned, 16> Indexes;
5734   if (ParseTypeAndValue(V, PFS) ||
5735       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5736       ParseUseListOrderIndexes(Indexes))
5737     return true;
5738
5739   return sortUseListOrder(V, Indexes, Loc);
5740 }
5741
5742 /// ParseUseListOrderBB
5743 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5744 bool LLParser::ParseUseListOrderBB() {
5745   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5746   SMLoc Loc = Lex.getLoc();
5747   Lex.Lex();
5748
5749   ValID Fn, Label;
5750   SmallVector<unsigned, 16> Indexes;
5751   if (ParseValID(Fn) ||
5752       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5753       ParseValID(Label) ||
5754       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5755       ParseUseListOrderIndexes(Indexes))
5756     return true;
5757
5758   // Check the function.
5759   GlobalValue *GV;
5760   if (Fn.Kind == ValID::t_GlobalName)
5761     GV = M->getNamedValue(Fn.StrVal);
5762   else if (Fn.Kind == ValID::t_GlobalID)
5763     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5764   else
5765     return Error(Fn.Loc, "expected function name in uselistorder_bb");
5766   if (!GV)
5767     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5768   auto *F = dyn_cast<Function>(GV);
5769   if (!F)
5770     return Error(Fn.Loc, "expected function name in uselistorder_bb");
5771   if (F->isDeclaration())
5772     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5773
5774   // Check the basic block.
5775   if (Label.Kind == ValID::t_LocalID)
5776     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5777   if (Label.Kind != ValID::t_LocalName)
5778     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5779   Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5780   if (!V)
5781     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5782   if (!isa<BasicBlock>(V))
5783     return Error(Label.Loc, "expected basic block in uselistorder_bb");
5784
5785   return sortUseListOrder(V, Indexes, Loc);
5786 }