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