xref: /freebsd/contrib/llvm-project/llvm/lib/AsmParser/LLParser.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the parser class for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/AsmParser/LLParser.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.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/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.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/Value.h"
41 #include "llvm/IR/ValueSymbolTable.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/SaveAndRestore.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstring>
50 #include <iterator>
51 #include <vector>
52 
53 using namespace llvm;
54 
55 static std::string getTypeString(Type *T) {
56   std::string Result;
57   raw_string_ostream Tmp(Result);
58   Tmp << *T;
59   return Tmp.str();
60 }
61 
62 /// Run: module ::= toplevelentity*
63 bool LLParser::Run(bool UpgradeDebugInfo,
64                    DataLayoutCallbackTy DataLayoutCallback) {
65   // Prime the lexer.
66   Lex.Lex();
67 
68   if (Context.shouldDiscardValueNames())
69     return error(
70         Lex.getLoc(),
71         "Can't read textual IR with a Context that discards named Values");
72 
73   if (M) {
74     if (parseTargetDefinitions())
75       return true;
76 
77     if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
78       M->setDataLayout(*LayoutOverride);
79   }
80 
81   return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
82          validateEndOfIndex();
83 }
84 
85 bool LLParser::parseStandaloneConstantValue(Constant *&C,
86                                             const SlotMapping *Slots) {
87   restoreParsingState(Slots);
88   Lex.Lex();
89 
90   Type *Ty = nullptr;
91   if (parseType(Ty) || parseConstantValue(Ty, C))
92     return true;
93   if (Lex.getKind() != lltok::Eof)
94     return error(Lex.getLoc(), "expected end of string");
95   return false;
96 }
97 
98 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
99                                     const SlotMapping *Slots) {
100   restoreParsingState(Slots);
101   Lex.Lex();
102 
103   Read = 0;
104   SMLoc Start = Lex.getLoc();
105   Ty = nullptr;
106   if (parseType(Ty))
107     return true;
108   SMLoc End = Lex.getLoc();
109   Read = End.getPointer() - Start.getPointer();
110 
111   return false;
112 }
113 
114 void LLParser::restoreParsingState(const SlotMapping *Slots) {
115   if (!Slots)
116     return;
117   NumberedVals = Slots->GlobalValues;
118   NumberedMetadata = Slots->MetadataNodes;
119   for (const auto &I : Slots->NamedTypes)
120     NamedTypes.insert(
121         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
122   for (const auto &I : Slots->Types)
123     NumberedTypes.insert(
124         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
125 }
126 
127 /// validateEndOfModule - Do final validity and sanity checks at the end of the
128 /// module.
129 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
130   if (!M)
131     return false;
132   // Handle any function attribute group forward references.
133   for (const auto &RAG : ForwardRefAttrGroups) {
134     Value *V = RAG.first;
135     const std::vector<unsigned> &Attrs = RAG.second;
136     AttrBuilder B;
137 
138     for (const auto &Attr : Attrs)
139       B.merge(NumberedAttrBuilders[Attr]);
140 
141     if (Function *Fn = dyn_cast<Function>(V)) {
142       AttributeList AS = Fn->getAttributes();
143       AttrBuilder FnAttrs(AS.getFnAttrs());
144       AS = AS.removeFnAttributes(Context);
145 
146       FnAttrs.merge(B);
147 
148       // If the alignment was parsed as an attribute, move to the alignment
149       // field.
150       if (FnAttrs.hasAlignmentAttr()) {
151         Fn->setAlignment(FnAttrs.getAlignment());
152         FnAttrs.removeAttribute(Attribute::Alignment);
153       }
154 
155       AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs));
156       Fn->setAttributes(AS);
157     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
158       AttributeList AS = CI->getAttributes();
159       AttrBuilder FnAttrs(AS.getFnAttrs());
160       AS = AS.removeFnAttributes(Context);
161       FnAttrs.merge(B);
162       AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs));
163       CI->setAttributes(AS);
164     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
165       AttributeList AS = II->getAttributes();
166       AttrBuilder FnAttrs(AS.getFnAttrs());
167       AS = AS.removeFnAttributes(Context);
168       FnAttrs.merge(B);
169       AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs));
170       II->setAttributes(AS);
171     } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
172       AttributeList AS = CBI->getAttributes();
173       AttrBuilder FnAttrs(AS.getFnAttrs());
174       AS = AS.removeFnAttributes(Context);
175       FnAttrs.merge(B);
176       AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs));
177       CBI->setAttributes(AS);
178     } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
179       AttrBuilder Attrs(GV->getAttributes());
180       Attrs.merge(B);
181       GV->setAttributes(AttributeSet::get(Context,Attrs));
182     } else {
183       llvm_unreachable("invalid object with forward attribute group reference");
184     }
185   }
186 
187   // If there are entries in ForwardRefBlockAddresses at this point, the
188   // function was never defined.
189   if (!ForwardRefBlockAddresses.empty())
190     return error(ForwardRefBlockAddresses.begin()->first.Loc,
191                  "expected function name in blockaddress");
192 
193   for (const auto &NT : NumberedTypes)
194     if (NT.second.second.isValid())
195       return error(NT.second.second,
196                    "use of undefined type '%" + Twine(NT.first) + "'");
197 
198   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
199        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
200     if (I->second.second.isValid())
201       return error(I->second.second,
202                    "use of undefined type named '" + I->getKey() + "'");
203 
204   if (!ForwardRefComdats.empty())
205     return error(ForwardRefComdats.begin()->second,
206                  "use of undefined comdat '$" +
207                      ForwardRefComdats.begin()->first + "'");
208 
209   if (!ForwardRefVals.empty())
210     return error(ForwardRefVals.begin()->second.second,
211                  "use of undefined value '@" + ForwardRefVals.begin()->first +
212                      "'");
213 
214   if (!ForwardRefValIDs.empty())
215     return error(ForwardRefValIDs.begin()->second.second,
216                  "use of undefined value '@" +
217                      Twine(ForwardRefValIDs.begin()->first) + "'");
218 
219   if (!ForwardRefMDNodes.empty())
220     return error(ForwardRefMDNodes.begin()->second.second,
221                  "use of undefined metadata '!" +
222                      Twine(ForwardRefMDNodes.begin()->first) + "'");
223 
224   // Resolve metadata cycles.
225   for (auto &N : NumberedMetadata) {
226     if (N.second && !N.second->isResolved())
227       N.second->resolveCycles();
228   }
229 
230   for (auto *Inst : InstsWithTBAATag) {
231     MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
232     assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
233     auto *UpgradedMD = UpgradeTBAANode(*MD);
234     if (MD != UpgradedMD)
235       Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
236   }
237 
238   // Look for intrinsic functions and CallInst that need to be upgraded.  We use
239   // make_early_inc_range here because we may remove some functions.
240   for (Function &F : llvm::make_early_inc_range(*M))
241     UpgradeCallsToIntrinsic(&F);
242 
243   // Some types could be renamed during loading if several modules are
244   // loaded in the same LLVMContext (LTO scenario). In this case we should
245   // remangle intrinsics names as well.
246   for (Function &F : llvm::make_early_inc_range(*M)) {
247     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) {
248       F.replaceAllUsesWith(Remangled.getValue());
249       F.eraseFromParent();
250     }
251   }
252 
253   if (UpgradeDebugInfo)
254     llvm::UpgradeDebugInfo(*M);
255 
256   UpgradeModuleFlags(*M);
257   UpgradeSectionAttributes(*M);
258 
259   if (!Slots)
260     return false;
261   // Initialize the slot mapping.
262   // Because by this point we've parsed and validated everything, we can "steal"
263   // the mapping from LLParser as it doesn't need it anymore.
264   Slots->GlobalValues = std::move(NumberedVals);
265   Slots->MetadataNodes = std::move(NumberedMetadata);
266   for (const auto &I : NamedTypes)
267     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
268   for (const auto &I : NumberedTypes)
269     Slots->Types.insert(std::make_pair(I.first, I.second.first));
270 
271   return false;
272 }
273 
274 /// Do final validity and sanity checks at the end of the index.
275 bool LLParser::validateEndOfIndex() {
276   if (!Index)
277     return false;
278 
279   if (!ForwardRefValueInfos.empty())
280     return error(ForwardRefValueInfos.begin()->second.front().second,
281                  "use of undefined summary '^" +
282                      Twine(ForwardRefValueInfos.begin()->first) + "'");
283 
284   if (!ForwardRefAliasees.empty())
285     return error(ForwardRefAliasees.begin()->second.front().second,
286                  "use of undefined summary '^" +
287                      Twine(ForwardRefAliasees.begin()->first) + "'");
288 
289   if (!ForwardRefTypeIds.empty())
290     return error(ForwardRefTypeIds.begin()->second.front().second,
291                  "use of undefined type id summary '^" +
292                      Twine(ForwardRefTypeIds.begin()->first) + "'");
293 
294   return false;
295 }
296 
297 //===----------------------------------------------------------------------===//
298 // Top-Level Entities
299 //===----------------------------------------------------------------------===//
300 
301 bool LLParser::parseTargetDefinitions() {
302   while (true) {
303     switch (Lex.getKind()) {
304     case lltok::kw_target:
305       if (parseTargetDefinition())
306         return true;
307       break;
308     case lltok::kw_source_filename:
309       if (parseSourceFileName())
310         return true;
311       break;
312     default:
313       return false;
314     }
315   }
316 }
317 
318 bool LLParser::parseTopLevelEntities() {
319   // If there is no Module, then parse just the summary index entries.
320   if (!M) {
321     while (true) {
322       switch (Lex.getKind()) {
323       case lltok::Eof:
324         return false;
325       case lltok::SummaryID:
326         if (parseSummaryEntry())
327           return true;
328         break;
329       case lltok::kw_source_filename:
330         if (parseSourceFileName())
331           return true;
332         break;
333       default:
334         // Skip everything else
335         Lex.Lex();
336       }
337     }
338   }
339   while (true) {
340     switch (Lex.getKind()) {
341     default:
342       return tokError("expected top-level entity");
343     case lltok::Eof: return false;
344     case lltok::kw_declare:
345       if (parseDeclare())
346         return true;
347       break;
348     case lltok::kw_define:
349       if (parseDefine())
350         return true;
351       break;
352     case lltok::kw_module:
353       if (parseModuleAsm())
354         return true;
355       break;
356     case lltok::LocalVarID:
357       if (parseUnnamedType())
358         return true;
359       break;
360     case lltok::LocalVar:
361       if (parseNamedType())
362         return true;
363       break;
364     case lltok::GlobalID:
365       if (parseUnnamedGlobal())
366         return true;
367       break;
368     case lltok::GlobalVar:
369       if (parseNamedGlobal())
370         return true;
371       break;
372     case lltok::ComdatVar:  if (parseComdat()) return true; break;
373     case lltok::exclaim:
374       if (parseStandaloneMetadata())
375         return true;
376       break;
377     case lltok::SummaryID:
378       if (parseSummaryEntry())
379         return true;
380       break;
381     case lltok::MetadataVar:
382       if (parseNamedMetadata())
383         return true;
384       break;
385     case lltok::kw_attributes:
386       if (parseUnnamedAttrGrp())
387         return true;
388       break;
389     case lltok::kw_uselistorder:
390       if (parseUseListOrder())
391         return true;
392       break;
393     case lltok::kw_uselistorder_bb:
394       if (parseUseListOrderBB())
395         return true;
396       break;
397     }
398   }
399 }
400 
401 /// toplevelentity
402 ///   ::= 'module' 'asm' STRINGCONSTANT
403 bool LLParser::parseModuleAsm() {
404   assert(Lex.getKind() == lltok::kw_module);
405   Lex.Lex();
406 
407   std::string AsmStr;
408   if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
409       parseStringConstant(AsmStr))
410     return true;
411 
412   M->appendModuleInlineAsm(AsmStr);
413   return false;
414 }
415 
416 /// toplevelentity
417 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
418 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
419 bool LLParser::parseTargetDefinition() {
420   assert(Lex.getKind() == lltok::kw_target);
421   std::string Str;
422   switch (Lex.Lex()) {
423   default:
424     return tokError("unknown target property");
425   case lltok::kw_triple:
426     Lex.Lex();
427     if (parseToken(lltok::equal, "expected '=' after target triple") ||
428         parseStringConstant(Str))
429       return true;
430     M->setTargetTriple(Str);
431     return false;
432   case lltok::kw_datalayout:
433     Lex.Lex();
434     if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
435         parseStringConstant(Str))
436       return true;
437     M->setDataLayout(Str);
438     return false;
439   }
440 }
441 
442 /// toplevelentity
443 ///   ::= 'source_filename' '=' STRINGCONSTANT
444 bool LLParser::parseSourceFileName() {
445   assert(Lex.getKind() == lltok::kw_source_filename);
446   Lex.Lex();
447   if (parseToken(lltok::equal, "expected '=' after source_filename") ||
448       parseStringConstant(SourceFileName))
449     return true;
450   if (M)
451     M->setSourceFileName(SourceFileName);
452   return false;
453 }
454 
455 /// parseUnnamedType:
456 ///   ::= LocalVarID '=' 'type' type
457 bool LLParser::parseUnnamedType() {
458   LocTy TypeLoc = Lex.getLoc();
459   unsigned TypeID = Lex.getUIntVal();
460   Lex.Lex(); // eat LocalVarID;
461 
462   if (parseToken(lltok::equal, "expected '=' after name") ||
463       parseToken(lltok::kw_type, "expected 'type' after '='"))
464     return true;
465 
466   Type *Result = nullptr;
467   if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
468     return true;
469 
470   if (!isa<StructType>(Result)) {
471     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
472     if (Entry.first)
473       return error(TypeLoc, "non-struct types may not be recursive");
474     Entry.first = Result;
475     Entry.second = SMLoc();
476   }
477 
478   return false;
479 }
480 
481 /// toplevelentity
482 ///   ::= LocalVar '=' 'type' type
483 bool LLParser::parseNamedType() {
484   std::string Name = Lex.getStrVal();
485   LocTy NameLoc = Lex.getLoc();
486   Lex.Lex();  // eat LocalVar.
487 
488   if (parseToken(lltok::equal, "expected '=' after name") ||
489       parseToken(lltok::kw_type, "expected 'type' after name"))
490     return true;
491 
492   Type *Result = nullptr;
493   if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
494     return true;
495 
496   if (!isa<StructType>(Result)) {
497     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
498     if (Entry.first)
499       return error(NameLoc, "non-struct types may not be recursive");
500     Entry.first = Result;
501     Entry.second = SMLoc();
502   }
503 
504   return false;
505 }
506 
507 /// toplevelentity
508 ///   ::= 'declare' FunctionHeader
509 bool LLParser::parseDeclare() {
510   assert(Lex.getKind() == lltok::kw_declare);
511   Lex.Lex();
512 
513   std::vector<std::pair<unsigned, MDNode *>> MDs;
514   while (Lex.getKind() == lltok::MetadataVar) {
515     unsigned MDK;
516     MDNode *N;
517     if (parseMetadataAttachment(MDK, N))
518       return true;
519     MDs.push_back({MDK, N});
520   }
521 
522   Function *F;
523   if (parseFunctionHeader(F, false))
524     return true;
525   for (auto &MD : MDs)
526     F->addMetadata(MD.first, *MD.second);
527   return false;
528 }
529 
530 /// toplevelentity
531 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
532 bool LLParser::parseDefine() {
533   assert(Lex.getKind() == lltok::kw_define);
534   Lex.Lex();
535 
536   Function *F;
537   return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
538          parseFunctionBody(*F);
539 }
540 
541 /// parseGlobalType
542 ///   ::= 'constant'
543 ///   ::= 'global'
544 bool LLParser::parseGlobalType(bool &IsConstant) {
545   if (Lex.getKind() == lltok::kw_constant)
546     IsConstant = true;
547   else if (Lex.getKind() == lltok::kw_global)
548     IsConstant = false;
549   else {
550     IsConstant = false;
551     return tokError("expected 'global' or 'constant'");
552   }
553   Lex.Lex();
554   return false;
555 }
556 
557 bool LLParser::parseOptionalUnnamedAddr(
558     GlobalVariable::UnnamedAddr &UnnamedAddr) {
559   if (EatIfPresent(lltok::kw_unnamed_addr))
560     UnnamedAddr = GlobalValue::UnnamedAddr::Global;
561   else if (EatIfPresent(lltok::kw_local_unnamed_addr))
562     UnnamedAddr = GlobalValue::UnnamedAddr::Local;
563   else
564     UnnamedAddr = GlobalValue::UnnamedAddr::None;
565   return false;
566 }
567 
568 /// parseUnnamedGlobal:
569 ///   OptionalVisibility (ALIAS | IFUNC) ...
570 ///   OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
571 ///   OptionalDLLStorageClass
572 ///                                                     ...   -> global variable
573 ///   GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
574 ///   GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
575 ///   OptionalVisibility
576 ///                OptionalDLLStorageClass
577 ///                                                     ...   -> global variable
578 bool LLParser::parseUnnamedGlobal() {
579   unsigned VarID = NumberedVals.size();
580   std::string Name;
581   LocTy NameLoc = Lex.getLoc();
582 
583   // Handle the GlobalID form.
584   if (Lex.getKind() == lltok::GlobalID) {
585     if (Lex.getUIntVal() != VarID)
586       return error(Lex.getLoc(),
587                    "variable expected to be numbered '%" + Twine(VarID) + "'");
588     Lex.Lex(); // eat GlobalID;
589 
590     if (parseToken(lltok::equal, "expected '=' after name"))
591       return true;
592   }
593 
594   bool HasLinkage;
595   unsigned Linkage, Visibility, DLLStorageClass;
596   bool DSOLocal;
597   GlobalVariable::ThreadLocalMode TLM;
598   GlobalVariable::UnnamedAddr UnnamedAddr;
599   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
600                            DSOLocal) ||
601       parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
602     return true;
603 
604   switch (Lex.getKind()) {
605   default:
606     return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
607                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
608   case lltok::kw_alias:
609   case lltok::kw_ifunc:
610     return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
611                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
612   }
613 }
614 
615 /// parseNamedGlobal:
616 ///   GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
617 ///   GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
618 ///                 OptionalVisibility OptionalDLLStorageClass
619 ///                                                     ...   -> global variable
620 bool LLParser::parseNamedGlobal() {
621   assert(Lex.getKind() == lltok::GlobalVar);
622   LocTy NameLoc = Lex.getLoc();
623   std::string Name = Lex.getStrVal();
624   Lex.Lex();
625 
626   bool HasLinkage;
627   unsigned Linkage, Visibility, DLLStorageClass;
628   bool DSOLocal;
629   GlobalVariable::ThreadLocalMode TLM;
630   GlobalVariable::UnnamedAddr UnnamedAddr;
631   if (parseToken(lltok::equal, "expected '=' in global variable") ||
632       parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
633                            DSOLocal) ||
634       parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
635     return true;
636 
637   switch (Lex.getKind()) {
638   default:
639     return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
640                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
641   case lltok::kw_alias:
642   case lltok::kw_ifunc:
643     return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
644                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
645   }
646 }
647 
648 bool LLParser::parseComdat() {
649   assert(Lex.getKind() == lltok::ComdatVar);
650   std::string Name = Lex.getStrVal();
651   LocTy NameLoc = Lex.getLoc();
652   Lex.Lex();
653 
654   if (parseToken(lltok::equal, "expected '=' here"))
655     return true;
656 
657   if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
658     return tokError("expected comdat type");
659 
660   Comdat::SelectionKind SK;
661   switch (Lex.getKind()) {
662   default:
663     return tokError("unknown selection kind");
664   case lltok::kw_any:
665     SK = Comdat::Any;
666     break;
667   case lltok::kw_exactmatch:
668     SK = Comdat::ExactMatch;
669     break;
670   case lltok::kw_largest:
671     SK = Comdat::Largest;
672     break;
673   case lltok::kw_nodeduplicate:
674     SK = Comdat::NoDeduplicate;
675     break;
676   case lltok::kw_samesize:
677     SK = Comdat::SameSize;
678     break;
679   }
680   Lex.Lex();
681 
682   // See if the comdat was forward referenced, if so, use the comdat.
683   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
684   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
685   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
686     return error(NameLoc, "redefinition of comdat '$" + Name + "'");
687 
688   Comdat *C;
689   if (I != ComdatSymTab.end())
690     C = &I->second;
691   else
692     C = M->getOrInsertComdat(Name);
693   C->setSelectionKind(SK);
694 
695   return false;
696 }
697 
698 // MDString:
699 //   ::= '!' STRINGCONSTANT
700 bool LLParser::parseMDString(MDString *&Result) {
701   std::string Str;
702   if (parseStringConstant(Str))
703     return true;
704   Result = MDString::get(Context, Str);
705   return false;
706 }
707 
708 // MDNode:
709 //   ::= '!' MDNodeNumber
710 bool LLParser::parseMDNodeID(MDNode *&Result) {
711   // !{ ..., !42, ... }
712   LocTy IDLoc = Lex.getLoc();
713   unsigned MID = 0;
714   if (parseUInt32(MID))
715     return true;
716 
717   // If not a forward reference, just return it now.
718   if (NumberedMetadata.count(MID)) {
719     Result = NumberedMetadata[MID];
720     return false;
721   }
722 
723   // Otherwise, create MDNode forward reference.
724   auto &FwdRef = ForwardRefMDNodes[MID];
725   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
726 
727   Result = FwdRef.first.get();
728   NumberedMetadata[MID].reset(Result);
729   return false;
730 }
731 
732 /// parseNamedMetadata:
733 ///   !foo = !{ !1, !2 }
734 bool LLParser::parseNamedMetadata() {
735   assert(Lex.getKind() == lltok::MetadataVar);
736   std::string Name = Lex.getStrVal();
737   Lex.Lex();
738 
739   if (parseToken(lltok::equal, "expected '=' here") ||
740       parseToken(lltok::exclaim, "Expected '!' here") ||
741       parseToken(lltok::lbrace, "Expected '{' here"))
742     return true;
743 
744   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
745   if (Lex.getKind() != lltok::rbrace)
746     do {
747       MDNode *N = nullptr;
748       // parse DIExpressions inline as a special case. They are still MDNodes,
749       // so they can still appear in named metadata. Remove this logic if they
750       // become plain Metadata.
751       if (Lex.getKind() == lltok::MetadataVar &&
752           Lex.getStrVal() == "DIExpression") {
753         if (parseDIExpression(N, /*IsDistinct=*/false))
754           return true;
755         // DIArgLists should only appear inline in a function, as they may
756         // contain LocalAsMetadata arguments which require a function context.
757       } else if (Lex.getKind() == lltok::MetadataVar &&
758                  Lex.getStrVal() == "DIArgList") {
759         return tokError("found DIArgList outside of function");
760       } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
761                  parseMDNodeID(N)) {
762         return true;
763       }
764       NMD->addOperand(N);
765     } while (EatIfPresent(lltok::comma));
766 
767   return parseToken(lltok::rbrace, "expected end of metadata node");
768 }
769 
770 /// parseStandaloneMetadata:
771 ///   !42 = !{...}
772 bool LLParser::parseStandaloneMetadata() {
773   assert(Lex.getKind() == lltok::exclaim);
774   Lex.Lex();
775   unsigned MetadataID = 0;
776 
777   MDNode *Init;
778   if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
779     return true;
780 
781   // Detect common error, from old metadata syntax.
782   if (Lex.getKind() == lltok::Type)
783     return tokError("unexpected type in metadata definition");
784 
785   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
786   if (Lex.getKind() == lltok::MetadataVar) {
787     if (parseSpecializedMDNode(Init, IsDistinct))
788       return true;
789   } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
790              parseMDTuple(Init, IsDistinct))
791     return true;
792 
793   // See if this was forward referenced, if so, handle it.
794   auto FI = ForwardRefMDNodes.find(MetadataID);
795   if (FI != ForwardRefMDNodes.end()) {
796     FI->second.first->replaceAllUsesWith(Init);
797     ForwardRefMDNodes.erase(FI);
798 
799     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
800   } else {
801     if (NumberedMetadata.count(MetadataID))
802       return tokError("Metadata id is already used");
803     NumberedMetadata[MetadataID].reset(Init);
804   }
805 
806   return false;
807 }
808 
809 // Skips a single module summary entry.
810 bool LLParser::skipModuleSummaryEntry() {
811   // Each module summary entry consists of a tag for the entry
812   // type, followed by a colon, then the fields which may be surrounded by
813   // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
814   // support is in place we will look for the tokens corresponding to the
815   // expected tags.
816   if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
817       Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
818       Lex.getKind() != lltok::kw_blockcount)
819     return tokError(
820         "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
821         "start of summary entry");
822   if (Lex.getKind() == lltok::kw_flags)
823     return parseSummaryIndexFlags();
824   if (Lex.getKind() == lltok::kw_blockcount)
825     return parseBlockCount();
826   Lex.Lex();
827   if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
828       parseToken(lltok::lparen, "expected '(' at start of summary entry"))
829     return true;
830   // Now walk through the parenthesized entry, until the number of open
831   // parentheses goes back down to 0 (the first '(' was parsed above).
832   unsigned NumOpenParen = 1;
833   do {
834     switch (Lex.getKind()) {
835     case lltok::lparen:
836       NumOpenParen++;
837       break;
838     case lltok::rparen:
839       NumOpenParen--;
840       break;
841     case lltok::Eof:
842       return tokError("found end of file while parsing summary entry");
843     default:
844       // Skip everything in between parentheses.
845       break;
846     }
847     Lex.Lex();
848   } while (NumOpenParen > 0);
849   return false;
850 }
851 
852 /// SummaryEntry
853 ///   ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
854 bool LLParser::parseSummaryEntry() {
855   assert(Lex.getKind() == lltok::SummaryID);
856   unsigned SummaryID = Lex.getUIntVal();
857 
858   // For summary entries, colons should be treated as distinct tokens,
859   // not an indication of the end of a label token.
860   Lex.setIgnoreColonInIdentifiers(true);
861 
862   Lex.Lex();
863   if (parseToken(lltok::equal, "expected '=' here"))
864     return true;
865 
866   // If we don't have an index object, skip the summary entry.
867   if (!Index)
868     return skipModuleSummaryEntry();
869 
870   bool result = false;
871   switch (Lex.getKind()) {
872   case lltok::kw_gv:
873     result = parseGVEntry(SummaryID);
874     break;
875   case lltok::kw_module:
876     result = parseModuleEntry(SummaryID);
877     break;
878   case lltok::kw_typeid:
879     result = parseTypeIdEntry(SummaryID);
880     break;
881   case lltok::kw_typeidCompatibleVTable:
882     result = parseTypeIdCompatibleVtableEntry(SummaryID);
883     break;
884   case lltok::kw_flags:
885     result = parseSummaryIndexFlags();
886     break;
887   case lltok::kw_blockcount:
888     result = parseBlockCount();
889     break;
890   default:
891     result = error(Lex.getLoc(), "unexpected summary kind");
892     break;
893   }
894   Lex.setIgnoreColonInIdentifiers(false);
895   return result;
896 }
897 
898 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
899   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
900          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
901 }
902 
903 // If there was an explicit dso_local, update GV. In the absence of an explicit
904 // dso_local we keep the default value.
905 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
906   if (DSOLocal)
907     GV.setDSOLocal(true);
908 }
909 
910 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
911                                               Type *Ty2) {
912   std::string ErrString;
913   raw_string_ostream ErrOS(ErrString);
914   ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
915   return ErrOS.str();
916 }
917 
918 /// parseAliasOrIFunc:
919 ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
920 ///                     OptionalVisibility OptionalDLLStorageClass
921 ///                     OptionalThreadLocal OptionalUnnamedAddr
922 ///                     'alias|ifunc' AliaseeOrResolver SymbolAttrs*
923 ///
924 /// AliaseeOrResolver
925 ///   ::= TypeAndValue
926 ///
927 /// SymbolAttrs
928 ///   ::= ',' 'partition' StringConstant
929 ///
930 /// Everything through OptionalUnnamedAddr has already been parsed.
931 ///
932 bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc,
933                                  unsigned L, unsigned Visibility,
934                                  unsigned DLLStorageClass, bool DSOLocal,
935                                  GlobalVariable::ThreadLocalMode TLM,
936                                  GlobalVariable::UnnamedAddr UnnamedAddr) {
937   bool IsAlias;
938   if (Lex.getKind() == lltok::kw_alias)
939     IsAlias = true;
940   else if (Lex.getKind() == lltok::kw_ifunc)
941     IsAlias = false;
942   else
943     llvm_unreachable("Not an alias or ifunc!");
944   Lex.Lex();
945 
946   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
947 
948   if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
949     return error(NameLoc, "invalid linkage type for alias");
950 
951   if (!isValidVisibilityForLinkage(Visibility, L))
952     return error(NameLoc,
953                  "symbol with local linkage must have default visibility");
954 
955   Type *Ty;
956   LocTy ExplicitTypeLoc = Lex.getLoc();
957   if (parseType(Ty) ||
958       parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
959     return true;
960 
961   Constant *Aliasee;
962   LocTy AliaseeLoc = Lex.getLoc();
963   if (Lex.getKind() != lltok::kw_bitcast &&
964       Lex.getKind() != lltok::kw_getelementptr &&
965       Lex.getKind() != lltok::kw_addrspacecast &&
966       Lex.getKind() != lltok::kw_inttoptr) {
967     if (parseGlobalTypeAndValue(Aliasee))
968       return true;
969   } else {
970     // The bitcast dest type is not present, it is implied by the dest type.
971     ValID ID;
972     if (parseValID(ID, /*PFS=*/nullptr))
973       return true;
974     if (ID.Kind != ValID::t_Constant)
975       return error(AliaseeLoc, "invalid aliasee");
976     Aliasee = ID.ConstantVal;
977   }
978 
979   Type *AliaseeType = Aliasee->getType();
980   auto *PTy = dyn_cast<PointerType>(AliaseeType);
981   if (!PTy)
982     return error(AliaseeLoc, "An alias or ifunc must have pointer type");
983   unsigned AddrSpace = PTy->getAddressSpace();
984 
985   if (IsAlias && !PTy->isOpaqueOrPointeeTypeMatches(Ty)) {
986     return error(
987         ExplicitTypeLoc,
988         typeComparisonErrorMessage(
989             "explicit pointee type doesn't match operand's pointee type", Ty,
990             PTy->getElementType()));
991   }
992 
993   if (!IsAlias && !PTy->getElementType()->isFunctionTy()) {
994     return error(ExplicitTypeLoc,
995                  "explicit pointee type should be a function type");
996   }
997 
998   GlobalValue *GVal = nullptr;
999 
1000   // See if the alias was forward referenced, if so, prepare to replace the
1001   // forward reference.
1002   if (!Name.empty()) {
1003     auto I = ForwardRefVals.find(Name);
1004     if (I != ForwardRefVals.end()) {
1005       GVal = I->second.first;
1006       ForwardRefVals.erase(Name);
1007     } else if (M->getNamedValue(Name)) {
1008       return error(NameLoc, "redefinition of global '@" + Name + "'");
1009     }
1010   } else {
1011     auto I = ForwardRefValIDs.find(NumberedVals.size());
1012     if (I != ForwardRefValIDs.end()) {
1013       GVal = I->second.first;
1014       ForwardRefValIDs.erase(I);
1015     }
1016   }
1017 
1018   // Okay, create the alias/ifunc but do not insert it into the module yet.
1019   std::unique_ptr<GlobalAlias> GA;
1020   std::unique_ptr<GlobalIFunc> GI;
1021   GlobalValue *GV;
1022   if (IsAlias) {
1023     GA.reset(GlobalAlias::create(Ty, AddrSpace,
1024                                  (GlobalValue::LinkageTypes)Linkage, Name,
1025                                  Aliasee, /*Parent*/ nullptr));
1026     GV = GA.get();
1027   } else {
1028     GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1029                                  (GlobalValue::LinkageTypes)Linkage, Name,
1030                                  Aliasee, /*Parent*/ nullptr));
1031     GV = GI.get();
1032   }
1033   GV->setThreadLocalMode(TLM);
1034   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1035   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1036   GV->setUnnamedAddr(UnnamedAddr);
1037   maybeSetDSOLocal(DSOLocal, *GV);
1038 
1039   // At this point we've parsed everything except for the IndirectSymbolAttrs.
1040   // Now parse them if there are any.
1041   while (Lex.getKind() == lltok::comma) {
1042     Lex.Lex();
1043 
1044     if (Lex.getKind() == lltok::kw_partition) {
1045       Lex.Lex();
1046       GV->setPartition(Lex.getStrVal());
1047       if (parseToken(lltok::StringConstant, "expected partition string"))
1048         return true;
1049     } else {
1050       return tokError("unknown alias or ifunc property!");
1051     }
1052   }
1053 
1054   if (Name.empty())
1055     NumberedVals.push_back(GV);
1056 
1057   if (GVal) {
1058     // Verify that types agree.
1059     if (GVal->getType() != GV->getType())
1060       return error(
1061           ExplicitTypeLoc,
1062           "forward reference and definition of alias have different types");
1063 
1064     // If they agree, just RAUW the old value with the alias and remove the
1065     // forward ref info.
1066     GVal->replaceAllUsesWith(GV);
1067     GVal->eraseFromParent();
1068   }
1069 
1070   // Insert into the module, we know its name won't collide now.
1071   if (IsAlias)
1072     M->getAliasList().push_back(GA.release());
1073   else
1074     M->getIFuncList().push_back(GI.release());
1075   assert(GV->getName() == Name && "Should not be a name conflict!");
1076 
1077   return false;
1078 }
1079 
1080 /// parseGlobal
1081 ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1082 ///       OptionalVisibility OptionalDLLStorageClass
1083 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1084 ///       OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1085 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1086 ///       OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1087 ///       OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1088 ///       Const OptionalAttrs
1089 ///
1090 /// Everything up to and including OptionalUnnamedAddr has been parsed
1091 /// already.
1092 ///
1093 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1094                            unsigned Linkage, bool HasLinkage,
1095                            unsigned Visibility, unsigned DLLStorageClass,
1096                            bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1097                            GlobalVariable::UnnamedAddr UnnamedAddr) {
1098   if (!isValidVisibilityForLinkage(Visibility, Linkage))
1099     return error(NameLoc,
1100                  "symbol with local linkage must have default visibility");
1101 
1102   unsigned AddrSpace;
1103   bool IsConstant, IsExternallyInitialized;
1104   LocTy IsExternallyInitializedLoc;
1105   LocTy TyLoc;
1106 
1107   Type *Ty = nullptr;
1108   if (parseOptionalAddrSpace(AddrSpace) ||
1109       parseOptionalToken(lltok::kw_externally_initialized,
1110                          IsExternallyInitialized,
1111                          &IsExternallyInitializedLoc) ||
1112       parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1113     return true;
1114 
1115   // If the linkage is specified and is external, then no initializer is
1116   // present.
1117   Constant *Init = nullptr;
1118   if (!HasLinkage ||
1119       !GlobalValue::isValidDeclarationLinkage(
1120           (GlobalValue::LinkageTypes)Linkage)) {
1121     if (parseGlobalValue(Ty, Init))
1122       return true;
1123   }
1124 
1125   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1126     return error(TyLoc, "invalid type for global variable");
1127 
1128   GlobalValue *GVal = nullptr;
1129 
1130   // See if the global was forward referenced, if so, use the global.
1131   if (!Name.empty()) {
1132     auto I = ForwardRefVals.find(Name);
1133     if (I != ForwardRefVals.end()) {
1134       GVal = I->second.first;
1135       ForwardRefVals.erase(I);
1136     } else if (M->getNamedValue(Name)) {
1137       return error(NameLoc, "redefinition of global '@" + Name + "'");
1138     }
1139   } else {
1140     auto I = ForwardRefValIDs.find(NumberedVals.size());
1141     if (I != ForwardRefValIDs.end()) {
1142       GVal = I->second.first;
1143       ForwardRefValIDs.erase(I);
1144     }
1145   }
1146 
1147   GlobalVariable *GV = new GlobalVariable(
1148       *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1149       GlobalVariable::NotThreadLocal, AddrSpace);
1150 
1151   if (Name.empty())
1152     NumberedVals.push_back(GV);
1153 
1154   // Set the parsed properties on the global.
1155   if (Init)
1156     GV->setInitializer(Init);
1157   GV->setConstant(IsConstant);
1158   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1159   maybeSetDSOLocal(DSOLocal, *GV);
1160   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1161   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1162   GV->setExternallyInitialized(IsExternallyInitialized);
1163   GV->setThreadLocalMode(TLM);
1164   GV->setUnnamedAddr(UnnamedAddr);
1165 
1166   if (GVal) {
1167     if (!GVal->getType()->isOpaque() && GVal->getValueType() != Ty)
1168       return error(
1169           TyLoc,
1170           "forward reference and definition of global have different types");
1171 
1172     GVal->replaceAllUsesWith(GV);
1173     GVal->eraseFromParent();
1174   }
1175 
1176   // parse attributes on the global.
1177   while (Lex.getKind() == lltok::comma) {
1178     Lex.Lex();
1179 
1180     if (Lex.getKind() == lltok::kw_section) {
1181       Lex.Lex();
1182       GV->setSection(Lex.getStrVal());
1183       if (parseToken(lltok::StringConstant, "expected global section string"))
1184         return true;
1185     } else if (Lex.getKind() == lltok::kw_partition) {
1186       Lex.Lex();
1187       GV->setPartition(Lex.getStrVal());
1188       if (parseToken(lltok::StringConstant, "expected partition string"))
1189         return true;
1190     } else if (Lex.getKind() == lltok::kw_align) {
1191       MaybeAlign Alignment;
1192       if (parseOptionalAlignment(Alignment))
1193         return true;
1194       GV->setAlignment(Alignment);
1195     } else if (Lex.getKind() == lltok::MetadataVar) {
1196       if (parseGlobalObjectMetadataAttachment(*GV))
1197         return true;
1198     } else {
1199       Comdat *C;
1200       if (parseOptionalComdat(Name, C))
1201         return true;
1202       if (C)
1203         GV->setComdat(C);
1204       else
1205         return tokError("unknown global variable property!");
1206     }
1207   }
1208 
1209   AttrBuilder Attrs;
1210   LocTy BuiltinLoc;
1211   std::vector<unsigned> FwdRefAttrGrps;
1212   if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1213     return true;
1214   if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1215     GV->setAttributes(AttributeSet::get(Context, Attrs));
1216     ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1217   }
1218 
1219   return false;
1220 }
1221 
1222 /// parseUnnamedAttrGrp
1223 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1224 bool LLParser::parseUnnamedAttrGrp() {
1225   assert(Lex.getKind() == lltok::kw_attributes);
1226   LocTy AttrGrpLoc = Lex.getLoc();
1227   Lex.Lex();
1228 
1229   if (Lex.getKind() != lltok::AttrGrpID)
1230     return tokError("expected attribute group id");
1231 
1232   unsigned VarID = Lex.getUIntVal();
1233   std::vector<unsigned> unused;
1234   LocTy BuiltinLoc;
1235   Lex.Lex();
1236 
1237   if (parseToken(lltok::equal, "expected '=' here") ||
1238       parseToken(lltok::lbrace, "expected '{' here") ||
1239       parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1240                                  BuiltinLoc) ||
1241       parseToken(lltok::rbrace, "expected end of attribute group"))
1242     return true;
1243 
1244   if (!NumberedAttrBuilders[VarID].hasAttributes())
1245     return error(AttrGrpLoc, "attribute group has no attributes");
1246 
1247   return false;
1248 }
1249 
1250 static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
1251   switch (Kind) {
1252 #define GET_ATTR_NAMES
1253 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1254   case lltok::kw_##DISPLAY_NAME: \
1255     return Attribute::ENUM_NAME;
1256 #include "llvm/IR/Attributes.inc"
1257   default:
1258     return Attribute::None;
1259   }
1260 }
1261 
1262 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1263                                   bool InAttrGroup) {
1264   if (Attribute::isTypeAttrKind(Attr))
1265     return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1266 
1267   switch (Attr) {
1268   case Attribute::Alignment: {
1269     MaybeAlign Alignment;
1270     if (InAttrGroup) {
1271       uint32_t Value = 0;
1272       Lex.Lex();
1273       if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1274         return true;
1275       Alignment = Align(Value);
1276     } else {
1277       if (parseOptionalAlignment(Alignment, true))
1278         return true;
1279     }
1280     B.addAlignmentAttr(Alignment);
1281     return false;
1282   }
1283   case Attribute::StackAlignment: {
1284     unsigned Alignment;
1285     if (InAttrGroup) {
1286       Lex.Lex();
1287       if (parseToken(lltok::equal, "expected '=' here") ||
1288           parseUInt32(Alignment))
1289         return true;
1290     } else {
1291       if (parseOptionalStackAlignment(Alignment))
1292         return true;
1293     }
1294     B.addStackAlignmentAttr(Alignment);
1295     return false;
1296   }
1297   case Attribute::AllocSize: {
1298     unsigned ElemSizeArg;
1299     Optional<unsigned> NumElemsArg;
1300     if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1301       return true;
1302     B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1303     return false;
1304   }
1305   case Attribute::VScaleRange: {
1306     unsigned MinValue, MaxValue;
1307     if (parseVScaleRangeArguments(MinValue, MaxValue))
1308       return true;
1309     B.addVScaleRangeAttr(MinValue, MaxValue);
1310     return false;
1311   }
1312   case Attribute::Dereferenceable: {
1313     uint64_t Bytes;
1314     if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1315       return true;
1316     B.addDereferenceableAttr(Bytes);
1317     return false;
1318   }
1319   case Attribute::DereferenceableOrNull: {
1320     uint64_t Bytes;
1321     if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1322       return true;
1323     B.addDereferenceableOrNullAttr(Bytes);
1324     return false;
1325   }
1326   default:
1327     B.addAttribute(Attr);
1328     Lex.Lex();
1329     return false;
1330   }
1331 }
1332 
1333 /// parseFnAttributeValuePairs
1334 ///   ::= <attr> | <attr> '=' <value>
1335 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1336                                           std::vector<unsigned> &FwdRefAttrGrps,
1337                                           bool InAttrGrp, LocTy &BuiltinLoc) {
1338   bool HaveError = false;
1339 
1340   B.clear();
1341 
1342   while (true) {
1343     lltok::Kind Token = Lex.getKind();
1344     if (Token == lltok::rbrace)
1345       return HaveError; // Finished.
1346 
1347     if (Token == lltok::StringConstant) {
1348       if (parseStringAttribute(B))
1349         return true;
1350       continue;
1351     }
1352 
1353     if (Token == lltok::AttrGrpID) {
1354       // Allow a function to reference an attribute group:
1355       //
1356       //   define void @foo() #1 { ... }
1357       if (InAttrGrp) {
1358         HaveError |= error(
1359             Lex.getLoc(),
1360             "cannot have an attribute group reference in an attribute group");
1361       } else {
1362         // Save the reference to the attribute group. We'll fill it in later.
1363         FwdRefAttrGrps.push_back(Lex.getUIntVal());
1364       }
1365       Lex.Lex();
1366       continue;
1367     }
1368 
1369     SMLoc Loc = Lex.getLoc();
1370     if (Token == lltok::kw_builtin)
1371       BuiltinLoc = Loc;
1372 
1373     Attribute::AttrKind Attr = tokenToAttribute(Token);
1374     if (Attr == Attribute::None) {
1375       if (!InAttrGrp)
1376         return HaveError;
1377       return error(Lex.getLoc(), "unterminated attribute group");
1378     }
1379 
1380     if (parseEnumAttribute(Attr, B, InAttrGrp))
1381       return true;
1382 
1383     // As a hack, we allow function alignment to be initially parsed as an
1384     // attribute on a function declaration/definition or added to an attribute
1385     // group and later moved to the alignment field.
1386     if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1387       HaveError |= error(Loc, "this attribute does not apply to functions");
1388   }
1389 }
1390 
1391 //===----------------------------------------------------------------------===//
1392 // GlobalValue Reference/Resolution Routines.
1393 //===----------------------------------------------------------------------===//
1394 
1395 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
1396   // For opaque pointers, the used global type does not matter. We will later
1397   // RAUW it with a global/function of the correct type.
1398   if (PTy->isOpaque())
1399     return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1400                               GlobalValue::ExternalWeakLinkage, nullptr, "",
1401                               nullptr, GlobalVariable::NotThreadLocal,
1402                               PTy->getAddressSpace());
1403 
1404   if (auto *FT = dyn_cast<FunctionType>(PTy->getPointerElementType()))
1405     return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1406                             PTy->getAddressSpace(), "", M);
1407   else
1408     return new GlobalVariable(*M, PTy->getPointerElementType(), false,
1409                               GlobalValue::ExternalWeakLinkage, nullptr, "",
1410                               nullptr, GlobalVariable::NotThreadLocal,
1411                               PTy->getAddressSpace());
1412 }
1413 
1414 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1415                                         Value *Val) {
1416   Type *ValTy = Val->getType();
1417   if (ValTy == Ty)
1418     return Val;
1419   if (Ty->isLabelTy())
1420     error(Loc, "'" + Name + "' is not a basic block");
1421   else
1422     error(Loc, "'" + Name + "' defined with type '" +
1423                    getTypeString(Val->getType()) + "' but expected '" +
1424                    getTypeString(Ty) + "'");
1425   return nullptr;
1426 }
1427 
1428 /// getGlobalVal - Get a value with the specified name or ID, creating a
1429 /// forward reference record if needed.  This can return null if the value
1430 /// exists but does not have the right type.
1431 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1432                                     LocTy Loc) {
1433   PointerType *PTy = dyn_cast<PointerType>(Ty);
1434   if (!PTy) {
1435     error(Loc, "global variable reference must have pointer type");
1436     return nullptr;
1437   }
1438 
1439   // Look this name up in the normal function symbol table.
1440   GlobalValue *Val =
1441     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1442 
1443   // If this is a forward reference for the value, see if we already created a
1444   // forward ref record.
1445   if (!Val) {
1446     auto I = ForwardRefVals.find(Name);
1447     if (I != ForwardRefVals.end())
1448       Val = I->second.first;
1449   }
1450 
1451   // If we have the value in the symbol table or fwd-ref table, return it.
1452   if (Val)
1453     return cast_or_null<GlobalValue>(
1454         checkValidVariableType(Loc, "@" + Name, Ty, Val));
1455 
1456   // Otherwise, create a new forward reference for this value and remember it.
1457   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1458   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1459   return FwdVal;
1460 }
1461 
1462 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1463   PointerType *PTy = dyn_cast<PointerType>(Ty);
1464   if (!PTy) {
1465     error(Loc, "global variable reference must have pointer type");
1466     return nullptr;
1467   }
1468 
1469   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1470 
1471   // If this is a forward reference for the value, see if we already created a
1472   // forward ref record.
1473   if (!Val) {
1474     auto I = ForwardRefValIDs.find(ID);
1475     if (I != ForwardRefValIDs.end())
1476       Val = I->second.first;
1477   }
1478 
1479   // If we have the value in the symbol table or fwd-ref table, return it.
1480   if (Val)
1481     return cast_or_null<GlobalValue>(
1482         checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1483 
1484   // Otherwise, create a new forward reference for this value and remember it.
1485   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1486   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1487   return FwdVal;
1488 }
1489 
1490 //===----------------------------------------------------------------------===//
1491 // Comdat Reference/Resolution Routines.
1492 //===----------------------------------------------------------------------===//
1493 
1494 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1495   // Look this name up in the comdat symbol table.
1496   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1497   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1498   if (I != ComdatSymTab.end())
1499     return &I->second;
1500 
1501   // Otherwise, create a new forward reference for this value and remember it.
1502   Comdat *C = M->getOrInsertComdat(Name);
1503   ForwardRefComdats[Name] = Loc;
1504   return C;
1505 }
1506 
1507 //===----------------------------------------------------------------------===//
1508 // Helper Routines.
1509 //===----------------------------------------------------------------------===//
1510 
1511 /// parseToken - If the current token has the specified kind, eat it and return
1512 /// success.  Otherwise, emit the specified error and return failure.
1513 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1514   if (Lex.getKind() != T)
1515     return tokError(ErrMsg);
1516   Lex.Lex();
1517   return false;
1518 }
1519 
1520 /// parseStringConstant
1521 ///   ::= StringConstant
1522 bool LLParser::parseStringConstant(std::string &Result) {
1523   if (Lex.getKind() != lltok::StringConstant)
1524     return tokError("expected string constant");
1525   Result = Lex.getStrVal();
1526   Lex.Lex();
1527   return false;
1528 }
1529 
1530 /// parseUInt32
1531 ///   ::= uint32
1532 bool LLParser::parseUInt32(uint32_t &Val) {
1533   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1534     return tokError("expected integer");
1535   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1536   if (Val64 != unsigned(Val64))
1537     return tokError("expected 32-bit integer (too large)");
1538   Val = Val64;
1539   Lex.Lex();
1540   return false;
1541 }
1542 
1543 /// parseUInt64
1544 ///   ::= uint64
1545 bool LLParser::parseUInt64(uint64_t &Val) {
1546   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1547     return tokError("expected integer");
1548   Val = Lex.getAPSIntVal().getLimitedValue();
1549   Lex.Lex();
1550   return false;
1551 }
1552 
1553 /// parseTLSModel
1554 ///   := 'localdynamic'
1555 ///   := 'initialexec'
1556 ///   := 'localexec'
1557 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1558   switch (Lex.getKind()) {
1559     default:
1560       return tokError("expected localdynamic, initialexec or localexec");
1561     case lltok::kw_localdynamic:
1562       TLM = GlobalVariable::LocalDynamicTLSModel;
1563       break;
1564     case lltok::kw_initialexec:
1565       TLM = GlobalVariable::InitialExecTLSModel;
1566       break;
1567     case lltok::kw_localexec:
1568       TLM = GlobalVariable::LocalExecTLSModel;
1569       break;
1570   }
1571 
1572   Lex.Lex();
1573   return false;
1574 }
1575 
1576 /// parseOptionalThreadLocal
1577 ///   := /*empty*/
1578 ///   := 'thread_local'
1579 ///   := 'thread_local' '(' tlsmodel ')'
1580 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1581   TLM = GlobalVariable::NotThreadLocal;
1582   if (!EatIfPresent(lltok::kw_thread_local))
1583     return false;
1584 
1585   TLM = GlobalVariable::GeneralDynamicTLSModel;
1586   if (Lex.getKind() == lltok::lparen) {
1587     Lex.Lex();
1588     return parseTLSModel(TLM) ||
1589            parseToken(lltok::rparen, "expected ')' after thread local model");
1590   }
1591   return false;
1592 }
1593 
1594 /// parseOptionalAddrSpace
1595 ///   := /*empty*/
1596 ///   := 'addrspace' '(' uint32 ')'
1597 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1598   AddrSpace = DefaultAS;
1599   if (!EatIfPresent(lltok::kw_addrspace))
1600     return false;
1601   return parseToken(lltok::lparen, "expected '(' in address space") ||
1602          parseUInt32(AddrSpace) ||
1603          parseToken(lltok::rparen, "expected ')' in address space");
1604 }
1605 
1606 /// parseStringAttribute
1607 ///   := StringConstant
1608 ///   := StringConstant '=' StringConstant
1609 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1610   std::string Attr = Lex.getStrVal();
1611   Lex.Lex();
1612   std::string Val;
1613   if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1614     return true;
1615   B.addAttribute(Attr, Val);
1616   return false;
1617 }
1618 
1619 /// Parse a potentially empty list of parameter or return attributes.
1620 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1621   bool HaveError = false;
1622 
1623   B.clear();
1624 
1625   while (true) {
1626     lltok::Kind Token = Lex.getKind();
1627     if (Token == lltok::StringConstant) {
1628       if (parseStringAttribute(B))
1629         return true;
1630       continue;
1631     }
1632 
1633     SMLoc Loc = Lex.getLoc();
1634     Attribute::AttrKind Attr = tokenToAttribute(Token);
1635     if (Attr == Attribute::None)
1636       return HaveError;
1637 
1638     if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1639       return true;
1640 
1641     if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1642       HaveError |= error(Loc, "this attribute does not apply to parameters");
1643     if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1644       HaveError |= error(Loc, "this attribute does not apply to return values");
1645   }
1646 }
1647 
1648 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1649   HasLinkage = true;
1650   switch (Kind) {
1651   default:
1652     HasLinkage = false;
1653     return GlobalValue::ExternalLinkage;
1654   case lltok::kw_private:
1655     return GlobalValue::PrivateLinkage;
1656   case lltok::kw_internal:
1657     return GlobalValue::InternalLinkage;
1658   case lltok::kw_weak:
1659     return GlobalValue::WeakAnyLinkage;
1660   case lltok::kw_weak_odr:
1661     return GlobalValue::WeakODRLinkage;
1662   case lltok::kw_linkonce:
1663     return GlobalValue::LinkOnceAnyLinkage;
1664   case lltok::kw_linkonce_odr:
1665     return GlobalValue::LinkOnceODRLinkage;
1666   case lltok::kw_available_externally:
1667     return GlobalValue::AvailableExternallyLinkage;
1668   case lltok::kw_appending:
1669     return GlobalValue::AppendingLinkage;
1670   case lltok::kw_common:
1671     return GlobalValue::CommonLinkage;
1672   case lltok::kw_extern_weak:
1673     return GlobalValue::ExternalWeakLinkage;
1674   case lltok::kw_external:
1675     return GlobalValue::ExternalLinkage;
1676   }
1677 }
1678 
1679 /// parseOptionalLinkage
1680 ///   ::= /*empty*/
1681 ///   ::= 'private'
1682 ///   ::= 'internal'
1683 ///   ::= 'weak'
1684 ///   ::= 'weak_odr'
1685 ///   ::= 'linkonce'
1686 ///   ::= 'linkonce_odr'
1687 ///   ::= 'available_externally'
1688 ///   ::= 'appending'
1689 ///   ::= 'common'
1690 ///   ::= 'extern_weak'
1691 ///   ::= 'external'
1692 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1693                                     unsigned &Visibility,
1694                                     unsigned &DLLStorageClass, bool &DSOLocal) {
1695   Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1696   if (HasLinkage)
1697     Lex.Lex();
1698   parseOptionalDSOLocal(DSOLocal);
1699   parseOptionalVisibility(Visibility);
1700   parseOptionalDLLStorageClass(DLLStorageClass);
1701 
1702   if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1703     return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1704   }
1705 
1706   return false;
1707 }
1708 
1709 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1710   switch (Lex.getKind()) {
1711   default:
1712     DSOLocal = false;
1713     break;
1714   case lltok::kw_dso_local:
1715     DSOLocal = true;
1716     Lex.Lex();
1717     break;
1718   case lltok::kw_dso_preemptable:
1719     DSOLocal = false;
1720     Lex.Lex();
1721     break;
1722   }
1723 }
1724 
1725 /// parseOptionalVisibility
1726 ///   ::= /*empty*/
1727 ///   ::= 'default'
1728 ///   ::= 'hidden'
1729 ///   ::= 'protected'
1730 ///
1731 void LLParser::parseOptionalVisibility(unsigned &Res) {
1732   switch (Lex.getKind()) {
1733   default:
1734     Res = GlobalValue::DefaultVisibility;
1735     return;
1736   case lltok::kw_default:
1737     Res = GlobalValue::DefaultVisibility;
1738     break;
1739   case lltok::kw_hidden:
1740     Res = GlobalValue::HiddenVisibility;
1741     break;
1742   case lltok::kw_protected:
1743     Res = GlobalValue::ProtectedVisibility;
1744     break;
1745   }
1746   Lex.Lex();
1747 }
1748 
1749 /// parseOptionalDLLStorageClass
1750 ///   ::= /*empty*/
1751 ///   ::= 'dllimport'
1752 ///   ::= 'dllexport'
1753 ///
1754 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1755   switch (Lex.getKind()) {
1756   default:
1757     Res = GlobalValue::DefaultStorageClass;
1758     return;
1759   case lltok::kw_dllimport:
1760     Res = GlobalValue::DLLImportStorageClass;
1761     break;
1762   case lltok::kw_dllexport:
1763     Res = GlobalValue::DLLExportStorageClass;
1764     break;
1765   }
1766   Lex.Lex();
1767 }
1768 
1769 /// parseOptionalCallingConv
1770 ///   ::= /*empty*/
1771 ///   ::= 'ccc'
1772 ///   ::= 'fastcc'
1773 ///   ::= 'intel_ocl_bicc'
1774 ///   ::= 'coldcc'
1775 ///   ::= 'cfguard_checkcc'
1776 ///   ::= 'x86_stdcallcc'
1777 ///   ::= 'x86_fastcallcc'
1778 ///   ::= 'x86_thiscallcc'
1779 ///   ::= 'x86_vectorcallcc'
1780 ///   ::= 'arm_apcscc'
1781 ///   ::= 'arm_aapcscc'
1782 ///   ::= 'arm_aapcs_vfpcc'
1783 ///   ::= 'aarch64_vector_pcs'
1784 ///   ::= 'aarch64_sve_vector_pcs'
1785 ///   ::= 'msp430_intrcc'
1786 ///   ::= 'avr_intrcc'
1787 ///   ::= 'avr_signalcc'
1788 ///   ::= 'ptx_kernel'
1789 ///   ::= 'ptx_device'
1790 ///   ::= 'spir_func'
1791 ///   ::= 'spir_kernel'
1792 ///   ::= 'x86_64_sysvcc'
1793 ///   ::= 'win64cc'
1794 ///   ::= 'webkit_jscc'
1795 ///   ::= 'anyregcc'
1796 ///   ::= 'preserve_mostcc'
1797 ///   ::= 'preserve_allcc'
1798 ///   ::= 'ghccc'
1799 ///   ::= 'swiftcc'
1800 ///   ::= 'swifttailcc'
1801 ///   ::= 'x86_intrcc'
1802 ///   ::= 'hhvmcc'
1803 ///   ::= 'hhvm_ccc'
1804 ///   ::= 'cxx_fast_tlscc'
1805 ///   ::= 'amdgpu_vs'
1806 ///   ::= 'amdgpu_ls'
1807 ///   ::= 'amdgpu_hs'
1808 ///   ::= 'amdgpu_es'
1809 ///   ::= 'amdgpu_gs'
1810 ///   ::= 'amdgpu_ps'
1811 ///   ::= 'amdgpu_cs'
1812 ///   ::= 'amdgpu_kernel'
1813 ///   ::= 'tailcc'
1814 ///   ::= 'cc' UINT
1815 ///
1816 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
1817   switch (Lex.getKind()) {
1818   default:                       CC = CallingConv::C; return false;
1819   case lltok::kw_ccc:            CC = CallingConv::C; break;
1820   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1821   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1822   case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
1823   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1824   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1825   case lltok::kw_x86_regcallcc:  CC = CallingConv::X86_RegCall; break;
1826   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1827   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1828   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1829   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1830   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1831   case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1832   case lltok::kw_aarch64_sve_vector_pcs:
1833     CC = CallingConv::AArch64_SVE_VectorCall;
1834     break;
1835   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1836   case lltok::kw_avr_intrcc:     CC = CallingConv::AVR_INTR; break;
1837   case lltok::kw_avr_signalcc:   CC = CallingConv::AVR_SIGNAL; break;
1838   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1839   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1840   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1841   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1842   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1843   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1844   case lltok::kw_win64cc:        CC = CallingConv::Win64; break;
1845   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1846   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1847   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1848   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1849   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1850   case lltok::kw_swiftcc:        CC = CallingConv::Swift; break;
1851   case lltok::kw_swifttailcc:    CC = CallingConv::SwiftTail; break;
1852   case lltok::kw_x86_intrcc:     CC = CallingConv::X86_INTR; break;
1853   case lltok::kw_hhvmcc:         CC = CallingConv::HHVM; break;
1854   case lltok::kw_hhvm_ccc:       CC = CallingConv::HHVM_C; break;
1855   case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1856   case lltok::kw_amdgpu_vs:      CC = CallingConv::AMDGPU_VS; break;
1857   case lltok::kw_amdgpu_gfx:     CC = CallingConv::AMDGPU_Gfx; break;
1858   case lltok::kw_amdgpu_ls:      CC = CallingConv::AMDGPU_LS; break;
1859   case lltok::kw_amdgpu_hs:      CC = CallingConv::AMDGPU_HS; break;
1860   case lltok::kw_amdgpu_es:      CC = CallingConv::AMDGPU_ES; break;
1861   case lltok::kw_amdgpu_gs:      CC = CallingConv::AMDGPU_GS; break;
1862   case lltok::kw_amdgpu_ps:      CC = CallingConv::AMDGPU_PS; break;
1863   case lltok::kw_amdgpu_cs:      CC = CallingConv::AMDGPU_CS; break;
1864   case lltok::kw_amdgpu_kernel:  CC = CallingConv::AMDGPU_KERNEL; break;
1865   case lltok::kw_tailcc:         CC = CallingConv::Tail; break;
1866   case lltok::kw_cc: {
1867       Lex.Lex();
1868       return parseUInt32(CC);
1869     }
1870   }
1871 
1872   Lex.Lex();
1873   return false;
1874 }
1875 
1876 /// parseMetadataAttachment
1877 ///   ::= !dbg !42
1878 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1879   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1880 
1881   std::string Name = Lex.getStrVal();
1882   Kind = M->getMDKindID(Name);
1883   Lex.Lex();
1884 
1885   return parseMDNode(MD);
1886 }
1887 
1888 /// parseInstructionMetadata
1889 ///   ::= !dbg !42 (',' !dbg !57)*
1890 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
1891   do {
1892     if (Lex.getKind() != lltok::MetadataVar)
1893       return tokError("expected metadata after comma");
1894 
1895     unsigned MDK;
1896     MDNode *N;
1897     if (parseMetadataAttachment(MDK, N))
1898       return true;
1899 
1900     Inst.setMetadata(MDK, N);
1901     if (MDK == LLVMContext::MD_tbaa)
1902       InstsWithTBAATag.push_back(&Inst);
1903 
1904     // If this is the end of the list, we're done.
1905   } while (EatIfPresent(lltok::comma));
1906   return false;
1907 }
1908 
1909 /// parseGlobalObjectMetadataAttachment
1910 ///   ::= !dbg !57
1911 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1912   unsigned MDK;
1913   MDNode *N;
1914   if (parseMetadataAttachment(MDK, N))
1915     return true;
1916 
1917   GO.addMetadata(MDK, *N);
1918   return false;
1919 }
1920 
1921 /// parseOptionalFunctionMetadata
1922 ///   ::= (!dbg !57)*
1923 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
1924   while (Lex.getKind() == lltok::MetadataVar)
1925     if (parseGlobalObjectMetadataAttachment(F))
1926       return true;
1927   return false;
1928 }
1929 
1930 /// parseOptionalAlignment
1931 ///   ::= /* empty */
1932 ///   ::= 'align' 4
1933 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
1934   Alignment = None;
1935   if (!EatIfPresent(lltok::kw_align))
1936     return false;
1937   LocTy AlignLoc = Lex.getLoc();
1938   uint64_t Value = 0;
1939 
1940   LocTy ParenLoc = Lex.getLoc();
1941   bool HaveParens = false;
1942   if (AllowParens) {
1943     if (EatIfPresent(lltok::lparen))
1944       HaveParens = true;
1945   }
1946 
1947   if (parseUInt64(Value))
1948     return true;
1949 
1950   if (HaveParens && !EatIfPresent(lltok::rparen))
1951     return error(ParenLoc, "expected ')'");
1952 
1953   if (!isPowerOf2_64(Value))
1954     return error(AlignLoc, "alignment is not a power of two");
1955   if (Value > Value::MaximumAlignment)
1956     return error(AlignLoc, "huge alignments are not supported yet");
1957   Alignment = Align(Value);
1958   return false;
1959 }
1960 
1961 /// parseOptionalDerefAttrBytes
1962 ///   ::= /* empty */
1963 ///   ::= AttrKind '(' 4 ')'
1964 ///
1965 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1966 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1967                                            uint64_t &Bytes) {
1968   assert((AttrKind == lltok::kw_dereferenceable ||
1969           AttrKind == lltok::kw_dereferenceable_or_null) &&
1970          "contract!");
1971 
1972   Bytes = 0;
1973   if (!EatIfPresent(AttrKind))
1974     return false;
1975   LocTy ParenLoc = Lex.getLoc();
1976   if (!EatIfPresent(lltok::lparen))
1977     return error(ParenLoc, "expected '('");
1978   LocTy DerefLoc = Lex.getLoc();
1979   if (parseUInt64(Bytes))
1980     return true;
1981   ParenLoc = Lex.getLoc();
1982   if (!EatIfPresent(lltok::rparen))
1983     return error(ParenLoc, "expected ')'");
1984   if (!Bytes)
1985     return error(DerefLoc, "dereferenceable bytes must be non-zero");
1986   return false;
1987 }
1988 
1989 /// parseOptionalCommaAlign
1990 ///   ::=
1991 ///   ::= ',' align 4
1992 ///
1993 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1994 /// end.
1995 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
1996                                        bool &AteExtraComma) {
1997   AteExtraComma = false;
1998   while (EatIfPresent(lltok::comma)) {
1999     // Metadata at the end is an early exit.
2000     if (Lex.getKind() == lltok::MetadataVar) {
2001       AteExtraComma = true;
2002       return false;
2003     }
2004 
2005     if (Lex.getKind() != lltok::kw_align)
2006       return error(Lex.getLoc(), "expected metadata or 'align'");
2007 
2008     if (parseOptionalAlignment(Alignment))
2009       return true;
2010   }
2011 
2012   return false;
2013 }
2014 
2015 /// parseOptionalCommaAddrSpace
2016 ///   ::=
2017 ///   ::= ',' addrspace(1)
2018 ///
2019 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2020 /// end.
2021 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2022                                            bool &AteExtraComma) {
2023   AteExtraComma = false;
2024   while (EatIfPresent(lltok::comma)) {
2025     // Metadata at the end is an early exit.
2026     if (Lex.getKind() == lltok::MetadataVar) {
2027       AteExtraComma = true;
2028       return false;
2029     }
2030 
2031     Loc = Lex.getLoc();
2032     if (Lex.getKind() != lltok::kw_addrspace)
2033       return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2034 
2035     if (parseOptionalAddrSpace(AddrSpace))
2036       return true;
2037   }
2038 
2039   return false;
2040 }
2041 
2042 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2043                                        Optional<unsigned> &HowManyArg) {
2044   Lex.Lex();
2045 
2046   auto StartParen = Lex.getLoc();
2047   if (!EatIfPresent(lltok::lparen))
2048     return error(StartParen, "expected '('");
2049 
2050   if (parseUInt32(BaseSizeArg))
2051     return true;
2052 
2053   if (EatIfPresent(lltok::comma)) {
2054     auto HowManyAt = Lex.getLoc();
2055     unsigned HowMany;
2056     if (parseUInt32(HowMany))
2057       return true;
2058     if (HowMany == BaseSizeArg)
2059       return error(HowManyAt,
2060                    "'allocsize' indices can't refer to the same parameter");
2061     HowManyArg = HowMany;
2062   } else
2063     HowManyArg = None;
2064 
2065   auto EndParen = Lex.getLoc();
2066   if (!EatIfPresent(lltok::rparen))
2067     return error(EndParen, "expected ')'");
2068   return false;
2069 }
2070 
2071 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2072                                          unsigned &MaxValue) {
2073   Lex.Lex();
2074 
2075   auto StartParen = Lex.getLoc();
2076   if (!EatIfPresent(lltok::lparen))
2077     return error(StartParen, "expected '('");
2078 
2079   if (parseUInt32(MinValue))
2080     return true;
2081 
2082   if (EatIfPresent(lltok::comma)) {
2083     if (parseUInt32(MaxValue))
2084       return true;
2085   } else
2086     MaxValue = MinValue;
2087 
2088   auto EndParen = Lex.getLoc();
2089   if (!EatIfPresent(lltok::rparen))
2090     return error(EndParen, "expected ')'");
2091   return false;
2092 }
2093 
2094 /// parseScopeAndOrdering
2095 ///   if isAtomic: ::= SyncScope? AtomicOrdering
2096 ///   else: ::=
2097 ///
2098 /// This sets Scope and Ordering to the parsed values.
2099 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2100                                      AtomicOrdering &Ordering) {
2101   if (!IsAtomic)
2102     return false;
2103 
2104   return parseScope(SSID) || parseOrdering(Ordering);
2105 }
2106 
2107 /// parseScope
2108 ///   ::= syncscope("singlethread" | "<target scope>")?
2109 ///
2110 /// This sets synchronization scope ID to the ID of the parsed value.
2111 bool LLParser::parseScope(SyncScope::ID &SSID) {
2112   SSID = SyncScope::System;
2113   if (EatIfPresent(lltok::kw_syncscope)) {
2114     auto StartParenAt = Lex.getLoc();
2115     if (!EatIfPresent(lltok::lparen))
2116       return error(StartParenAt, "Expected '(' in syncscope");
2117 
2118     std::string SSN;
2119     auto SSNAt = Lex.getLoc();
2120     if (parseStringConstant(SSN))
2121       return error(SSNAt, "Expected synchronization scope name");
2122 
2123     auto EndParenAt = Lex.getLoc();
2124     if (!EatIfPresent(lltok::rparen))
2125       return error(EndParenAt, "Expected ')' in syncscope");
2126 
2127     SSID = Context.getOrInsertSyncScopeID(SSN);
2128   }
2129 
2130   return false;
2131 }
2132 
2133 /// parseOrdering
2134 ///   ::= AtomicOrdering
2135 ///
2136 /// This sets Ordering to the parsed value.
2137 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2138   switch (Lex.getKind()) {
2139   default:
2140     return tokError("Expected ordering on atomic instruction");
2141   case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2142   case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2143   // Not specified yet:
2144   // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2145   case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2146   case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2147   case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2148   case lltok::kw_seq_cst:
2149     Ordering = AtomicOrdering::SequentiallyConsistent;
2150     break;
2151   }
2152   Lex.Lex();
2153   return false;
2154 }
2155 
2156 /// parseOptionalStackAlignment
2157 ///   ::= /* empty */
2158 ///   ::= 'alignstack' '(' 4 ')'
2159 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2160   Alignment = 0;
2161   if (!EatIfPresent(lltok::kw_alignstack))
2162     return false;
2163   LocTy ParenLoc = Lex.getLoc();
2164   if (!EatIfPresent(lltok::lparen))
2165     return error(ParenLoc, "expected '('");
2166   LocTy AlignLoc = Lex.getLoc();
2167   if (parseUInt32(Alignment))
2168     return true;
2169   ParenLoc = Lex.getLoc();
2170   if (!EatIfPresent(lltok::rparen))
2171     return error(ParenLoc, "expected ')'");
2172   if (!isPowerOf2_32(Alignment))
2173     return error(AlignLoc, "stack alignment is not a power of two");
2174   return false;
2175 }
2176 
2177 /// parseIndexList - This parses the index list for an insert/extractvalue
2178 /// instruction.  This sets AteExtraComma in the case where we eat an extra
2179 /// comma at the end of the line and find that it is followed by metadata.
2180 /// Clients that don't allow metadata can call the version of this function that
2181 /// only takes one argument.
2182 ///
2183 /// parseIndexList
2184 ///    ::=  (',' uint32)+
2185 ///
2186 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2187                               bool &AteExtraComma) {
2188   AteExtraComma = false;
2189 
2190   if (Lex.getKind() != lltok::comma)
2191     return tokError("expected ',' as start of index list");
2192 
2193   while (EatIfPresent(lltok::comma)) {
2194     if (Lex.getKind() == lltok::MetadataVar) {
2195       if (Indices.empty())
2196         return tokError("expected index");
2197       AteExtraComma = true;
2198       return false;
2199     }
2200     unsigned Idx = 0;
2201     if (parseUInt32(Idx))
2202       return true;
2203     Indices.push_back(Idx);
2204   }
2205 
2206   return false;
2207 }
2208 
2209 //===----------------------------------------------------------------------===//
2210 // Type Parsing.
2211 //===----------------------------------------------------------------------===//
2212 
2213 /// parseType - parse a type.
2214 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2215   SMLoc TypeLoc = Lex.getLoc();
2216   switch (Lex.getKind()) {
2217   default:
2218     return tokError(Msg);
2219   case lltok::Type:
2220     // Type ::= 'float' | 'void' (etc)
2221     Result = Lex.getTyVal();
2222     Lex.Lex();
2223 
2224     // Handle "ptr" opaque pointer type.
2225     //
2226     // Type ::= ptr ('addrspace' '(' uint32 ')')?
2227     if (Result->isOpaquePointerTy()) {
2228       unsigned AddrSpace;
2229       if (parseOptionalAddrSpace(AddrSpace))
2230         return true;
2231       Result = PointerType::get(getContext(), AddrSpace);
2232 
2233       // Give a nice error for 'ptr*'.
2234       if (Lex.getKind() == lltok::star)
2235         return tokError("ptr* is invalid - use ptr instead");
2236 
2237       // Fall through to parsing the type suffixes only if this 'ptr' is a
2238       // function return. Otherwise, return success, implicitly rejecting other
2239       // suffixes.
2240       if (Lex.getKind() != lltok::lparen)
2241         return false;
2242     }
2243     break;
2244   case lltok::lbrace:
2245     // Type ::= StructType
2246     if (parseAnonStructType(Result, false))
2247       return true;
2248     break;
2249   case lltok::lsquare:
2250     // Type ::= '[' ... ']'
2251     Lex.Lex(); // eat the lsquare.
2252     if (parseArrayVectorType(Result, false))
2253       return true;
2254     break;
2255   case lltok::less: // Either vector or packed struct.
2256     // Type ::= '<' ... '>'
2257     Lex.Lex();
2258     if (Lex.getKind() == lltok::lbrace) {
2259       if (parseAnonStructType(Result, true) ||
2260           parseToken(lltok::greater, "expected '>' at end of packed struct"))
2261         return true;
2262     } else if (parseArrayVectorType(Result, true))
2263       return true;
2264     break;
2265   case lltok::LocalVar: {
2266     // Type ::= %foo
2267     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2268 
2269     // If the type hasn't been defined yet, create a forward definition and
2270     // remember where that forward def'n was seen (in case it never is defined).
2271     if (!Entry.first) {
2272       Entry.first = StructType::create(Context, Lex.getStrVal());
2273       Entry.second = Lex.getLoc();
2274     }
2275     Result = Entry.first;
2276     Lex.Lex();
2277     break;
2278   }
2279 
2280   case lltok::LocalVarID: {
2281     // Type ::= %4
2282     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2283 
2284     // If the type hasn't been defined yet, create a forward definition and
2285     // remember where that forward def'n was seen (in case it never is defined).
2286     if (!Entry.first) {
2287       Entry.first = StructType::create(Context);
2288       Entry.second = Lex.getLoc();
2289     }
2290     Result = Entry.first;
2291     Lex.Lex();
2292     break;
2293   }
2294   }
2295 
2296   // parse the type suffixes.
2297   while (true) {
2298     switch (Lex.getKind()) {
2299     // End of type.
2300     default:
2301       if (!AllowVoid && Result->isVoidTy())
2302         return error(TypeLoc, "void type only allowed for function results");
2303       return false;
2304 
2305     // Type ::= Type '*'
2306     case lltok::star:
2307       if (Result->isLabelTy())
2308         return tokError("basic block pointers are invalid");
2309       if (Result->isVoidTy())
2310         return tokError("pointers to void are invalid - use i8* instead");
2311       if (!PointerType::isValidElementType(Result))
2312         return tokError("pointer to this type is invalid");
2313       Result = PointerType::getUnqual(Result);
2314       Lex.Lex();
2315       break;
2316 
2317     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2318     case lltok::kw_addrspace: {
2319       if (Result->isLabelTy())
2320         return tokError("basic block pointers are invalid");
2321       if (Result->isVoidTy())
2322         return tokError("pointers to void are invalid; use i8* instead");
2323       if (!PointerType::isValidElementType(Result))
2324         return tokError("pointer to this type is invalid");
2325       unsigned AddrSpace;
2326       if (parseOptionalAddrSpace(AddrSpace) ||
2327           parseToken(lltok::star, "expected '*' in address space"))
2328         return true;
2329 
2330       Result = PointerType::get(Result, AddrSpace);
2331       break;
2332     }
2333 
2334     /// Types '(' ArgTypeListI ')' OptFuncAttrs
2335     case lltok::lparen:
2336       if (parseFunctionType(Result))
2337         return true;
2338       break;
2339     }
2340   }
2341 }
2342 
2343 /// parseParameterList
2344 ///    ::= '(' ')'
2345 ///    ::= '(' Arg (',' Arg)* ')'
2346 ///  Arg
2347 ///    ::= Type OptionalAttributes Value OptionalAttributes
2348 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2349                                   PerFunctionState &PFS, bool IsMustTailCall,
2350                                   bool InVarArgsFunc) {
2351   if (parseToken(lltok::lparen, "expected '(' in call"))
2352     return true;
2353 
2354   while (Lex.getKind() != lltok::rparen) {
2355     // If this isn't the first argument, we need a comma.
2356     if (!ArgList.empty() &&
2357         parseToken(lltok::comma, "expected ',' in argument list"))
2358       return true;
2359 
2360     // parse an ellipsis if this is a musttail call in a variadic function.
2361     if (Lex.getKind() == lltok::dotdotdot) {
2362       const char *Msg = "unexpected ellipsis in argument list for ";
2363       if (!IsMustTailCall)
2364         return tokError(Twine(Msg) + "non-musttail call");
2365       if (!InVarArgsFunc)
2366         return tokError(Twine(Msg) + "musttail call in non-varargs function");
2367       Lex.Lex();  // Lex the '...', it is purely for readability.
2368       return parseToken(lltok::rparen, "expected ')' at end of argument list");
2369     }
2370 
2371     // parse the argument.
2372     LocTy ArgLoc;
2373     Type *ArgTy = nullptr;
2374     AttrBuilder ArgAttrs;
2375     Value *V;
2376     if (parseType(ArgTy, ArgLoc))
2377       return true;
2378 
2379     if (ArgTy->isMetadataTy()) {
2380       if (parseMetadataAsValue(V, PFS))
2381         return true;
2382     } else {
2383       // Otherwise, handle normal operands.
2384       if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2385         return true;
2386     }
2387     ArgList.push_back(ParamInfo(
2388         ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2389   }
2390 
2391   if (IsMustTailCall && InVarArgsFunc)
2392     return tokError("expected '...' at end of argument list for musttail call "
2393                     "in varargs function");
2394 
2395   Lex.Lex();  // Lex the ')'.
2396   return false;
2397 }
2398 
2399 /// parseRequiredTypeAttr
2400 ///   ::= attrname(<ty>)
2401 bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2402                                      Attribute::AttrKind AttrKind) {
2403   Type *Ty = nullptr;
2404   if (!EatIfPresent(AttrToken))
2405     return true;
2406   if (!EatIfPresent(lltok::lparen))
2407     return error(Lex.getLoc(), "expected '('");
2408   if (parseType(Ty))
2409     return true;
2410   if (!EatIfPresent(lltok::rparen))
2411     return error(Lex.getLoc(), "expected ')'");
2412 
2413   B.addTypeAttr(AttrKind, Ty);
2414   return false;
2415 }
2416 
2417 /// parseOptionalOperandBundles
2418 ///    ::= /*empty*/
2419 ///    ::= '[' OperandBundle [, OperandBundle ]* ']'
2420 ///
2421 /// OperandBundle
2422 ///    ::= bundle-tag '(' ')'
2423 ///    ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2424 ///
2425 /// bundle-tag ::= String Constant
2426 bool LLParser::parseOptionalOperandBundles(
2427     SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2428   LocTy BeginLoc = Lex.getLoc();
2429   if (!EatIfPresent(lltok::lsquare))
2430     return false;
2431 
2432   while (Lex.getKind() != lltok::rsquare) {
2433     // If this isn't the first operand bundle, we need a comma.
2434     if (!BundleList.empty() &&
2435         parseToken(lltok::comma, "expected ',' in input list"))
2436       return true;
2437 
2438     std::string Tag;
2439     if (parseStringConstant(Tag))
2440       return true;
2441 
2442     if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2443       return true;
2444 
2445     std::vector<Value *> Inputs;
2446     while (Lex.getKind() != lltok::rparen) {
2447       // If this isn't the first input, we need a comma.
2448       if (!Inputs.empty() &&
2449           parseToken(lltok::comma, "expected ',' in input list"))
2450         return true;
2451 
2452       Type *Ty = nullptr;
2453       Value *Input = nullptr;
2454       if (parseType(Ty) || parseValue(Ty, Input, PFS))
2455         return true;
2456       Inputs.push_back(Input);
2457     }
2458 
2459     BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2460 
2461     Lex.Lex(); // Lex the ')'.
2462   }
2463 
2464   if (BundleList.empty())
2465     return error(BeginLoc, "operand bundle set must not be empty");
2466 
2467   Lex.Lex(); // Lex the ']'.
2468   return false;
2469 }
2470 
2471 /// parseArgumentList - parse the argument list for a function type or function
2472 /// prototype.
2473 ///   ::= '(' ArgTypeListI ')'
2474 /// ArgTypeListI
2475 ///   ::= /*empty*/
2476 ///   ::= '...'
2477 ///   ::= ArgTypeList ',' '...'
2478 ///   ::= ArgType (',' ArgType)*
2479 ///
2480 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2481                                  bool &IsVarArg) {
2482   unsigned CurValID = 0;
2483   IsVarArg = false;
2484   assert(Lex.getKind() == lltok::lparen);
2485   Lex.Lex(); // eat the (.
2486 
2487   if (Lex.getKind() == lltok::rparen) {
2488     // empty
2489   } else if (Lex.getKind() == lltok::dotdotdot) {
2490     IsVarArg = true;
2491     Lex.Lex();
2492   } else {
2493     LocTy TypeLoc = Lex.getLoc();
2494     Type *ArgTy = nullptr;
2495     AttrBuilder Attrs;
2496     std::string Name;
2497 
2498     if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2499       return true;
2500 
2501     if (ArgTy->isVoidTy())
2502       return error(TypeLoc, "argument can not have void type");
2503 
2504     if (Lex.getKind() == lltok::LocalVar) {
2505       Name = Lex.getStrVal();
2506       Lex.Lex();
2507     } else if (Lex.getKind() == lltok::LocalVarID) {
2508       if (Lex.getUIntVal() != CurValID)
2509         return error(TypeLoc, "argument expected to be numbered '%" +
2510                                   Twine(CurValID) + "'");
2511       ++CurValID;
2512       Lex.Lex();
2513     }
2514 
2515     if (!FunctionType::isValidArgumentType(ArgTy))
2516       return error(TypeLoc, "invalid type for function argument");
2517 
2518     ArgList.emplace_back(TypeLoc, ArgTy,
2519                          AttributeSet::get(ArgTy->getContext(), Attrs),
2520                          std::move(Name));
2521 
2522     while (EatIfPresent(lltok::comma)) {
2523       // Handle ... at end of arg list.
2524       if (EatIfPresent(lltok::dotdotdot)) {
2525         IsVarArg = true;
2526         break;
2527       }
2528 
2529       // Otherwise must be an argument type.
2530       TypeLoc = Lex.getLoc();
2531       if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2532         return true;
2533 
2534       if (ArgTy->isVoidTy())
2535         return error(TypeLoc, "argument can not have void type");
2536 
2537       if (Lex.getKind() == lltok::LocalVar) {
2538         Name = Lex.getStrVal();
2539         Lex.Lex();
2540       } else {
2541         if (Lex.getKind() == lltok::LocalVarID) {
2542           if (Lex.getUIntVal() != CurValID)
2543             return error(TypeLoc, "argument expected to be numbered '%" +
2544                                       Twine(CurValID) + "'");
2545           Lex.Lex();
2546         }
2547         ++CurValID;
2548         Name = "";
2549       }
2550 
2551       if (!ArgTy->isFirstClassType())
2552         return error(TypeLoc, "invalid type for function argument");
2553 
2554       ArgList.emplace_back(TypeLoc, ArgTy,
2555                            AttributeSet::get(ArgTy->getContext(), Attrs),
2556                            std::move(Name));
2557     }
2558   }
2559 
2560   return parseToken(lltok::rparen, "expected ')' at end of argument list");
2561 }
2562 
2563 /// parseFunctionType
2564 ///  ::= Type ArgumentList OptionalAttrs
2565 bool LLParser::parseFunctionType(Type *&Result) {
2566   assert(Lex.getKind() == lltok::lparen);
2567 
2568   if (!FunctionType::isValidReturnType(Result))
2569     return tokError("invalid function return type");
2570 
2571   SmallVector<ArgInfo, 8> ArgList;
2572   bool IsVarArg;
2573   if (parseArgumentList(ArgList, IsVarArg))
2574     return true;
2575 
2576   // Reject names on the arguments lists.
2577   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2578     if (!ArgList[i].Name.empty())
2579       return error(ArgList[i].Loc, "argument name invalid in function type");
2580     if (ArgList[i].Attrs.hasAttributes())
2581       return error(ArgList[i].Loc,
2582                    "argument attributes invalid in function type");
2583   }
2584 
2585   SmallVector<Type*, 16> ArgListTy;
2586   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2587     ArgListTy.push_back(ArgList[i].Ty);
2588 
2589   Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2590   return false;
2591 }
2592 
2593 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2594 /// other structs.
2595 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2596   SmallVector<Type*, 8> Elts;
2597   if (parseStructBody(Elts))
2598     return true;
2599 
2600   Result = StructType::get(Context, Elts, Packed);
2601   return false;
2602 }
2603 
2604 /// parseStructDefinition - parse a struct in a 'type' definition.
2605 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2606                                      std::pair<Type *, LocTy> &Entry,
2607                                      Type *&ResultTy) {
2608   // If the type was already defined, diagnose the redefinition.
2609   if (Entry.first && !Entry.second.isValid())
2610     return error(TypeLoc, "redefinition of type");
2611 
2612   // If we have opaque, just return without filling in the definition for the
2613   // struct.  This counts as a definition as far as the .ll file goes.
2614   if (EatIfPresent(lltok::kw_opaque)) {
2615     // This type is being defined, so clear the location to indicate this.
2616     Entry.second = SMLoc();
2617 
2618     // If this type number has never been uttered, create it.
2619     if (!Entry.first)
2620       Entry.first = StructType::create(Context, Name);
2621     ResultTy = Entry.first;
2622     return false;
2623   }
2624 
2625   // If the type starts with '<', then it is either a packed struct or a vector.
2626   bool isPacked = EatIfPresent(lltok::less);
2627 
2628   // If we don't have a struct, then we have a random type alias, which we
2629   // accept for compatibility with old files.  These types are not allowed to be
2630   // forward referenced and not allowed to be recursive.
2631   if (Lex.getKind() != lltok::lbrace) {
2632     if (Entry.first)
2633       return error(TypeLoc, "forward references to non-struct type");
2634 
2635     ResultTy = nullptr;
2636     if (isPacked)
2637       return parseArrayVectorType(ResultTy, true);
2638     return parseType(ResultTy);
2639   }
2640 
2641   // This type is being defined, so clear the location to indicate this.
2642   Entry.second = SMLoc();
2643 
2644   // If this type number has never been uttered, create it.
2645   if (!Entry.first)
2646     Entry.first = StructType::create(Context, Name);
2647 
2648   StructType *STy = cast<StructType>(Entry.first);
2649 
2650   SmallVector<Type*, 8> Body;
2651   if (parseStructBody(Body) ||
2652       (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2653     return true;
2654 
2655   STy->setBody(Body, isPacked);
2656   ResultTy = STy;
2657   return false;
2658 }
2659 
2660 /// parseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2661 ///   StructType
2662 ///     ::= '{' '}'
2663 ///     ::= '{' Type (',' Type)* '}'
2664 ///     ::= '<' '{' '}' '>'
2665 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2666 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2667   assert(Lex.getKind() == lltok::lbrace);
2668   Lex.Lex(); // Consume the '{'
2669 
2670   // Handle the empty struct.
2671   if (EatIfPresent(lltok::rbrace))
2672     return false;
2673 
2674   LocTy EltTyLoc = Lex.getLoc();
2675   Type *Ty = nullptr;
2676   if (parseType(Ty))
2677     return true;
2678   Body.push_back(Ty);
2679 
2680   if (!StructType::isValidElementType(Ty))
2681     return error(EltTyLoc, "invalid element type for struct");
2682 
2683   while (EatIfPresent(lltok::comma)) {
2684     EltTyLoc = Lex.getLoc();
2685     if (parseType(Ty))
2686       return true;
2687 
2688     if (!StructType::isValidElementType(Ty))
2689       return error(EltTyLoc, "invalid element type for struct");
2690 
2691     Body.push_back(Ty);
2692   }
2693 
2694   return parseToken(lltok::rbrace, "expected '}' at end of struct");
2695 }
2696 
2697 /// parseArrayVectorType - parse an array or vector type, assuming the first
2698 /// token has already been consumed.
2699 ///   Type
2700 ///     ::= '[' APSINTVAL 'x' Types ']'
2701 ///     ::= '<' APSINTVAL 'x' Types '>'
2702 ///     ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2703 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
2704   bool Scalable = false;
2705 
2706   if (IsVector && Lex.getKind() == lltok::kw_vscale) {
2707     Lex.Lex(); // consume the 'vscale'
2708     if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
2709       return true;
2710 
2711     Scalable = true;
2712   }
2713 
2714   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2715       Lex.getAPSIntVal().getBitWidth() > 64)
2716     return tokError("expected number in address space");
2717 
2718   LocTy SizeLoc = Lex.getLoc();
2719   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2720   Lex.Lex();
2721 
2722   if (parseToken(lltok::kw_x, "expected 'x' after element count"))
2723     return true;
2724 
2725   LocTy TypeLoc = Lex.getLoc();
2726   Type *EltTy = nullptr;
2727   if (parseType(EltTy))
2728     return true;
2729 
2730   if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
2731                  "expected end of sequential type"))
2732     return true;
2733 
2734   if (IsVector) {
2735     if (Size == 0)
2736       return error(SizeLoc, "zero element vector is illegal");
2737     if ((unsigned)Size != Size)
2738       return error(SizeLoc, "size too large for vector");
2739     if (!VectorType::isValidElementType(EltTy))
2740       return error(TypeLoc, "invalid vector element type");
2741     Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2742   } else {
2743     if (!ArrayType::isValidElementType(EltTy))
2744       return error(TypeLoc, "invalid array element type");
2745     Result = ArrayType::get(EltTy, Size);
2746   }
2747   return false;
2748 }
2749 
2750 //===----------------------------------------------------------------------===//
2751 // Function Semantic Analysis.
2752 //===----------------------------------------------------------------------===//
2753 
2754 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2755                                              int functionNumber)
2756   : P(p), F(f), FunctionNumber(functionNumber) {
2757 
2758   // Insert unnamed arguments into the NumberedVals list.
2759   for (Argument &A : F.args())
2760     if (!A.hasName())
2761       NumberedVals.push_back(&A);
2762 }
2763 
2764 LLParser::PerFunctionState::~PerFunctionState() {
2765   // If there were any forward referenced non-basicblock values, delete them.
2766 
2767   for (const auto &P : ForwardRefVals) {
2768     if (isa<BasicBlock>(P.second.first))
2769       continue;
2770     P.second.first->replaceAllUsesWith(
2771         UndefValue::get(P.second.first->getType()));
2772     P.second.first->deleteValue();
2773   }
2774 
2775   for (const auto &P : ForwardRefValIDs) {
2776     if (isa<BasicBlock>(P.second.first))
2777       continue;
2778     P.second.first->replaceAllUsesWith(
2779         UndefValue::get(P.second.first->getType()));
2780     P.second.first->deleteValue();
2781   }
2782 }
2783 
2784 bool LLParser::PerFunctionState::finishFunction() {
2785   if (!ForwardRefVals.empty())
2786     return P.error(ForwardRefVals.begin()->second.second,
2787                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2788                        "'");
2789   if (!ForwardRefValIDs.empty())
2790     return P.error(ForwardRefValIDs.begin()->second.second,
2791                    "use of undefined value '%" +
2792                        Twine(ForwardRefValIDs.begin()->first) + "'");
2793   return false;
2794 }
2795 
2796 /// getVal - Get a value with the specified name or ID, creating a
2797 /// forward reference record if needed.  This can return null if the value
2798 /// exists but does not have the right type.
2799 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
2800                                           LocTy Loc) {
2801   // Look this name up in the normal function symbol table.
2802   Value *Val = F.getValueSymbolTable()->lookup(Name);
2803 
2804   // If this is a forward reference for the value, see if we already created a
2805   // forward ref record.
2806   if (!Val) {
2807     auto I = ForwardRefVals.find(Name);
2808     if (I != ForwardRefVals.end())
2809       Val = I->second.first;
2810   }
2811 
2812   // If we have the value in the symbol table or fwd-ref table, return it.
2813   if (Val)
2814     return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
2815 
2816   // Don't make placeholders with invalid type.
2817   if (!Ty->isFirstClassType()) {
2818     P.error(Loc, "invalid use of a non-first-class type");
2819     return nullptr;
2820   }
2821 
2822   // Otherwise, create a new forward reference for this value and remember it.
2823   Value *FwdVal;
2824   if (Ty->isLabelTy()) {
2825     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2826   } else {
2827     FwdVal = new Argument(Ty, Name);
2828   }
2829 
2830   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2831   return FwdVal;
2832 }
2833 
2834 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
2835   // Look this name up in the normal function symbol table.
2836   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2837 
2838   // If this is a forward reference for the value, see if we already created a
2839   // forward ref record.
2840   if (!Val) {
2841     auto I = ForwardRefValIDs.find(ID);
2842     if (I != ForwardRefValIDs.end())
2843       Val = I->second.first;
2844   }
2845 
2846   // If we have the value in the symbol table or fwd-ref table, return it.
2847   if (Val)
2848     return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
2849 
2850   if (!Ty->isFirstClassType()) {
2851     P.error(Loc, "invalid use of a non-first-class type");
2852     return nullptr;
2853   }
2854 
2855   // Otherwise, create a new forward reference for this value and remember it.
2856   Value *FwdVal;
2857   if (Ty->isLabelTy()) {
2858     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2859   } else {
2860     FwdVal = new Argument(Ty);
2861   }
2862 
2863   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2864   return FwdVal;
2865 }
2866 
2867 /// setInstName - After an instruction is parsed and inserted into its
2868 /// basic block, this installs its name.
2869 bool LLParser::PerFunctionState::setInstName(int NameID,
2870                                              const std::string &NameStr,
2871                                              LocTy NameLoc, Instruction *Inst) {
2872   // If this instruction has void type, it cannot have a name or ID specified.
2873   if (Inst->getType()->isVoidTy()) {
2874     if (NameID != -1 || !NameStr.empty())
2875       return P.error(NameLoc, "instructions returning void cannot have a name");
2876     return false;
2877   }
2878 
2879   // If this was a numbered instruction, verify that the instruction is the
2880   // expected value and resolve any forward references.
2881   if (NameStr.empty()) {
2882     // If neither a name nor an ID was specified, just use the next ID.
2883     if (NameID == -1)
2884       NameID = NumberedVals.size();
2885 
2886     if (unsigned(NameID) != NumberedVals.size())
2887       return P.error(NameLoc, "instruction expected to be numbered '%" +
2888                                   Twine(NumberedVals.size()) + "'");
2889 
2890     auto FI = ForwardRefValIDs.find(NameID);
2891     if (FI != ForwardRefValIDs.end()) {
2892       Value *Sentinel = FI->second.first;
2893       if (Sentinel->getType() != Inst->getType())
2894         return P.error(NameLoc, "instruction forward referenced with type '" +
2895                                     getTypeString(FI->second.first->getType()) +
2896                                     "'");
2897 
2898       Sentinel->replaceAllUsesWith(Inst);
2899       Sentinel->deleteValue();
2900       ForwardRefValIDs.erase(FI);
2901     }
2902 
2903     NumberedVals.push_back(Inst);
2904     return false;
2905   }
2906 
2907   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2908   auto FI = ForwardRefVals.find(NameStr);
2909   if (FI != ForwardRefVals.end()) {
2910     Value *Sentinel = FI->second.first;
2911     if (Sentinel->getType() != Inst->getType())
2912       return P.error(NameLoc, "instruction forward referenced with type '" +
2913                                   getTypeString(FI->second.first->getType()) +
2914                                   "'");
2915 
2916     Sentinel->replaceAllUsesWith(Inst);
2917     Sentinel->deleteValue();
2918     ForwardRefVals.erase(FI);
2919   }
2920 
2921   // Set the name on the instruction.
2922   Inst->setName(NameStr);
2923 
2924   if (Inst->getName() != NameStr)
2925     return P.error(NameLoc, "multiple definition of local value named '" +
2926                                 NameStr + "'");
2927   return false;
2928 }
2929 
2930 /// getBB - Get a basic block with the specified name or ID, creating a
2931 /// forward reference record if needed.
2932 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
2933                                               LocTy Loc) {
2934   return dyn_cast_or_null<BasicBlock>(
2935       getVal(Name, Type::getLabelTy(F.getContext()), Loc));
2936 }
2937 
2938 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
2939   return dyn_cast_or_null<BasicBlock>(
2940       getVal(ID, Type::getLabelTy(F.getContext()), Loc));
2941 }
2942 
2943 /// defineBB - Define the specified basic block, which is either named or
2944 /// unnamed.  If there is an error, this returns null otherwise it returns
2945 /// the block being defined.
2946 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
2947                                                  int NameID, LocTy Loc) {
2948   BasicBlock *BB;
2949   if (Name.empty()) {
2950     if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
2951       P.error(Loc, "label expected to be numbered '" +
2952                        Twine(NumberedVals.size()) + "'");
2953       return nullptr;
2954     }
2955     BB = getBB(NumberedVals.size(), Loc);
2956     if (!BB) {
2957       P.error(Loc, "unable to create block numbered '" +
2958                        Twine(NumberedVals.size()) + "'");
2959       return nullptr;
2960     }
2961   } else {
2962     BB = getBB(Name, Loc);
2963     if (!BB) {
2964       P.error(Loc, "unable to create block named '" + Name + "'");
2965       return nullptr;
2966     }
2967   }
2968 
2969   // Move the block to the end of the function.  Forward ref'd blocks are
2970   // inserted wherever they happen to be referenced.
2971   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2972 
2973   // Remove the block from forward ref sets.
2974   if (Name.empty()) {
2975     ForwardRefValIDs.erase(NumberedVals.size());
2976     NumberedVals.push_back(BB);
2977   } else {
2978     // BB forward references are already in the function symbol table.
2979     ForwardRefVals.erase(Name);
2980   }
2981 
2982   return BB;
2983 }
2984 
2985 //===----------------------------------------------------------------------===//
2986 // Constants.
2987 //===----------------------------------------------------------------------===//
2988 
2989 /// parseValID - parse an abstract value that doesn't necessarily have a
2990 /// type implied.  For example, if we parse "4" we don't know what integer type
2991 /// it has.  The value will later be combined with its type and checked for
2992 /// sanity.  PFS is used to convert function-local operands of metadata (since
2993 /// metadata operands are not just parsed here but also converted to values).
2994 /// PFS can be null when we are not parsing metadata values inside a function.
2995 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
2996   ID.Loc = Lex.getLoc();
2997   switch (Lex.getKind()) {
2998   default:
2999     return tokError("expected value token");
3000   case lltok::GlobalID:  // @42
3001     ID.UIntVal = Lex.getUIntVal();
3002     ID.Kind = ValID::t_GlobalID;
3003     break;
3004   case lltok::GlobalVar:  // @foo
3005     ID.StrVal = Lex.getStrVal();
3006     ID.Kind = ValID::t_GlobalName;
3007     break;
3008   case lltok::LocalVarID:  // %42
3009     ID.UIntVal = Lex.getUIntVal();
3010     ID.Kind = ValID::t_LocalID;
3011     break;
3012   case lltok::LocalVar:  // %foo
3013     ID.StrVal = Lex.getStrVal();
3014     ID.Kind = ValID::t_LocalName;
3015     break;
3016   case lltok::APSInt:
3017     ID.APSIntVal = Lex.getAPSIntVal();
3018     ID.Kind = ValID::t_APSInt;
3019     break;
3020   case lltok::APFloat:
3021     ID.APFloatVal = Lex.getAPFloatVal();
3022     ID.Kind = ValID::t_APFloat;
3023     break;
3024   case lltok::kw_true:
3025     ID.ConstantVal = ConstantInt::getTrue(Context);
3026     ID.Kind = ValID::t_Constant;
3027     break;
3028   case lltok::kw_false:
3029     ID.ConstantVal = ConstantInt::getFalse(Context);
3030     ID.Kind = ValID::t_Constant;
3031     break;
3032   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3033   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3034   case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3035   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3036   case lltok::kw_none: ID.Kind = ValID::t_None; break;
3037 
3038   case lltok::lbrace: {
3039     // ValID ::= '{' ConstVector '}'
3040     Lex.Lex();
3041     SmallVector<Constant*, 16> Elts;
3042     if (parseGlobalValueVector(Elts) ||
3043         parseToken(lltok::rbrace, "expected end of struct constant"))
3044       return true;
3045 
3046     ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3047     ID.UIntVal = Elts.size();
3048     memcpy(ID.ConstantStructElts.get(), Elts.data(),
3049            Elts.size() * sizeof(Elts[0]));
3050     ID.Kind = ValID::t_ConstantStruct;
3051     return false;
3052   }
3053   case lltok::less: {
3054     // ValID ::= '<' ConstVector '>'         --> Vector.
3055     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3056     Lex.Lex();
3057     bool isPackedStruct = EatIfPresent(lltok::lbrace);
3058 
3059     SmallVector<Constant*, 16> Elts;
3060     LocTy FirstEltLoc = Lex.getLoc();
3061     if (parseGlobalValueVector(Elts) ||
3062         (isPackedStruct &&
3063          parseToken(lltok::rbrace, "expected end of packed struct")) ||
3064         parseToken(lltok::greater, "expected end of constant"))
3065       return true;
3066 
3067     if (isPackedStruct) {
3068       ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3069       memcpy(ID.ConstantStructElts.get(), Elts.data(),
3070              Elts.size() * sizeof(Elts[0]));
3071       ID.UIntVal = Elts.size();
3072       ID.Kind = ValID::t_PackedConstantStruct;
3073       return false;
3074     }
3075 
3076     if (Elts.empty())
3077       return error(ID.Loc, "constant vector must not be empty");
3078 
3079     if (!Elts[0]->getType()->isIntegerTy() &&
3080         !Elts[0]->getType()->isFloatingPointTy() &&
3081         !Elts[0]->getType()->isPointerTy())
3082       return error(
3083           FirstEltLoc,
3084           "vector elements must have integer, pointer or floating point type");
3085 
3086     // Verify that all the vector elements have the same type.
3087     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3088       if (Elts[i]->getType() != Elts[0]->getType())
3089         return error(FirstEltLoc, "vector element #" + Twine(i) +
3090                                       " is not of type '" +
3091                                       getTypeString(Elts[0]->getType()));
3092 
3093     ID.ConstantVal = ConstantVector::get(Elts);
3094     ID.Kind = ValID::t_Constant;
3095     return false;
3096   }
3097   case lltok::lsquare: {   // Array Constant
3098     Lex.Lex();
3099     SmallVector<Constant*, 16> Elts;
3100     LocTy FirstEltLoc = Lex.getLoc();
3101     if (parseGlobalValueVector(Elts) ||
3102         parseToken(lltok::rsquare, "expected end of array constant"))
3103       return true;
3104 
3105     // Handle empty element.
3106     if (Elts.empty()) {
3107       // Use undef instead of an array because it's inconvenient to determine
3108       // the element type at this point, there being no elements to examine.
3109       ID.Kind = ValID::t_EmptyArray;
3110       return false;
3111     }
3112 
3113     if (!Elts[0]->getType()->isFirstClassType())
3114       return error(FirstEltLoc, "invalid array element type: " +
3115                                     getTypeString(Elts[0]->getType()));
3116 
3117     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3118 
3119     // Verify all elements are correct type!
3120     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3121       if (Elts[i]->getType() != Elts[0]->getType())
3122         return error(FirstEltLoc, "array element #" + Twine(i) +
3123                                       " is not of type '" +
3124                                       getTypeString(Elts[0]->getType()));
3125     }
3126 
3127     ID.ConstantVal = ConstantArray::get(ATy, Elts);
3128     ID.Kind = ValID::t_Constant;
3129     return false;
3130   }
3131   case lltok::kw_c:  // c "foo"
3132     Lex.Lex();
3133     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3134                                                   false);
3135     if (parseToken(lltok::StringConstant, "expected string"))
3136       return true;
3137     ID.Kind = ValID::t_Constant;
3138     return false;
3139 
3140   case lltok::kw_asm: {
3141     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3142     //             STRINGCONSTANT
3143     bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3144     Lex.Lex();
3145     if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3146         parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3147         parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3148         parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3149         parseStringConstant(ID.StrVal) ||
3150         parseToken(lltok::comma, "expected comma in inline asm expression") ||
3151         parseToken(lltok::StringConstant, "expected constraint string"))
3152       return true;
3153     ID.StrVal2 = Lex.getStrVal();
3154     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3155                  (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3156     ID.Kind = ValID::t_InlineAsm;
3157     return false;
3158   }
3159 
3160   case lltok::kw_blockaddress: {
3161     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3162     Lex.Lex();
3163 
3164     ValID Fn, Label;
3165 
3166     if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3167         parseValID(Fn, PFS) ||
3168         parseToken(lltok::comma,
3169                    "expected comma in block address expression") ||
3170         parseValID(Label, PFS) ||
3171         parseToken(lltok::rparen, "expected ')' in block address expression"))
3172       return true;
3173 
3174     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3175       return error(Fn.Loc, "expected function name in blockaddress");
3176     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3177       return error(Label.Loc, "expected basic block name in blockaddress");
3178 
3179     // Try to find the function (but skip it if it's forward-referenced).
3180     GlobalValue *GV = nullptr;
3181     if (Fn.Kind == ValID::t_GlobalID) {
3182       if (Fn.UIntVal < NumberedVals.size())
3183         GV = NumberedVals[Fn.UIntVal];
3184     } else if (!ForwardRefVals.count(Fn.StrVal)) {
3185       GV = M->getNamedValue(Fn.StrVal);
3186     }
3187     Function *F = nullptr;
3188     if (GV) {
3189       // Confirm that it's actually a function with a definition.
3190       if (!isa<Function>(GV))
3191         return error(Fn.Loc, "expected function name in blockaddress");
3192       F = cast<Function>(GV);
3193       if (F->isDeclaration())
3194         return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3195     }
3196 
3197     if (!F) {
3198       // Make a global variable as a placeholder for this reference.
3199       GlobalValue *&FwdRef =
3200           ForwardRefBlockAddresses.insert(std::make_pair(
3201                                               std::move(Fn),
3202                                               std::map<ValID, GlobalValue *>()))
3203               .first->second.insert(std::make_pair(std::move(Label), nullptr))
3204               .first->second;
3205       if (!FwdRef) {
3206         unsigned FwdDeclAS;
3207         if (ExpectedTy) {
3208           // If we know the type that the blockaddress is being assigned to,
3209           // we can use the address space of that type.
3210           if (!ExpectedTy->isPointerTy())
3211             return error(ID.Loc,
3212                          "type of blockaddress must be a pointer and not '" +
3213                              getTypeString(ExpectedTy) + "'");
3214           FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3215         } else if (PFS) {
3216           // Otherwise, we default the address space of the current function.
3217           FwdDeclAS = PFS->getFunction().getAddressSpace();
3218         } else {
3219           llvm_unreachable("Unknown address space for blockaddress");
3220         }
3221         FwdRef = new GlobalVariable(
3222             *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3223             nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3224       }
3225 
3226       ID.ConstantVal = FwdRef;
3227       ID.Kind = ValID::t_Constant;
3228       return false;
3229     }
3230 
3231     // We found the function; now find the basic block.  Don't use PFS, since we
3232     // might be inside a constant expression.
3233     BasicBlock *BB;
3234     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3235       if (Label.Kind == ValID::t_LocalID)
3236         BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3237       else
3238         BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3239       if (!BB)
3240         return error(Label.Loc, "referenced value is not a basic block");
3241     } else {
3242       if (Label.Kind == ValID::t_LocalID)
3243         return error(Label.Loc, "cannot take address of numeric label after "
3244                                 "the function is defined");
3245       BB = dyn_cast_or_null<BasicBlock>(
3246           F->getValueSymbolTable()->lookup(Label.StrVal));
3247       if (!BB)
3248         return error(Label.Loc, "referenced value is not a basic block");
3249     }
3250 
3251     ID.ConstantVal = BlockAddress::get(F, BB);
3252     ID.Kind = ValID::t_Constant;
3253     return false;
3254   }
3255 
3256   case lltok::kw_dso_local_equivalent: {
3257     // ValID ::= 'dso_local_equivalent' @foo
3258     Lex.Lex();
3259 
3260     ValID Fn;
3261 
3262     if (parseValID(Fn, PFS))
3263       return true;
3264 
3265     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3266       return error(Fn.Loc,
3267                    "expected global value name in dso_local_equivalent");
3268 
3269     // Try to find the function (but skip it if it's forward-referenced).
3270     GlobalValue *GV = nullptr;
3271     if (Fn.Kind == ValID::t_GlobalID) {
3272       if (Fn.UIntVal < NumberedVals.size())
3273         GV = NumberedVals[Fn.UIntVal];
3274     } else if (!ForwardRefVals.count(Fn.StrVal)) {
3275       GV = M->getNamedValue(Fn.StrVal);
3276     }
3277 
3278     assert(GV && "Could not find a corresponding global variable");
3279 
3280     if (!GV->getValueType()->isFunctionTy())
3281       return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3282                            "in dso_local_equivalent");
3283 
3284     ID.ConstantVal = DSOLocalEquivalent::get(GV);
3285     ID.Kind = ValID::t_Constant;
3286     return false;
3287   }
3288 
3289   case lltok::kw_trunc:
3290   case lltok::kw_zext:
3291   case lltok::kw_sext:
3292   case lltok::kw_fptrunc:
3293   case lltok::kw_fpext:
3294   case lltok::kw_bitcast:
3295   case lltok::kw_addrspacecast:
3296   case lltok::kw_uitofp:
3297   case lltok::kw_sitofp:
3298   case lltok::kw_fptoui:
3299   case lltok::kw_fptosi:
3300   case lltok::kw_inttoptr:
3301   case lltok::kw_ptrtoint: {
3302     unsigned Opc = Lex.getUIntVal();
3303     Type *DestTy = nullptr;
3304     Constant *SrcVal;
3305     Lex.Lex();
3306     if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3307         parseGlobalTypeAndValue(SrcVal) ||
3308         parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3309         parseType(DestTy) ||
3310         parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3311       return true;
3312     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3313       return error(ID.Loc, "invalid cast opcode for cast from '" +
3314                                getTypeString(SrcVal->getType()) + "' to '" +
3315                                getTypeString(DestTy) + "'");
3316     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3317                                                  SrcVal, DestTy);
3318     ID.Kind = ValID::t_Constant;
3319     return false;
3320   }
3321   case lltok::kw_extractvalue: {
3322     Lex.Lex();
3323     Constant *Val;
3324     SmallVector<unsigned, 4> Indices;
3325     if (parseToken(lltok::lparen,
3326                    "expected '(' in extractvalue constantexpr") ||
3327         parseGlobalTypeAndValue(Val) || parseIndexList(Indices) ||
3328         parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3329       return true;
3330 
3331     if (!Val->getType()->isAggregateType())
3332       return error(ID.Loc, "extractvalue operand must be aggregate type");
3333     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3334       return error(ID.Loc, "invalid indices for extractvalue");
3335     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3336     ID.Kind = ValID::t_Constant;
3337     return false;
3338   }
3339   case lltok::kw_insertvalue: {
3340     Lex.Lex();
3341     Constant *Val0, *Val1;
3342     SmallVector<unsigned, 4> Indices;
3343     if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") ||
3344         parseGlobalTypeAndValue(Val0) ||
3345         parseToken(lltok::comma,
3346                    "expected comma in insertvalue constantexpr") ||
3347         parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) ||
3348         parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3349       return true;
3350     if (!Val0->getType()->isAggregateType())
3351       return error(ID.Loc, "insertvalue operand must be aggregate type");
3352     Type *IndexedType =
3353         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3354     if (!IndexedType)
3355       return error(ID.Loc, "invalid indices for insertvalue");
3356     if (IndexedType != Val1->getType())
3357       return error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3358                                getTypeString(Val1->getType()) +
3359                                "' instead of '" + getTypeString(IndexedType) +
3360                                "'");
3361     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3362     ID.Kind = ValID::t_Constant;
3363     return false;
3364   }
3365   case lltok::kw_icmp:
3366   case lltok::kw_fcmp: {
3367     unsigned PredVal, Opc = Lex.getUIntVal();
3368     Constant *Val0, *Val1;
3369     Lex.Lex();
3370     if (parseCmpPredicate(PredVal, Opc) ||
3371         parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3372         parseGlobalTypeAndValue(Val0) ||
3373         parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3374         parseGlobalTypeAndValue(Val1) ||
3375         parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3376       return true;
3377 
3378     if (Val0->getType() != Val1->getType())
3379       return error(ID.Loc, "compare operands must have the same type");
3380 
3381     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3382 
3383     if (Opc == Instruction::FCmp) {
3384       if (!Val0->getType()->isFPOrFPVectorTy())
3385         return error(ID.Loc, "fcmp requires floating point operands");
3386       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3387     } else {
3388       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3389       if (!Val0->getType()->isIntOrIntVectorTy() &&
3390           !Val0->getType()->isPtrOrPtrVectorTy())
3391         return error(ID.Loc, "icmp requires pointer or integer operands");
3392       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3393     }
3394     ID.Kind = ValID::t_Constant;
3395     return false;
3396   }
3397 
3398   // Unary Operators.
3399   case lltok::kw_fneg: {
3400     unsigned Opc = Lex.getUIntVal();
3401     Constant *Val;
3402     Lex.Lex();
3403     if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3404         parseGlobalTypeAndValue(Val) ||
3405         parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3406       return true;
3407 
3408     // Check that the type is valid for the operator.
3409     switch (Opc) {
3410     case Instruction::FNeg:
3411       if (!Val->getType()->isFPOrFPVectorTy())
3412         return error(ID.Loc, "constexpr requires fp operands");
3413       break;
3414     default: llvm_unreachable("Unknown unary operator!");
3415     }
3416     unsigned Flags = 0;
3417     Constant *C = ConstantExpr::get(Opc, Val, Flags);
3418     ID.ConstantVal = C;
3419     ID.Kind = ValID::t_Constant;
3420     return false;
3421   }
3422   // Binary Operators.
3423   case lltok::kw_add:
3424   case lltok::kw_fadd:
3425   case lltok::kw_sub:
3426   case lltok::kw_fsub:
3427   case lltok::kw_mul:
3428   case lltok::kw_fmul:
3429   case lltok::kw_udiv:
3430   case lltok::kw_sdiv:
3431   case lltok::kw_fdiv:
3432   case lltok::kw_urem:
3433   case lltok::kw_srem:
3434   case lltok::kw_frem:
3435   case lltok::kw_shl:
3436   case lltok::kw_lshr:
3437   case lltok::kw_ashr: {
3438     bool NUW = false;
3439     bool NSW = false;
3440     bool Exact = false;
3441     unsigned Opc = Lex.getUIntVal();
3442     Constant *Val0, *Val1;
3443     Lex.Lex();
3444     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3445         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3446       if (EatIfPresent(lltok::kw_nuw))
3447         NUW = true;
3448       if (EatIfPresent(lltok::kw_nsw)) {
3449         NSW = true;
3450         if (EatIfPresent(lltok::kw_nuw))
3451           NUW = true;
3452       }
3453     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3454                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3455       if (EatIfPresent(lltok::kw_exact))
3456         Exact = true;
3457     }
3458     if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3459         parseGlobalTypeAndValue(Val0) ||
3460         parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3461         parseGlobalTypeAndValue(Val1) ||
3462         parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3463       return true;
3464     if (Val0->getType() != Val1->getType())
3465       return error(ID.Loc, "operands of constexpr must have same type");
3466     // Check that the type is valid for the operator.
3467     switch (Opc) {
3468     case Instruction::Add:
3469     case Instruction::Sub:
3470     case Instruction::Mul:
3471     case Instruction::UDiv:
3472     case Instruction::SDiv:
3473     case Instruction::URem:
3474     case Instruction::SRem:
3475     case Instruction::Shl:
3476     case Instruction::AShr:
3477     case Instruction::LShr:
3478       if (!Val0->getType()->isIntOrIntVectorTy())
3479         return error(ID.Loc, "constexpr requires integer operands");
3480       break;
3481     case Instruction::FAdd:
3482     case Instruction::FSub:
3483     case Instruction::FMul:
3484     case Instruction::FDiv:
3485     case Instruction::FRem:
3486       if (!Val0->getType()->isFPOrFPVectorTy())
3487         return error(ID.Loc, "constexpr requires fp operands");
3488       break;
3489     default: llvm_unreachable("Unknown binary operator!");
3490     }
3491     unsigned Flags = 0;
3492     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3493     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3494     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3495     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3496     ID.ConstantVal = C;
3497     ID.Kind = ValID::t_Constant;
3498     return false;
3499   }
3500 
3501   // Logical Operations
3502   case lltok::kw_and:
3503   case lltok::kw_or:
3504   case lltok::kw_xor: {
3505     unsigned Opc = Lex.getUIntVal();
3506     Constant *Val0, *Val1;
3507     Lex.Lex();
3508     if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3509         parseGlobalTypeAndValue(Val0) ||
3510         parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3511         parseGlobalTypeAndValue(Val1) ||
3512         parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3513       return true;
3514     if (Val0->getType() != Val1->getType())
3515       return error(ID.Loc, "operands of constexpr must have same type");
3516     if (!Val0->getType()->isIntOrIntVectorTy())
3517       return error(ID.Loc,
3518                    "constexpr requires integer or integer vector operands");
3519     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3520     ID.Kind = ValID::t_Constant;
3521     return false;
3522   }
3523 
3524   case lltok::kw_getelementptr:
3525   case lltok::kw_shufflevector:
3526   case lltok::kw_insertelement:
3527   case lltok::kw_extractelement:
3528   case lltok::kw_select: {
3529     unsigned Opc = Lex.getUIntVal();
3530     SmallVector<Constant*, 16> Elts;
3531     bool InBounds = false;
3532     Type *Ty;
3533     Lex.Lex();
3534 
3535     if (Opc == Instruction::GetElementPtr)
3536       InBounds = EatIfPresent(lltok::kw_inbounds);
3537 
3538     if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3539       return true;
3540 
3541     LocTy ExplicitTypeLoc = Lex.getLoc();
3542     if (Opc == Instruction::GetElementPtr) {
3543       if (parseType(Ty) ||
3544           parseToken(lltok::comma, "expected comma after getelementptr's type"))
3545         return true;
3546     }
3547 
3548     Optional<unsigned> InRangeOp;
3549     if (parseGlobalValueVector(
3550             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3551         parseToken(lltok::rparen, "expected ')' in constantexpr"))
3552       return true;
3553 
3554     if (Opc == Instruction::GetElementPtr) {
3555       if (Elts.size() == 0 ||
3556           !Elts[0]->getType()->isPtrOrPtrVectorTy())
3557         return error(ID.Loc, "base of getelementptr must be a pointer");
3558 
3559       Type *BaseType = Elts[0]->getType();
3560       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3561       if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
3562         return error(
3563             ExplicitTypeLoc,
3564             typeComparisonErrorMessage(
3565                 "explicit pointee type doesn't match operand's pointee type",
3566                 Ty, BasePointerType->getElementType()));
3567       }
3568 
3569       unsigned GEPWidth =
3570           BaseType->isVectorTy()
3571               ? cast<FixedVectorType>(BaseType)->getNumElements()
3572               : 0;
3573 
3574       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3575       for (Constant *Val : Indices) {
3576         Type *ValTy = Val->getType();
3577         if (!ValTy->isIntOrIntVectorTy())
3578           return error(ID.Loc, "getelementptr index must be an integer");
3579         if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3580           unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3581           if (GEPWidth && (ValNumEl != GEPWidth))
3582             return error(
3583                 ID.Loc,
3584                 "getelementptr vector index has a wrong number of elements");
3585           // GEPWidth may have been unknown because the base is a scalar,
3586           // but it is known now.
3587           GEPWidth = ValNumEl;
3588         }
3589       }
3590 
3591       SmallPtrSet<Type*, 4> Visited;
3592       if (!Indices.empty() && !Ty->isSized(&Visited))
3593         return error(ID.Loc, "base element of getelementptr must be sized");
3594 
3595       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3596         return error(ID.Loc, "invalid getelementptr indices");
3597 
3598       if (InRangeOp) {
3599         if (*InRangeOp == 0)
3600           return error(ID.Loc,
3601                        "inrange keyword may not appear on pointer operand");
3602         --*InRangeOp;
3603       }
3604 
3605       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3606                                                       InBounds, InRangeOp);
3607     } else if (Opc == Instruction::Select) {
3608       if (Elts.size() != 3)
3609         return error(ID.Loc, "expected three operands to select");
3610       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3611                                                               Elts[2]))
3612         return error(ID.Loc, Reason);
3613       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3614     } else if (Opc == Instruction::ShuffleVector) {
3615       if (Elts.size() != 3)
3616         return error(ID.Loc, "expected three operands to shufflevector");
3617       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3618         return error(ID.Loc, "invalid operands to shufflevector");
3619       SmallVector<int, 16> Mask;
3620       ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3621       ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3622     } else if (Opc == Instruction::ExtractElement) {
3623       if (Elts.size() != 2)
3624         return error(ID.Loc, "expected two operands to extractelement");
3625       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3626         return error(ID.Loc, "invalid extractelement operands");
3627       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3628     } else {
3629       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3630       if (Elts.size() != 3)
3631         return error(ID.Loc, "expected three operands to insertelement");
3632       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3633         return error(ID.Loc, "invalid insertelement operands");
3634       ID.ConstantVal =
3635                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3636     }
3637 
3638     ID.Kind = ValID::t_Constant;
3639     return false;
3640   }
3641   }
3642 
3643   Lex.Lex();
3644   return false;
3645 }
3646 
3647 /// parseGlobalValue - parse a global value with the specified type.
3648 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3649   C = nullptr;
3650   ValID ID;
3651   Value *V = nullptr;
3652   bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
3653                 convertValIDToValue(Ty, ID, V, nullptr);
3654   if (V && !(C = dyn_cast<Constant>(V)))
3655     return error(ID.Loc, "global values must be constants");
3656   return Parsed;
3657 }
3658 
3659 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3660   Type *Ty = nullptr;
3661   return parseType(Ty) || parseGlobalValue(Ty, V);
3662 }
3663 
3664 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3665   C = nullptr;
3666 
3667   LocTy KwLoc = Lex.getLoc();
3668   if (!EatIfPresent(lltok::kw_comdat))
3669     return false;
3670 
3671   if (EatIfPresent(lltok::lparen)) {
3672     if (Lex.getKind() != lltok::ComdatVar)
3673       return tokError("expected comdat variable");
3674     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3675     Lex.Lex();
3676     if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3677       return true;
3678   } else {
3679     if (GlobalName.empty())
3680       return tokError("comdat cannot be unnamed");
3681     C = getComdat(std::string(GlobalName), KwLoc);
3682   }
3683 
3684   return false;
3685 }
3686 
3687 /// parseGlobalValueVector
3688 ///   ::= /*empty*/
3689 ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3690 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3691                                       Optional<unsigned> *InRangeOp) {
3692   // Empty list.
3693   if (Lex.getKind() == lltok::rbrace ||
3694       Lex.getKind() == lltok::rsquare ||
3695       Lex.getKind() == lltok::greater ||
3696       Lex.getKind() == lltok::rparen)
3697     return false;
3698 
3699   do {
3700     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3701       *InRangeOp = Elts.size();
3702 
3703     Constant *C;
3704     if (parseGlobalTypeAndValue(C))
3705       return true;
3706     Elts.push_back(C);
3707   } while (EatIfPresent(lltok::comma));
3708 
3709   return false;
3710 }
3711 
3712 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3713   SmallVector<Metadata *, 16> Elts;
3714   if (parseMDNodeVector(Elts))
3715     return true;
3716 
3717   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3718   return false;
3719 }
3720 
3721 /// MDNode:
3722 ///  ::= !{ ... }
3723 ///  ::= !7
3724 ///  ::= !DILocation(...)
3725 bool LLParser::parseMDNode(MDNode *&N) {
3726   if (Lex.getKind() == lltok::MetadataVar)
3727     return parseSpecializedMDNode(N);
3728 
3729   return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3730 }
3731 
3732 bool LLParser::parseMDNodeTail(MDNode *&N) {
3733   // !{ ... }
3734   if (Lex.getKind() == lltok::lbrace)
3735     return parseMDTuple(N);
3736 
3737   // !42
3738   return parseMDNodeID(N);
3739 }
3740 
3741 namespace {
3742 
3743 /// Structure to represent an optional metadata field.
3744 template <class FieldTy> struct MDFieldImpl {
3745   typedef MDFieldImpl ImplTy;
3746   FieldTy Val;
3747   bool Seen;
3748 
3749   void assign(FieldTy Val) {
3750     Seen = true;
3751     this->Val = std::move(Val);
3752   }
3753 
3754   explicit MDFieldImpl(FieldTy Default)
3755       : Val(std::move(Default)), Seen(false) {}
3756 };
3757 
3758 /// Structure to represent an optional metadata field that
3759 /// can be of either type (A or B) and encapsulates the
3760 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3761 /// to reimplement the specifics for representing each Field.
3762 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3763   typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3764   FieldTypeA A;
3765   FieldTypeB B;
3766   bool Seen;
3767 
3768   enum {
3769     IsInvalid = 0,
3770     IsTypeA = 1,
3771     IsTypeB = 2
3772   } WhatIs;
3773 
3774   void assign(FieldTypeA A) {
3775     Seen = true;
3776     this->A = std::move(A);
3777     WhatIs = IsTypeA;
3778   }
3779 
3780   void assign(FieldTypeB B) {
3781     Seen = true;
3782     this->B = std::move(B);
3783     WhatIs = IsTypeB;
3784   }
3785 
3786   explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3787       : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3788         WhatIs(IsInvalid) {}
3789 };
3790 
3791 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3792   uint64_t Max;
3793 
3794   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3795       : ImplTy(Default), Max(Max) {}
3796 };
3797 
3798 struct LineField : public MDUnsignedField {
3799   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3800 };
3801 
3802 struct ColumnField : public MDUnsignedField {
3803   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3804 };
3805 
3806 struct DwarfTagField : public MDUnsignedField {
3807   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3808   DwarfTagField(dwarf::Tag DefaultTag)
3809       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3810 };
3811 
3812 struct DwarfMacinfoTypeField : public MDUnsignedField {
3813   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3814   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3815     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3816 };
3817 
3818 struct DwarfAttEncodingField : public MDUnsignedField {
3819   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3820 };
3821 
3822 struct DwarfVirtualityField : public MDUnsignedField {
3823   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3824 };
3825 
3826 struct DwarfLangField : public MDUnsignedField {
3827   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3828 };
3829 
3830 struct DwarfCCField : public MDUnsignedField {
3831   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3832 };
3833 
3834 struct EmissionKindField : public MDUnsignedField {
3835   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3836 };
3837 
3838 struct NameTableKindField : public MDUnsignedField {
3839   NameTableKindField()
3840       : MDUnsignedField(
3841             0, (unsigned)
3842                    DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3843 };
3844 
3845 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3846   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3847 };
3848 
3849 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3850   DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3851 };
3852 
3853 struct MDAPSIntField : public MDFieldImpl<APSInt> {
3854   MDAPSIntField() : ImplTy(APSInt()) {}
3855 };
3856 
3857 struct MDSignedField : public MDFieldImpl<int64_t> {
3858   int64_t Min;
3859   int64_t Max;
3860 
3861   MDSignedField(int64_t Default = 0)
3862       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3863   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3864       : ImplTy(Default), Min(Min), Max(Max) {}
3865 };
3866 
3867 struct MDBoolField : public MDFieldImpl<bool> {
3868   MDBoolField(bool Default = false) : ImplTy(Default) {}
3869 };
3870 
3871 struct MDField : public MDFieldImpl<Metadata *> {
3872   bool AllowNull;
3873 
3874   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3875 };
3876 
3877 struct MDStringField : public MDFieldImpl<MDString *> {
3878   bool AllowEmpty;
3879   MDStringField(bool AllowEmpty = true)
3880       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3881 };
3882 
3883 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3884   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3885 };
3886 
3887 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3888   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3889 };
3890 
3891 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3892   MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3893       : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3894 
3895   MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3896                     bool AllowNull = true)
3897       : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3898 
3899   bool isMDSignedField() const { return WhatIs == IsTypeA; }
3900   bool isMDField() const { return WhatIs == IsTypeB; }
3901   int64_t getMDSignedValue() const {
3902     assert(isMDSignedField() && "Wrong field type");
3903     return A.Val;
3904   }
3905   Metadata *getMDFieldValue() const {
3906     assert(isMDField() && "Wrong field type");
3907     return B.Val;
3908   }
3909 };
3910 
3911 } // end anonymous namespace
3912 
3913 namespace llvm {
3914 
3915 template <>
3916 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
3917   if (Lex.getKind() != lltok::APSInt)
3918     return tokError("expected integer");
3919 
3920   Result.assign(Lex.getAPSIntVal());
3921   Lex.Lex();
3922   return false;
3923 }
3924 
3925 template <>
3926 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
3927                             MDUnsignedField &Result) {
3928   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3929     return tokError("expected unsigned integer");
3930 
3931   auto &U = Lex.getAPSIntVal();
3932   if (U.ugt(Result.Max))
3933     return tokError("value for '" + Name + "' too large, limit is " +
3934                     Twine(Result.Max));
3935   Result.assign(U.getZExtValue());
3936   assert(Result.Val <= Result.Max && "Expected value in range");
3937   Lex.Lex();
3938   return false;
3939 }
3940 
3941 template <>
3942 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3943   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3944 }
3945 template <>
3946 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3947   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3948 }
3949 
3950 template <>
3951 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3952   if (Lex.getKind() == lltok::APSInt)
3953     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3954 
3955   if (Lex.getKind() != lltok::DwarfTag)
3956     return tokError("expected DWARF tag");
3957 
3958   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3959   if (Tag == dwarf::DW_TAG_invalid)
3960     return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3961   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3962 
3963   Result.assign(Tag);
3964   Lex.Lex();
3965   return false;
3966 }
3967 
3968 template <>
3969 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
3970                             DwarfMacinfoTypeField &Result) {
3971   if (Lex.getKind() == lltok::APSInt)
3972     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3973 
3974   if (Lex.getKind() != lltok::DwarfMacinfo)
3975     return tokError("expected DWARF macinfo type");
3976 
3977   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3978   if (Macinfo == dwarf::DW_MACINFO_invalid)
3979     return tokError("invalid DWARF macinfo type" + Twine(" '") +
3980                     Lex.getStrVal() + "'");
3981   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3982 
3983   Result.assign(Macinfo);
3984   Lex.Lex();
3985   return false;
3986 }
3987 
3988 template <>
3989 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
3990                             DwarfVirtualityField &Result) {
3991   if (Lex.getKind() == lltok::APSInt)
3992     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3993 
3994   if (Lex.getKind() != lltok::DwarfVirtuality)
3995     return tokError("expected DWARF virtuality code");
3996 
3997   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3998   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3999     return tokError("invalid DWARF virtuality code" + Twine(" '") +
4000                     Lex.getStrVal() + "'");
4001   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4002   Result.assign(Virtuality);
4003   Lex.Lex();
4004   return false;
4005 }
4006 
4007 template <>
4008 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4009   if (Lex.getKind() == lltok::APSInt)
4010     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4011 
4012   if (Lex.getKind() != lltok::DwarfLang)
4013     return tokError("expected DWARF language");
4014 
4015   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4016   if (!Lang)
4017     return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4018                     "'");
4019   assert(Lang <= Result.Max && "Expected valid DWARF language");
4020   Result.assign(Lang);
4021   Lex.Lex();
4022   return false;
4023 }
4024 
4025 template <>
4026 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4027   if (Lex.getKind() == lltok::APSInt)
4028     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4029 
4030   if (Lex.getKind() != lltok::DwarfCC)
4031     return tokError("expected DWARF calling convention");
4032 
4033   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4034   if (!CC)
4035     return tokError("invalid DWARF calling convention" + Twine(" '") +
4036                     Lex.getStrVal() + "'");
4037   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4038   Result.assign(CC);
4039   Lex.Lex();
4040   return false;
4041 }
4042 
4043 template <>
4044 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4045                             EmissionKindField &Result) {
4046   if (Lex.getKind() == lltok::APSInt)
4047     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4048 
4049   if (Lex.getKind() != lltok::EmissionKind)
4050     return tokError("expected emission kind");
4051 
4052   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4053   if (!Kind)
4054     return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4055                     "'");
4056   assert(*Kind <= Result.Max && "Expected valid emission kind");
4057   Result.assign(*Kind);
4058   Lex.Lex();
4059   return false;
4060 }
4061 
4062 template <>
4063 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4064                             NameTableKindField &Result) {
4065   if (Lex.getKind() == lltok::APSInt)
4066     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4067 
4068   if (Lex.getKind() != lltok::NameTableKind)
4069     return tokError("expected nameTable kind");
4070 
4071   auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4072   if (!Kind)
4073     return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4074                     "'");
4075   assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4076   Result.assign((unsigned)*Kind);
4077   Lex.Lex();
4078   return false;
4079 }
4080 
4081 template <>
4082 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4083                             DwarfAttEncodingField &Result) {
4084   if (Lex.getKind() == lltok::APSInt)
4085     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4086 
4087   if (Lex.getKind() != lltok::DwarfAttEncoding)
4088     return tokError("expected DWARF type attribute encoding");
4089 
4090   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4091   if (!Encoding)
4092     return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4093                     Lex.getStrVal() + "'");
4094   assert(Encoding <= Result.Max && "Expected valid DWARF language");
4095   Result.assign(Encoding);
4096   Lex.Lex();
4097   return false;
4098 }
4099 
4100 /// DIFlagField
4101 ///  ::= uint32
4102 ///  ::= DIFlagVector
4103 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4104 template <>
4105 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4106 
4107   // parser for a single flag.
4108   auto parseFlag = [&](DINode::DIFlags &Val) {
4109     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4110       uint32_t TempVal = static_cast<uint32_t>(Val);
4111       bool Res = parseUInt32(TempVal);
4112       Val = static_cast<DINode::DIFlags>(TempVal);
4113       return Res;
4114     }
4115 
4116     if (Lex.getKind() != lltok::DIFlag)
4117       return tokError("expected debug info flag");
4118 
4119     Val = DINode::getFlag(Lex.getStrVal());
4120     if (!Val)
4121       return tokError(Twine("invalid debug info flag flag '") +
4122                       Lex.getStrVal() + "'");
4123     Lex.Lex();
4124     return false;
4125   };
4126 
4127   // parse the flags and combine them together.
4128   DINode::DIFlags Combined = DINode::FlagZero;
4129   do {
4130     DINode::DIFlags Val;
4131     if (parseFlag(Val))
4132       return true;
4133     Combined |= Val;
4134   } while (EatIfPresent(lltok::bar));
4135 
4136   Result.assign(Combined);
4137   return false;
4138 }
4139 
4140 /// DISPFlagField
4141 ///  ::= uint32
4142 ///  ::= DISPFlagVector
4143 ///  ::= DISPFlagVector '|' DISPFlag* '|' uint32
4144 template <>
4145 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4146 
4147   // parser for a single flag.
4148   auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4149     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4150       uint32_t TempVal = static_cast<uint32_t>(Val);
4151       bool Res = parseUInt32(TempVal);
4152       Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4153       return Res;
4154     }
4155 
4156     if (Lex.getKind() != lltok::DISPFlag)
4157       return tokError("expected debug info flag");
4158 
4159     Val = DISubprogram::getFlag(Lex.getStrVal());
4160     if (!Val)
4161       return tokError(Twine("invalid subprogram debug info flag '") +
4162                       Lex.getStrVal() + "'");
4163     Lex.Lex();
4164     return false;
4165   };
4166 
4167   // parse the flags and combine them together.
4168   DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4169   do {
4170     DISubprogram::DISPFlags Val;
4171     if (parseFlag(Val))
4172       return true;
4173     Combined |= Val;
4174   } while (EatIfPresent(lltok::bar));
4175 
4176   Result.assign(Combined);
4177   return false;
4178 }
4179 
4180 template <>
4181 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4182   if (Lex.getKind() != lltok::APSInt)
4183     return tokError("expected signed integer");
4184 
4185   auto &S = Lex.getAPSIntVal();
4186   if (S < Result.Min)
4187     return tokError("value for '" + Name + "' too small, limit is " +
4188                     Twine(Result.Min));
4189   if (S > Result.Max)
4190     return tokError("value for '" + Name + "' too large, limit is " +
4191                     Twine(Result.Max));
4192   Result.assign(S.getExtValue());
4193   assert(Result.Val >= Result.Min && "Expected value in range");
4194   assert(Result.Val <= Result.Max && "Expected value in range");
4195   Lex.Lex();
4196   return false;
4197 }
4198 
4199 template <>
4200 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4201   switch (Lex.getKind()) {
4202   default:
4203     return tokError("expected 'true' or 'false'");
4204   case lltok::kw_true:
4205     Result.assign(true);
4206     break;
4207   case lltok::kw_false:
4208     Result.assign(false);
4209     break;
4210   }
4211   Lex.Lex();
4212   return false;
4213 }
4214 
4215 template <>
4216 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4217   if (Lex.getKind() == lltok::kw_null) {
4218     if (!Result.AllowNull)
4219       return tokError("'" + Name + "' cannot be null");
4220     Lex.Lex();
4221     Result.assign(nullptr);
4222     return false;
4223   }
4224 
4225   Metadata *MD;
4226   if (parseMetadata(MD, nullptr))
4227     return true;
4228 
4229   Result.assign(MD);
4230   return false;
4231 }
4232 
4233 template <>
4234 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4235                             MDSignedOrMDField &Result) {
4236   // Try to parse a signed int.
4237   if (Lex.getKind() == lltok::APSInt) {
4238     MDSignedField Res = Result.A;
4239     if (!parseMDField(Loc, Name, Res)) {
4240       Result.assign(Res);
4241       return false;
4242     }
4243     return true;
4244   }
4245 
4246   // Otherwise, try to parse as an MDField.
4247   MDField Res = Result.B;
4248   if (!parseMDField(Loc, Name, Res)) {
4249     Result.assign(Res);
4250     return false;
4251   }
4252 
4253   return true;
4254 }
4255 
4256 template <>
4257 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4258   LocTy ValueLoc = Lex.getLoc();
4259   std::string S;
4260   if (parseStringConstant(S))
4261     return true;
4262 
4263   if (!Result.AllowEmpty && S.empty())
4264     return error(ValueLoc, "'" + Name + "' cannot be empty");
4265 
4266   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4267   return false;
4268 }
4269 
4270 template <>
4271 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4272   SmallVector<Metadata *, 4> MDs;
4273   if (parseMDNodeVector(MDs))
4274     return true;
4275 
4276   Result.assign(std::move(MDs));
4277   return false;
4278 }
4279 
4280 template <>
4281 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4282                             ChecksumKindField &Result) {
4283   Optional<DIFile::ChecksumKind> CSKind =
4284       DIFile::getChecksumKind(Lex.getStrVal());
4285 
4286   if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4287     return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4288                     "'");
4289 
4290   Result.assign(*CSKind);
4291   Lex.Lex();
4292   return false;
4293 }
4294 
4295 } // end namespace llvm
4296 
4297 template <class ParserTy>
4298 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4299   do {
4300     if (Lex.getKind() != lltok::LabelStr)
4301       return tokError("expected field label here");
4302 
4303     if (ParseField())
4304       return true;
4305   } while (EatIfPresent(lltok::comma));
4306 
4307   return false;
4308 }
4309 
4310 template <class ParserTy>
4311 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4312   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4313   Lex.Lex();
4314 
4315   if (parseToken(lltok::lparen, "expected '(' here"))
4316     return true;
4317   if (Lex.getKind() != lltok::rparen)
4318     if (parseMDFieldsImplBody(ParseField))
4319       return true;
4320 
4321   ClosingLoc = Lex.getLoc();
4322   return parseToken(lltok::rparen, "expected ')' here");
4323 }
4324 
4325 template <class FieldTy>
4326 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4327   if (Result.Seen)
4328     return tokError("field '" + Name + "' cannot be specified more than once");
4329 
4330   LocTy Loc = Lex.getLoc();
4331   Lex.Lex();
4332   return parseMDField(Loc, Name, Result);
4333 }
4334 
4335 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4336   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4337 
4338 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
4339   if (Lex.getStrVal() == #CLASS)                                               \
4340     return parse##CLASS(N, IsDistinct);
4341 #include "llvm/IR/Metadata.def"
4342 
4343   return tokError("expected metadata type");
4344 }
4345 
4346 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4347 #define NOP_FIELD(NAME, TYPE, INIT)
4348 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
4349   if (!NAME.Seen)                                                              \
4350     return error(ClosingLoc, "missing required field '" #NAME "'");
4351 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
4352   if (Lex.getStrVal() == #NAME)                                                \
4353     return parseMDField(#NAME, NAME);
4354 #define PARSE_MD_FIELDS()                                                      \
4355   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
4356   do {                                                                         \
4357     LocTy ClosingLoc;                                                          \
4358     if (parseMDFieldsImpl(                                                     \
4359             [&]() -> bool {                                                    \
4360               VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                  \
4361               return tokError(Twine("invalid field '") + Lex.getStrVal() +     \
4362                               "'");                                            \
4363             },                                                                 \
4364             ClosingLoc))                                                       \
4365       return true;                                                             \
4366     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
4367   } while (false)
4368 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
4369   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4370 
4371 /// parseDILocationFields:
4372 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4373 ///   isImplicitCode: true)
4374 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4375 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4376   OPTIONAL(line, LineField, );                                                 \
4377   OPTIONAL(column, ColumnField, );                                             \
4378   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4379   OPTIONAL(inlinedAt, MDField, );                                              \
4380   OPTIONAL(isImplicitCode, MDBoolField, (false));
4381   PARSE_MD_FIELDS();
4382 #undef VISIT_MD_FIELDS
4383 
4384   Result =
4385       GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4386                                    inlinedAt.Val, isImplicitCode.Val));
4387   return false;
4388 }
4389 
4390 /// parseGenericDINode:
4391 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4392 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4393 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4394   REQUIRED(tag, DwarfTagField, );                                              \
4395   OPTIONAL(header, MDStringField, );                                           \
4396   OPTIONAL(operands, MDFieldList, );
4397   PARSE_MD_FIELDS();
4398 #undef VISIT_MD_FIELDS
4399 
4400   Result = GET_OR_DISTINCT(GenericDINode,
4401                            (Context, tag.Val, header.Val, operands.Val));
4402   return false;
4403 }
4404 
4405 /// parseDISubrange:
4406 ///   ::= !DISubrange(count: 30, lowerBound: 2)
4407 ///   ::= !DISubrange(count: !node, lowerBound: 2)
4408 ///   ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4409 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4410 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4411   OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false));              \
4412   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4413   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4414   OPTIONAL(stride, MDSignedOrMDField, );
4415   PARSE_MD_FIELDS();
4416 #undef VISIT_MD_FIELDS
4417 
4418   Metadata *Count = nullptr;
4419   Metadata *LowerBound = nullptr;
4420   Metadata *UpperBound = nullptr;
4421   Metadata *Stride = nullptr;
4422 
4423   auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4424     if (Bound.isMDSignedField())
4425       return ConstantAsMetadata::get(ConstantInt::getSigned(
4426           Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4427     if (Bound.isMDField())
4428       return Bound.getMDFieldValue();
4429     return nullptr;
4430   };
4431 
4432   Count = convToMetadata(count);
4433   LowerBound = convToMetadata(lowerBound);
4434   UpperBound = convToMetadata(upperBound);
4435   Stride = convToMetadata(stride);
4436 
4437   Result = GET_OR_DISTINCT(DISubrange,
4438                            (Context, Count, LowerBound, UpperBound, Stride));
4439 
4440   return false;
4441 }
4442 
4443 /// parseDIGenericSubrange:
4444 ///   ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4445 ///   !node3)
4446 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4447 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4448   OPTIONAL(count, MDSignedOrMDField, );                                        \
4449   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4450   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4451   OPTIONAL(stride, MDSignedOrMDField, );
4452   PARSE_MD_FIELDS();
4453 #undef VISIT_MD_FIELDS
4454 
4455   auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4456     if (Bound.isMDSignedField())
4457       return DIExpression::get(
4458           Context, {dwarf::DW_OP_consts,
4459                     static_cast<uint64_t>(Bound.getMDSignedValue())});
4460     if (Bound.isMDField())
4461       return Bound.getMDFieldValue();
4462     return nullptr;
4463   };
4464 
4465   Metadata *Count = ConvToMetadata(count);
4466   Metadata *LowerBound = ConvToMetadata(lowerBound);
4467   Metadata *UpperBound = ConvToMetadata(upperBound);
4468   Metadata *Stride = ConvToMetadata(stride);
4469 
4470   Result = GET_OR_DISTINCT(DIGenericSubrange,
4471                            (Context, Count, LowerBound, UpperBound, Stride));
4472 
4473   return false;
4474 }
4475 
4476 /// parseDIEnumerator:
4477 ///   ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4478 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4479 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4480   REQUIRED(name, MDStringField, );                                             \
4481   REQUIRED(value, MDAPSIntField, );                                            \
4482   OPTIONAL(isUnsigned, MDBoolField, (false));
4483   PARSE_MD_FIELDS();
4484 #undef VISIT_MD_FIELDS
4485 
4486   if (isUnsigned.Val && value.Val.isNegative())
4487     return tokError("unsigned enumerator with negative value");
4488 
4489   APSInt Value(value.Val);
4490   // Add a leading zero so that unsigned values with the msb set are not
4491   // mistaken for negative values when used for signed enumerators.
4492   if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4493     Value = Value.zext(Value.getBitWidth() + 1);
4494 
4495   Result =
4496       GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4497 
4498   return false;
4499 }
4500 
4501 /// parseDIBasicType:
4502 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4503 ///                    encoding: DW_ATE_encoding, flags: 0)
4504 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4505 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4506   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
4507   OPTIONAL(name, MDStringField, );                                             \
4508   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4509   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4510   OPTIONAL(encoding, DwarfAttEncodingField, );                                 \
4511   OPTIONAL(flags, DIFlagField, );
4512   PARSE_MD_FIELDS();
4513 #undef VISIT_MD_FIELDS
4514 
4515   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4516                                          align.Val, encoding.Val, flags.Val));
4517   return false;
4518 }
4519 
4520 /// parseDIStringType:
4521 ///   ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4522 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4523 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4524   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type));                   \
4525   OPTIONAL(name, MDStringField, );                                             \
4526   OPTIONAL(stringLength, MDField, );                                           \
4527   OPTIONAL(stringLengthExpression, MDField, );                                 \
4528   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4529   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4530   OPTIONAL(encoding, DwarfAttEncodingField, );
4531   PARSE_MD_FIELDS();
4532 #undef VISIT_MD_FIELDS
4533 
4534   Result = GET_OR_DISTINCT(DIStringType,
4535                            (Context, tag.Val, name.Val, stringLength.Val,
4536                             stringLengthExpression.Val, size.Val, align.Val,
4537                             encoding.Val));
4538   return false;
4539 }
4540 
4541 /// parseDIDerivedType:
4542 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4543 ///                      line: 7, scope: !1, baseType: !2, size: 32,
4544 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
4545 ///                      dwarfAddressSpace: 3)
4546 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4547 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4548   REQUIRED(tag, DwarfTagField, );                                              \
4549   OPTIONAL(name, MDStringField, );                                             \
4550   OPTIONAL(file, MDField, );                                                   \
4551   OPTIONAL(line, LineField, );                                                 \
4552   OPTIONAL(scope, MDField, );                                                  \
4553   REQUIRED(baseType, MDField, );                                               \
4554   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4555   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4556   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4557   OPTIONAL(flags, DIFlagField, );                                              \
4558   OPTIONAL(extraData, MDField, );                                              \
4559   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));      \
4560   OPTIONAL(annotations, MDField, );
4561   PARSE_MD_FIELDS();
4562 #undef VISIT_MD_FIELDS
4563 
4564   Optional<unsigned> DWARFAddressSpace;
4565   if (dwarfAddressSpace.Val != UINT32_MAX)
4566     DWARFAddressSpace = dwarfAddressSpace.Val;
4567 
4568   Result = GET_OR_DISTINCT(DIDerivedType,
4569                            (Context, tag.Val, name.Val, file.Val, line.Val,
4570                             scope.Val, baseType.Val, size.Val, align.Val,
4571                             offset.Val, DWARFAddressSpace, flags.Val,
4572                             extraData.Val, annotations.Val));
4573   return false;
4574 }
4575 
4576 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4577 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4578   REQUIRED(tag, DwarfTagField, );                                              \
4579   OPTIONAL(name, MDStringField, );                                             \
4580   OPTIONAL(file, MDField, );                                                   \
4581   OPTIONAL(line, LineField, );                                                 \
4582   OPTIONAL(scope, MDField, );                                                  \
4583   OPTIONAL(baseType, MDField, );                                               \
4584   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4585   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4586   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4587   OPTIONAL(flags, DIFlagField, );                                              \
4588   OPTIONAL(elements, MDField, );                                               \
4589   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
4590   OPTIONAL(vtableHolder, MDField, );                                           \
4591   OPTIONAL(templateParams, MDField, );                                         \
4592   OPTIONAL(identifier, MDStringField, );                                       \
4593   OPTIONAL(discriminator, MDField, );                                          \
4594   OPTIONAL(dataLocation, MDField, );                                           \
4595   OPTIONAL(associated, MDField, );                                             \
4596   OPTIONAL(allocated, MDField, );                                              \
4597   OPTIONAL(rank, MDSignedOrMDField, );                                         \
4598   OPTIONAL(annotations, MDField, );
4599   PARSE_MD_FIELDS();
4600 #undef VISIT_MD_FIELDS
4601 
4602   Metadata *Rank = nullptr;
4603   if (rank.isMDSignedField())
4604     Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4605         Type::getInt64Ty(Context), rank.getMDSignedValue()));
4606   else if (rank.isMDField())
4607     Rank = rank.getMDFieldValue();
4608 
4609   // If this has an identifier try to build an ODR type.
4610   if (identifier.Val)
4611     if (auto *CT = DICompositeType::buildODRType(
4612             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4613             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4614             elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4615             discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4616             Rank, annotations.Val)) {
4617       Result = CT;
4618       return false;
4619     }
4620 
4621   // Create a new node, and save it in the context if it belongs in the type
4622   // map.
4623   Result = GET_OR_DISTINCT(
4624       DICompositeType,
4625       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4626        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4627        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4628        discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
4629        annotations.Val));
4630   return false;
4631 }
4632 
4633 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4634 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4635   OPTIONAL(flags, DIFlagField, );                                              \
4636   OPTIONAL(cc, DwarfCCField, );                                                \
4637   REQUIRED(types, MDField, );
4638   PARSE_MD_FIELDS();
4639 #undef VISIT_MD_FIELDS
4640 
4641   Result = GET_OR_DISTINCT(DISubroutineType,
4642                            (Context, flags.Val, cc.Val, types.Val));
4643   return false;
4644 }
4645 
4646 /// parseDIFileType:
4647 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4648 ///                   checksumkind: CSK_MD5,
4649 ///                   checksum: "000102030405060708090a0b0c0d0e0f",
4650 ///                   source: "source file contents")
4651 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4652   // The default constructed value for checksumkind is required, but will never
4653   // be used, as the parser checks if the field was actually Seen before using
4654   // the Val.
4655 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4656   REQUIRED(filename, MDStringField, );                                         \
4657   REQUIRED(directory, MDStringField, );                                        \
4658   OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5));                \
4659   OPTIONAL(checksum, MDStringField, );                                         \
4660   OPTIONAL(source, MDStringField, );
4661   PARSE_MD_FIELDS();
4662 #undef VISIT_MD_FIELDS
4663 
4664   Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4665   if (checksumkind.Seen && checksum.Seen)
4666     OptChecksum.emplace(checksumkind.Val, checksum.Val);
4667   else if (checksumkind.Seen || checksum.Seen)
4668     return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4669 
4670   Optional<MDString *> OptSource;
4671   if (source.Seen)
4672     OptSource = source.Val;
4673   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4674                                     OptChecksum, OptSource));
4675   return false;
4676 }
4677 
4678 /// parseDICompileUnit:
4679 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4680 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
4681 ///                      splitDebugFilename: "abc.debug",
4682 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4683 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4684 ///                      sysroot: "/", sdk: "MacOSX.sdk")
4685 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4686   if (!IsDistinct)
4687     return Lex.Error("missing 'distinct', required for !DICompileUnit");
4688 
4689 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4690   REQUIRED(language, DwarfLangField, );                                        \
4691   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
4692   OPTIONAL(producer, MDStringField, );                                         \
4693   OPTIONAL(isOptimized, MDBoolField, );                                        \
4694   OPTIONAL(flags, MDStringField, );                                            \
4695   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
4696   OPTIONAL(splitDebugFilename, MDStringField, );                               \
4697   OPTIONAL(emissionKind, EmissionKindField, );                                 \
4698   OPTIONAL(enums, MDField, );                                                  \
4699   OPTIONAL(retainedTypes, MDField, );                                          \
4700   OPTIONAL(globals, MDField, );                                                \
4701   OPTIONAL(imports, MDField, );                                                \
4702   OPTIONAL(macros, MDField, );                                                 \
4703   OPTIONAL(dwoId, MDUnsignedField, );                                          \
4704   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
4705   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);                       \
4706   OPTIONAL(nameTableKind, NameTableKindField, );                               \
4707   OPTIONAL(rangesBaseAddress, MDBoolField, = false);                           \
4708   OPTIONAL(sysroot, MDStringField, );                                          \
4709   OPTIONAL(sdk, MDStringField, );
4710   PARSE_MD_FIELDS();
4711 #undef VISIT_MD_FIELDS
4712 
4713   Result = DICompileUnit::getDistinct(
4714       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4715       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4716       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4717       splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4718       rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4719   return false;
4720 }
4721 
4722 /// parseDISubprogram:
4723 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4724 ///                     file: !1, line: 7, type: !2, isLocal: false,
4725 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
4726 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
4727 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
4728 ///                     spFlags: 10, isOptimized: false, templateParams: !4,
4729 ///                     declaration: !5, retainedNodes: !6, thrownTypes: !7,
4730 ///                     annotations: !8)
4731 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4732   auto Loc = Lex.getLoc();
4733 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4734   OPTIONAL(scope, MDField, );                                                  \
4735   OPTIONAL(name, MDStringField, );                                             \
4736   OPTIONAL(linkageName, MDStringField, );                                      \
4737   OPTIONAL(file, MDField, );                                                   \
4738   OPTIONAL(line, LineField, );                                                 \
4739   OPTIONAL(type, MDField, );                                                   \
4740   OPTIONAL(isLocal, MDBoolField, );                                            \
4741   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4742   OPTIONAL(scopeLine, LineField, );                                            \
4743   OPTIONAL(containingType, MDField, );                                         \
4744   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
4745   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
4746   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
4747   OPTIONAL(flags, DIFlagField, );                                              \
4748   OPTIONAL(spFlags, DISPFlagField, );                                          \
4749   OPTIONAL(isOptimized, MDBoolField, );                                        \
4750   OPTIONAL(unit, MDField, );                                                   \
4751   OPTIONAL(templateParams, MDField, );                                         \
4752   OPTIONAL(declaration, MDField, );                                            \
4753   OPTIONAL(retainedNodes, MDField, );                                          \
4754   OPTIONAL(thrownTypes, MDField, );                                            \
4755   OPTIONAL(annotations, MDField, );
4756   PARSE_MD_FIELDS();
4757 #undef VISIT_MD_FIELDS
4758 
4759   // An explicit spFlags field takes precedence over individual fields in
4760   // older IR versions.
4761   DISubprogram::DISPFlags SPFlags =
4762       spFlags.Seen ? spFlags.Val
4763                    : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4764                                              isOptimized.Val, virtuality.Val);
4765   if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4766     return Lex.Error(
4767         Loc,
4768         "missing 'distinct', required for !DISubprogram that is a Definition");
4769   Result = GET_OR_DISTINCT(
4770       DISubprogram,
4771       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4772        type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4773        thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4774        declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val));
4775   return false;
4776 }
4777 
4778 /// parseDILexicalBlock:
4779 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4780 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4781 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4782   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4783   OPTIONAL(file, MDField, );                                                   \
4784   OPTIONAL(line, LineField, );                                                 \
4785   OPTIONAL(column, ColumnField, );
4786   PARSE_MD_FIELDS();
4787 #undef VISIT_MD_FIELDS
4788 
4789   Result = GET_OR_DISTINCT(
4790       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4791   return false;
4792 }
4793 
4794 /// parseDILexicalBlockFile:
4795 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4796 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4797 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4798   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4799   OPTIONAL(file, MDField, );                                                   \
4800   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4801   PARSE_MD_FIELDS();
4802 #undef VISIT_MD_FIELDS
4803 
4804   Result = GET_OR_DISTINCT(DILexicalBlockFile,
4805                            (Context, scope.Val, file.Val, discriminator.Val));
4806   return false;
4807 }
4808 
4809 /// parseDICommonBlock:
4810 ///   ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4811 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4812 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4813   REQUIRED(scope, MDField, );                                                  \
4814   OPTIONAL(declaration, MDField, );                                            \
4815   OPTIONAL(name, MDStringField, );                                             \
4816   OPTIONAL(file, MDField, );                                                   \
4817   OPTIONAL(line, LineField, );
4818   PARSE_MD_FIELDS();
4819 #undef VISIT_MD_FIELDS
4820 
4821   Result = GET_OR_DISTINCT(DICommonBlock,
4822                            (Context, scope.Val, declaration.Val, name.Val,
4823                             file.Val, line.Val));
4824   return false;
4825 }
4826 
4827 /// parseDINamespace:
4828 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4829 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
4830 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4831   REQUIRED(scope, MDField, );                                                  \
4832   OPTIONAL(name, MDStringField, );                                             \
4833   OPTIONAL(exportSymbols, MDBoolField, );
4834   PARSE_MD_FIELDS();
4835 #undef VISIT_MD_FIELDS
4836 
4837   Result = GET_OR_DISTINCT(DINamespace,
4838                            (Context, scope.Val, name.Val, exportSymbols.Val));
4839   return false;
4840 }
4841 
4842 /// parseDIMacro:
4843 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
4844 ///   "SomeValue")
4845 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
4846 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4847   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
4848   OPTIONAL(line, LineField, );                                                 \
4849   REQUIRED(name, MDStringField, );                                             \
4850   OPTIONAL(value, MDStringField, );
4851   PARSE_MD_FIELDS();
4852 #undef VISIT_MD_FIELDS
4853 
4854   Result = GET_OR_DISTINCT(DIMacro,
4855                            (Context, type.Val, line.Val, name.Val, value.Val));
4856   return false;
4857 }
4858 
4859 /// parseDIMacroFile:
4860 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4861 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4862 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4863   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
4864   OPTIONAL(line, LineField, );                                                 \
4865   REQUIRED(file, MDField, );                                                   \
4866   OPTIONAL(nodes, MDField, );
4867   PARSE_MD_FIELDS();
4868 #undef VISIT_MD_FIELDS
4869 
4870   Result = GET_OR_DISTINCT(DIMacroFile,
4871                            (Context, type.Val, line.Val, file.Val, nodes.Val));
4872   return false;
4873 }
4874 
4875 /// parseDIModule:
4876 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
4877 ///   "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
4878 ///   file: !1, line: 4, isDecl: false)
4879 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
4880 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4881   REQUIRED(scope, MDField, );                                                  \
4882   REQUIRED(name, MDStringField, );                                             \
4883   OPTIONAL(configMacros, MDStringField, );                                     \
4884   OPTIONAL(includePath, MDStringField, );                                      \
4885   OPTIONAL(apinotes, MDStringField, );                                         \
4886   OPTIONAL(file, MDField, );                                                   \
4887   OPTIONAL(line, LineField, );                                                 \
4888   OPTIONAL(isDecl, MDBoolField, );
4889   PARSE_MD_FIELDS();
4890 #undef VISIT_MD_FIELDS
4891 
4892   Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
4893                                       configMacros.Val, includePath.Val,
4894                                       apinotes.Val, line.Val, isDecl.Val));
4895   return false;
4896 }
4897 
4898 /// parseDITemplateTypeParameter:
4899 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
4900 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4901 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4902   OPTIONAL(name, MDStringField, );                                             \
4903   REQUIRED(type, MDField, );                                                   \
4904   OPTIONAL(defaulted, MDBoolField, );
4905   PARSE_MD_FIELDS();
4906 #undef VISIT_MD_FIELDS
4907 
4908   Result = GET_OR_DISTINCT(DITemplateTypeParameter,
4909                            (Context, name.Val, type.Val, defaulted.Val));
4910   return false;
4911 }
4912 
4913 /// parseDITemplateValueParameter:
4914 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4915 ///                                 name: "V", type: !1, defaulted: false,
4916 ///                                 value: i32 7)
4917 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4918 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4919   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
4920   OPTIONAL(name, MDStringField, );                                             \
4921   OPTIONAL(type, MDField, );                                                   \
4922   OPTIONAL(defaulted, MDBoolField, );                                          \
4923   REQUIRED(value, MDField, );
4924 
4925   PARSE_MD_FIELDS();
4926 #undef VISIT_MD_FIELDS
4927 
4928   Result = GET_OR_DISTINCT(
4929       DITemplateValueParameter,
4930       (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
4931   return false;
4932 }
4933 
4934 /// parseDIGlobalVariable:
4935 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4936 ///                         file: !1, line: 7, type: !2, isLocal: false,
4937 ///                         isDefinition: true, templateParams: !3,
4938 ///                         declaration: !4, align: 8)
4939 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4940 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4941   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
4942   OPTIONAL(scope, MDField, );                                                  \
4943   OPTIONAL(linkageName, MDStringField, );                                      \
4944   OPTIONAL(file, MDField, );                                                   \
4945   OPTIONAL(line, LineField, );                                                 \
4946   OPTIONAL(type, MDField, );                                                   \
4947   OPTIONAL(isLocal, MDBoolField, );                                            \
4948   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4949   OPTIONAL(templateParams, MDField, );                                         \
4950   OPTIONAL(declaration, MDField, );                                            \
4951   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4952   OPTIONAL(annotations, MDField, );
4953   PARSE_MD_FIELDS();
4954 #undef VISIT_MD_FIELDS
4955 
4956   Result =
4957       GET_OR_DISTINCT(DIGlobalVariable,
4958                       (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4959                        line.Val, type.Val, isLocal.Val, isDefinition.Val,
4960                        declaration.Val, templateParams.Val, align.Val,
4961                        annotations.Val));
4962   return false;
4963 }
4964 
4965 /// parseDILocalVariable:
4966 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4967 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
4968 ///                        align: 8)
4969 ///   ::= !DILocalVariable(scope: !0, name: "foo",
4970 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
4971 ///                        align: 8)
4972 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4973 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4974   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4975   OPTIONAL(name, MDStringField, );                                             \
4976   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
4977   OPTIONAL(file, MDField, );                                                   \
4978   OPTIONAL(line, LineField, );                                                 \
4979   OPTIONAL(type, MDField, );                                                   \
4980   OPTIONAL(flags, DIFlagField, );                                              \
4981   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4982   OPTIONAL(annotations, MDField, );
4983   PARSE_MD_FIELDS();
4984 #undef VISIT_MD_FIELDS
4985 
4986   Result = GET_OR_DISTINCT(DILocalVariable,
4987                            (Context, scope.Val, name.Val, file.Val, line.Val,
4988                             type.Val, arg.Val, flags.Val, align.Val,
4989                             annotations.Val));
4990   return false;
4991 }
4992 
4993 /// parseDILabel:
4994 ///   ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4995 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
4996 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4997   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4998   REQUIRED(name, MDStringField, );                                             \
4999   REQUIRED(file, MDField, );                                                   \
5000   REQUIRED(line, LineField, );
5001   PARSE_MD_FIELDS();
5002 #undef VISIT_MD_FIELDS
5003 
5004   Result = GET_OR_DISTINCT(DILabel,
5005                            (Context, scope.Val, name.Val, file.Val, line.Val));
5006   return false;
5007 }
5008 
5009 /// parseDIExpression:
5010 ///   ::= !DIExpression(0, 7, -1)
5011 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5012   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5013   Lex.Lex();
5014 
5015   if (parseToken(lltok::lparen, "expected '(' here"))
5016     return true;
5017 
5018   SmallVector<uint64_t, 8> Elements;
5019   if (Lex.getKind() != lltok::rparen)
5020     do {
5021       if (Lex.getKind() == lltok::DwarfOp) {
5022         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5023           Lex.Lex();
5024           Elements.push_back(Op);
5025           continue;
5026         }
5027         return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5028       }
5029 
5030       if (Lex.getKind() == lltok::DwarfAttEncoding) {
5031         if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5032           Lex.Lex();
5033           Elements.push_back(Op);
5034           continue;
5035         }
5036         return tokError(Twine("invalid DWARF attribute encoding '") +
5037                         Lex.getStrVal() + "'");
5038       }
5039 
5040       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5041         return tokError("expected unsigned integer");
5042 
5043       auto &U = Lex.getAPSIntVal();
5044       if (U.ugt(UINT64_MAX))
5045         return tokError("element too large, limit is " + Twine(UINT64_MAX));
5046       Elements.push_back(U.getZExtValue());
5047       Lex.Lex();
5048     } while (EatIfPresent(lltok::comma));
5049 
5050   if (parseToken(lltok::rparen, "expected ')' here"))
5051     return true;
5052 
5053   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5054   return false;
5055 }
5056 
5057 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5058   return parseDIArgList(Result, IsDistinct, nullptr);
5059 }
5060 /// ParseDIArgList:
5061 ///   ::= !DIArgList(i32 7, i64 %0)
5062 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5063                               PerFunctionState *PFS) {
5064   assert(PFS && "Expected valid function state");
5065   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5066   Lex.Lex();
5067 
5068   if (parseToken(lltok::lparen, "expected '(' here"))
5069     return true;
5070 
5071   SmallVector<ValueAsMetadata *, 4> Args;
5072   if (Lex.getKind() != lltok::rparen)
5073     do {
5074       Metadata *MD;
5075       if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5076         return true;
5077       Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5078     } while (EatIfPresent(lltok::comma));
5079 
5080   if (parseToken(lltok::rparen, "expected ')' here"))
5081     return true;
5082 
5083   Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5084   return false;
5085 }
5086 
5087 /// parseDIGlobalVariableExpression:
5088 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5089 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5090                                                bool IsDistinct) {
5091 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5092   REQUIRED(var, MDField, );                                                    \
5093   REQUIRED(expr, MDField, );
5094   PARSE_MD_FIELDS();
5095 #undef VISIT_MD_FIELDS
5096 
5097   Result =
5098       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5099   return false;
5100 }
5101 
5102 /// parseDIObjCProperty:
5103 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5104 ///                       getter: "getFoo", attributes: 7, type: !2)
5105 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5106 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5107   OPTIONAL(name, MDStringField, );                                             \
5108   OPTIONAL(file, MDField, );                                                   \
5109   OPTIONAL(line, LineField, );                                                 \
5110   OPTIONAL(setter, MDStringField, );                                           \
5111   OPTIONAL(getter, MDStringField, );                                           \
5112   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
5113   OPTIONAL(type, MDField, );
5114   PARSE_MD_FIELDS();
5115 #undef VISIT_MD_FIELDS
5116 
5117   Result = GET_OR_DISTINCT(DIObjCProperty,
5118                            (Context, name.Val, file.Val, line.Val, setter.Val,
5119                             getter.Val, attributes.Val, type.Val));
5120   return false;
5121 }
5122 
5123 /// parseDIImportedEntity:
5124 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5125 ///                         line: 7, name: "foo", elements: !2)
5126 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5127 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5128   REQUIRED(tag, DwarfTagField, );                                              \
5129   REQUIRED(scope, MDField, );                                                  \
5130   OPTIONAL(entity, MDField, );                                                 \
5131   OPTIONAL(file, MDField, );                                                   \
5132   OPTIONAL(line, LineField, );                                                 \
5133   OPTIONAL(name, MDStringField, );                                             \
5134   OPTIONAL(elements, MDField, );
5135   PARSE_MD_FIELDS();
5136 #undef VISIT_MD_FIELDS
5137 
5138   Result = GET_OR_DISTINCT(DIImportedEntity,
5139                            (Context, tag.Val, scope.Val, entity.Val, file.Val,
5140                             line.Val, name.Val, elements.Val));
5141   return false;
5142 }
5143 
5144 #undef PARSE_MD_FIELD
5145 #undef NOP_FIELD
5146 #undef REQUIRE_FIELD
5147 #undef DECLARE_FIELD
5148 
5149 /// parseMetadataAsValue
5150 ///  ::= metadata i32 %local
5151 ///  ::= metadata i32 @global
5152 ///  ::= metadata i32 7
5153 ///  ::= metadata !0
5154 ///  ::= metadata !{...}
5155 ///  ::= metadata !"string"
5156 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5157   // Note: the type 'metadata' has already been parsed.
5158   Metadata *MD;
5159   if (parseMetadata(MD, &PFS))
5160     return true;
5161 
5162   V = MetadataAsValue::get(Context, MD);
5163   return false;
5164 }
5165 
5166 /// parseValueAsMetadata
5167 ///  ::= i32 %local
5168 ///  ::= i32 @global
5169 ///  ::= i32 7
5170 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5171                                     PerFunctionState *PFS) {
5172   Type *Ty;
5173   LocTy Loc;
5174   if (parseType(Ty, TypeMsg, Loc))
5175     return true;
5176   if (Ty->isMetadataTy())
5177     return error(Loc, "invalid metadata-value-metadata roundtrip");
5178 
5179   Value *V;
5180   if (parseValue(Ty, V, PFS))
5181     return true;
5182 
5183   MD = ValueAsMetadata::get(V);
5184   return false;
5185 }
5186 
5187 /// parseMetadata
5188 ///  ::= i32 %local
5189 ///  ::= i32 @global
5190 ///  ::= i32 7
5191 ///  ::= !42
5192 ///  ::= !{...}
5193 ///  ::= !"string"
5194 ///  ::= !DILocation(...)
5195 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5196   if (Lex.getKind() == lltok::MetadataVar) {
5197     MDNode *N;
5198     // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5199     // so parsing this requires a Function State.
5200     if (Lex.getStrVal() == "DIArgList") {
5201       if (parseDIArgList(N, false, PFS))
5202         return true;
5203     } else if (parseSpecializedMDNode(N)) {
5204       return true;
5205     }
5206     MD = N;
5207     return false;
5208   }
5209 
5210   // ValueAsMetadata:
5211   // <type> <value>
5212   if (Lex.getKind() != lltok::exclaim)
5213     return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5214 
5215   // '!'.
5216   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5217   Lex.Lex();
5218 
5219   // MDString:
5220   //   ::= '!' STRINGCONSTANT
5221   if (Lex.getKind() == lltok::StringConstant) {
5222     MDString *S;
5223     if (parseMDString(S))
5224       return true;
5225     MD = S;
5226     return false;
5227   }
5228 
5229   // MDNode:
5230   // !{ ... }
5231   // !7
5232   MDNode *N;
5233   if (parseMDNodeTail(N))
5234     return true;
5235   MD = N;
5236   return false;
5237 }
5238 
5239 //===----------------------------------------------------------------------===//
5240 // Function Parsing.
5241 //===----------------------------------------------------------------------===//
5242 
5243 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5244                                    PerFunctionState *PFS) {
5245   if (Ty->isFunctionTy())
5246     return error(ID.Loc, "functions are not values, refer to them as pointers");
5247 
5248   switch (ID.Kind) {
5249   case ValID::t_LocalID:
5250     if (!PFS)
5251       return error(ID.Loc, "invalid use of function-local name");
5252     V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
5253     return V == nullptr;
5254   case ValID::t_LocalName:
5255     if (!PFS)
5256       return error(ID.Loc, "invalid use of function-local name");
5257     V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
5258     return V == nullptr;
5259   case ValID::t_InlineAsm: {
5260     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5261       return error(ID.Loc, "invalid type for inline asm constraint string");
5262     V = InlineAsm::get(
5263         ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5264         InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5265     return false;
5266   }
5267   case ValID::t_GlobalName:
5268     V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
5269     return V == nullptr;
5270   case ValID::t_GlobalID:
5271     V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
5272     return V == nullptr;
5273   case ValID::t_APSInt:
5274     if (!Ty->isIntegerTy())
5275       return error(ID.Loc, "integer constant must have integer type");
5276     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5277     V = ConstantInt::get(Context, ID.APSIntVal);
5278     return false;
5279   case ValID::t_APFloat:
5280     if (!Ty->isFloatingPointTy() ||
5281         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5282       return error(ID.Loc, "floating point constant invalid for type");
5283 
5284     // The lexer has no type info, so builds all half, bfloat, float, and double
5285     // FP constants as double.  Fix this here.  Long double does not need this.
5286     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5287       // Check for signaling before potentially converting and losing that info.
5288       bool IsSNAN = ID.APFloatVal.isSignaling();
5289       bool Ignored;
5290       if (Ty->isHalfTy())
5291         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5292                               &Ignored);
5293       else if (Ty->isBFloatTy())
5294         ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5295                               &Ignored);
5296       else if (Ty->isFloatTy())
5297         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5298                               &Ignored);
5299       if (IsSNAN) {
5300         // The convert call above may quiet an SNaN, so manufacture another
5301         // SNaN. The bitcast works because the payload (significand) parameter
5302         // is truncated to fit.
5303         APInt Payload = ID.APFloatVal.bitcastToAPInt();
5304         ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5305                                          ID.APFloatVal.isNegative(), &Payload);
5306       }
5307     }
5308     V = ConstantFP::get(Context, ID.APFloatVal);
5309 
5310     if (V->getType() != Ty)
5311       return error(ID.Loc, "floating point constant does not have type '" +
5312                                getTypeString(Ty) + "'");
5313 
5314     return false;
5315   case ValID::t_Null:
5316     if (!Ty->isPointerTy())
5317       return error(ID.Loc, "null must be a pointer type");
5318     V = ConstantPointerNull::get(cast<PointerType>(Ty));
5319     return false;
5320   case ValID::t_Undef:
5321     // FIXME: LabelTy should not be a first-class type.
5322     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5323       return error(ID.Loc, "invalid type for undef constant");
5324     V = UndefValue::get(Ty);
5325     return false;
5326   case ValID::t_EmptyArray:
5327     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5328       return error(ID.Loc, "invalid empty array initializer");
5329     V = UndefValue::get(Ty);
5330     return false;
5331   case ValID::t_Zero:
5332     // FIXME: LabelTy should not be a first-class type.
5333     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5334       return error(ID.Loc, "invalid type for null constant");
5335     V = Constant::getNullValue(Ty);
5336     return false;
5337   case ValID::t_None:
5338     if (!Ty->isTokenTy())
5339       return error(ID.Loc, "invalid type for none constant");
5340     V = Constant::getNullValue(Ty);
5341     return false;
5342   case ValID::t_Poison:
5343     // FIXME: LabelTy should not be a first-class type.
5344     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5345       return error(ID.Loc, "invalid type for poison constant");
5346     V = PoisonValue::get(Ty);
5347     return false;
5348   case ValID::t_Constant:
5349     if (ID.ConstantVal->getType() != Ty)
5350       return error(ID.Loc, "constant expression type mismatch: got type '" +
5351                                getTypeString(ID.ConstantVal->getType()) +
5352                                "' but expected '" + getTypeString(Ty) + "'");
5353     V = ID.ConstantVal;
5354     return false;
5355   case ValID::t_ConstantStruct:
5356   case ValID::t_PackedConstantStruct:
5357     if (StructType *ST = dyn_cast<StructType>(Ty)) {
5358       if (ST->getNumElements() != ID.UIntVal)
5359         return error(ID.Loc,
5360                      "initializer with struct type has wrong # elements");
5361       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5362         return error(ID.Loc, "packed'ness of initializer and type don't match");
5363 
5364       // Verify that the elements are compatible with the structtype.
5365       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5366         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5367           return error(
5368               ID.Loc,
5369               "element " + Twine(i) +
5370                   " of struct initializer doesn't match struct element type");
5371 
5372       V = ConstantStruct::get(
5373           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5374     } else
5375       return error(ID.Loc, "constant expression type mismatch");
5376     return false;
5377   }
5378   llvm_unreachable("Invalid ValID");
5379 }
5380 
5381 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5382   C = nullptr;
5383   ValID ID;
5384   auto Loc = Lex.getLoc();
5385   if (parseValID(ID, /*PFS=*/nullptr))
5386     return true;
5387   switch (ID.Kind) {
5388   case ValID::t_APSInt:
5389   case ValID::t_APFloat:
5390   case ValID::t_Undef:
5391   case ValID::t_Constant:
5392   case ValID::t_ConstantStruct:
5393   case ValID::t_PackedConstantStruct: {
5394     Value *V;
5395     if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
5396       return true;
5397     assert(isa<Constant>(V) && "Expected a constant value");
5398     C = cast<Constant>(V);
5399     return false;
5400   }
5401   case ValID::t_Null:
5402     C = Constant::getNullValue(Ty);
5403     return false;
5404   default:
5405     return error(Loc, "expected a constant value");
5406   }
5407 }
5408 
5409 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5410   V = nullptr;
5411   ValID ID;
5412   return parseValID(ID, PFS, Ty) ||
5413          convertValIDToValue(Ty, ID, V, PFS);
5414 }
5415 
5416 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5417   Type *Ty = nullptr;
5418   return parseType(Ty) || parseValue(Ty, V, PFS);
5419 }
5420 
5421 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5422                                       PerFunctionState &PFS) {
5423   Value *V;
5424   Loc = Lex.getLoc();
5425   if (parseTypeAndValue(V, PFS))
5426     return true;
5427   if (!isa<BasicBlock>(V))
5428     return error(Loc, "expected a basic block");
5429   BB = cast<BasicBlock>(V);
5430   return false;
5431 }
5432 
5433 /// FunctionHeader
5434 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5435 ///       OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5436 ///       '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5437 ///       OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5438 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5439   // parse the linkage.
5440   LocTy LinkageLoc = Lex.getLoc();
5441   unsigned Linkage;
5442   unsigned Visibility;
5443   unsigned DLLStorageClass;
5444   bool DSOLocal;
5445   AttrBuilder RetAttrs;
5446   unsigned CC;
5447   bool HasLinkage;
5448   Type *RetType = nullptr;
5449   LocTy RetTypeLoc = Lex.getLoc();
5450   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5451                            DSOLocal) ||
5452       parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5453       parseType(RetType, RetTypeLoc, true /*void allowed*/))
5454     return true;
5455 
5456   // Verify that the linkage is ok.
5457   switch ((GlobalValue::LinkageTypes)Linkage) {
5458   case GlobalValue::ExternalLinkage:
5459     break; // always ok.
5460   case GlobalValue::ExternalWeakLinkage:
5461     if (IsDefine)
5462       return error(LinkageLoc, "invalid linkage for function definition");
5463     break;
5464   case GlobalValue::PrivateLinkage:
5465   case GlobalValue::InternalLinkage:
5466   case GlobalValue::AvailableExternallyLinkage:
5467   case GlobalValue::LinkOnceAnyLinkage:
5468   case GlobalValue::LinkOnceODRLinkage:
5469   case GlobalValue::WeakAnyLinkage:
5470   case GlobalValue::WeakODRLinkage:
5471     if (!IsDefine)
5472       return error(LinkageLoc, "invalid linkage for function declaration");
5473     break;
5474   case GlobalValue::AppendingLinkage:
5475   case GlobalValue::CommonLinkage:
5476     return error(LinkageLoc, "invalid function linkage type");
5477   }
5478 
5479   if (!isValidVisibilityForLinkage(Visibility, Linkage))
5480     return error(LinkageLoc,
5481                  "symbol with local linkage must have default visibility");
5482 
5483   if (!FunctionType::isValidReturnType(RetType))
5484     return error(RetTypeLoc, "invalid function return type");
5485 
5486   LocTy NameLoc = Lex.getLoc();
5487 
5488   std::string FunctionName;
5489   if (Lex.getKind() == lltok::GlobalVar) {
5490     FunctionName = Lex.getStrVal();
5491   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
5492     unsigned NameID = Lex.getUIntVal();
5493 
5494     if (NameID != NumberedVals.size())
5495       return tokError("function expected to be numbered '%" +
5496                       Twine(NumberedVals.size()) + "'");
5497   } else {
5498     return tokError("expected function name");
5499   }
5500 
5501   Lex.Lex();
5502 
5503   if (Lex.getKind() != lltok::lparen)
5504     return tokError("expected '(' in function argument list");
5505 
5506   SmallVector<ArgInfo, 8> ArgList;
5507   bool IsVarArg;
5508   AttrBuilder FuncAttrs;
5509   std::vector<unsigned> FwdRefAttrGrps;
5510   LocTy BuiltinLoc;
5511   std::string Section;
5512   std::string Partition;
5513   MaybeAlign Alignment;
5514   std::string GC;
5515   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5516   unsigned AddrSpace = 0;
5517   Constant *Prefix = nullptr;
5518   Constant *Prologue = nullptr;
5519   Constant *PersonalityFn = nullptr;
5520   Comdat *C;
5521 
5522   if (parseArgumentList(ArgList, IsVarArg) ||
5523       parseOptionalUnnamedAddr(UnnamedAddr) ||
5524       parseOptionalProgramAddrSpace(AddrSpace) ||
5525       parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5526                                  BuiltinLoc) ||
5527       (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5528       (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5529       parseOptionalComdat(FunctionName, C) ||
5530       parseOptionalAlignment(Alignment) ||
5531       (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5532       (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5533       (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5534       (EatIfPresent(lltok::kw_personality) &&
5535        parseGlobalTypeAndValue(PersonalityFn)))
5536     return true;
5537 
5538   if (FuncAttrs.contains(Attribute::Builtin))
5539     return error(BuiltinLoc, "'builtin' attribute not valid on function");
5540 
5541   // If the alignment was parsed as an attribute, move to the alignment field.
5542   if (FuncAttrs.hasAlignmentAttr()) {
5543     Alignment = FuncAttrs.getAlignment();
5544     FuncAttrs.removeAttribute(Attribute::Alignment);
5545   }
5546 
5547   // Okay, if we got here, the function is syntactically valid.  Convert types
5548   // and do semantic checks.
5549   std::vector<Type*> ParamTypeList;
5550   SmallVector<AttributeSet, 8> Attrs;
5551 
5552   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5553     ParamTypeList.push_back(ArgList[i].Ty);
5554     Attrs.push_back(ArgList[i].Attrs);
5555   }
5556 
5557   AttributeList PAL =
5558       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5559                          AttributeSet::get(Context, RetAttrs), Attrs);
5560 
5561   if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
5562     return error(RetTypeLoc, "functions with 'sret' argument must return void");
5563 
5564   FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5565   PointerType *PFT = PointerType::get(FT, AddrSpace);
5566 
5567   Fn = nullptr;
5568   GlobalValue *FwdFn = nullptr;
5569   if (!FunctionName.empty()) {
5570     // If this was a definition of a forward reference, remove the definition
5571     // from the forward reference table and fill in the forward ref.
5572     auto FRVI = ForwardRefVals.find(FunctionName);
5573     if (FRVI != ForwardRefVals.end()) {
5574       FwdFn = FRVI->second.first;
5575       if (!FwdFn->getType()->isOpaque()) {
5576         if (!FwdFn->getType()->getPointerElementType()->isFunctionTy())
5577           return error(FRVI->second.second, "invalid forward reference to "
5578                                             "function as global value!");
5579         if (FwdFn->getType() != PFT)
5580           return error(FRVI->second.second,
5581                        "invalid forward reference to "
5582                        "function '" +
5583                            FunctionName +
5584                            "' with wrong type: "
5585                            "expected '" +
5586                            getTypeString(PFT) + "' but was '" +
5587                            getTypeString(FwdFn->getType()) + "'");
5588       }
5589       ForwardRefVals.erase(FRVI);
5590     } else if ((Fn = M->getFunction(FunctionName))) {
5591       // Reject redefinitions.
5592       return error(NameLoc,
5593                    "invalid redefinition of function '" + FunctionName + "'");
5594     } else if (M->getNamedValue(FunctionName)) {
5595       return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5596     }
5597 
5598   } else {
5599     // If this is a definition of a forward referenced function, make sure the
5600     // types agree.
5601     auto I = ForwardRefValIDs.find(NumberedVals.size());
5602     if (I != ForwardRefValIDs.end()) {
5603       FwdFn = cast<Function>(I->second.first);
5604       if (!FwdFn->getType()->isOpaque() && FwdFn->getType() != PFT)
5605         return error(NameLoc, "type of definition and forward reference of '@" +
5606                                   Twine(NumberedVals.size()) +
5607                                   "' disagree: "
5608                                   "expected '" +
5609                                   getTypeString(PFT) + "' but was '" +
5610                                   getTypeString(FwdFn->getType()) + "'");
5611       ForwardRefValIDs.erase(I);
5612     }
5613   }
5614 
5615   Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5616                         FunctionName, M);
5617 
5618   assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5619 
5620   if (FunctionName.empty())
5621     NumberedVals.push_back(Fn);
5622 
5623   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5624   maybeSetDSOLocal(DSOLocal, *Fn);
5625   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5626   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5627   Fn->setCallingConv(CC);
5628   Fn->setAttributes(PAL);
5629   Fn->setUnnamedAddr(UnnamedAddr);
5630   Fn->setAlignment(MaybeAlign(Alignment));
5631   Fn->setSection(Section);
5632   Fn->setPartition(Partition);
5633   Fn->setComdat(C);
5634   Fn->setPersonalityFn(PersonalityFn);
5635   if (!GC.empty()) Fn->setGC(GC);
5636   Fn->setPrefixData(Prefix);
5637   Fn->setPrologueData(Prologue);
5638   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5639 
5640   // Add all of the arguments we parsed to the function.
5641   Function::arg_iterator ArgIt = Fn->arg_begin();
5642   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5643     // If the argument has a name, insert it into the argument symbol table.
5644     if (ArgList[i].Name.empty()) continue;
5645 
5646     // Set the name, if it conflicted, it will be auto-renamed.
5647     ArgIt->setName(ArgList[i].Name);
5648 
5649     if (ArgIt->getName() != ArgList[i].Name)
5650       return error(ArgList[i].Loc,
5651                    "redefinition of argument '%" + ArgList[i].Name + "'");
5652   }
5653 
5654   if (FwdFn) {
5655     FwdFn->replaceAllUsesWith(Fn);
5656     FwdFn->eraseFromParent();
5657   }
5658 
5659   if (IsDefine)
5660     return false;
5661 
5662   // Check the declaration has no block address forward references.
5663   ValID ID;
5664   if (FunctionName.empty()) {
5665     ID.Kind = ValID::t_GlobalID;
5666     ID.UIntVal = NumberedVals.size() - 1;
5667   } else {
5668     ID.Kind = ValID::t_GlobalName;
5669     ID.StrVal = FunctionName;
5670   }
5671   auto Blocks = ForwardRefBlockAddresses.find(ID);
5672   if (Blocks != ForwardRefBlockAddresses.end())
5673     return error(Blocks->first.Loc,
5674                  "cannot take blockaddress inside a declaration");
5675   return false;
5676 }
5677 
5678 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5679   ValID ID;
5680   if (FunctionNumber == -1) {
5681     ID.Kind = ValID::t_GlobalName;
5682     ID.StrVal = std::string(F.getName());
5683   } else {
5684     ID.Kind = ValID::t_GlobalID;
5685     ID.UIntVal = FunctionNumber;
5686   }
5687 
5688   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5689   if (Blocks == P.ForwardRefBlockAddresses.end())
5690     return false;
5691 
5692   for (const auto &I : Blocks->second) {
5693     const ValID &BBID = I.first;
5694     GlobalValue *GV = I.second;
5695 
5696     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5697            "Expected local id or name");
5698     BasicBlock *BB;
5699     if (BBID.Kind == ValID::t_LocalName)
5700       BB = getBB(BBID.StrVal, BBID.Loc);
5701     else
5702       BB = getBB(BBID.UIntVal, BBID.Loc);
5703     if (!BB)
5704       return P.error(BBID.Loc, "referenced value is not a basic block");
5705 
5706     Value *ResolvedVal = BlockAddress::get(&F, BB);
5707     ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
5708                                            ResolvedVal);
5709     if (!ResolvedVal)
5710       return true;
5711     GV->replaceAllUsesWith(ResolvedVal);
5712     GV->eraseFromParent();
5713   }
5714 
5715   P.ForwardRefBlockAddresses.erase(Blocks);
5716   return false;
5717 }
5718 
5719 /// parseFunctionBody
5720 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
5721 bool LLParser::parseFunctionBody(Function &Fn) {
5722   if (Lex.getKind() != lltok::lbrace)
5723     return tokError("expected '{' in function body");
5724   Lex.Lex();  // eat the {.
5725 
5726   int FunctionNumber = -1;
5727   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5728 
5729   PerFunctionState PFS(*this, Fn, FunctionNumber);
5730 
5731   // Resolve block addresses and allow basic blocks to be forward-declared
5732   // within this function.
5733   if (PFS.resolveForwardRefBlockAddresses())
5734     return true;
5735   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5736 
5737   // We need at least one basic block.
5738   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5739     return tokError("function body requires at least one basic block");
5740 
5741   while (Lex.getKind() != lltok::rbrace &&
5742          Lex.getKind() != lltok::kw_uselistorder)
5743     if (parseBasicBlock(PFS))
5744       return true;
5745 
5746   while (Lex.getKind() != lltok::rbrace)
5747     if (parseUseListOrder(&PFS))
5748       return true;
5749 
5750   // Eat the }.
5751   Lex.Lex();
5752 
5753   // Verify function is ok.
5754   return PFS.finishFunction();
5755 }
5756 
5757 /// parseBasicBlock
5758 ///   ::= (LabelStr|LabelID)? Instruction*
5759 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
5760   // If this basic block starts out with a name, remember it.
5761   std::string Name;
5762   int NameID = -1;
5763   LocTy NameLoc = Lex.getLoc();
5764   if (Lex.getKind() == lltok::LabelStr) {
5765     Name = Lex.getStrVal();
5766     Lex.Lex();
5767   } else if (Lex.getKind() == lltok::LabelID) {
5768     NameID = Lex.getUIntVal();
5769     Lex.Lex();
5770   }
5771 
5772   BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
5773   if (!BB)
5774     return true;
5775 
5776   std::string NameStr;
5777 
5778   // parse the instructions in this block until we get a terminator.
5779   Instruction *Inst;
5780   do {
5781     // This instruction may have three possibilities for a name: a) none
5782     // specified, b) name specified "%foo =", c) number specified: "%4 =".
5783     LocTy NameLoc = Lex.getLoc();
5784     int NameID = -1;
5785     NameStr = "";
5786 
5787     if (Lex.getKind() == lltok::LocalVarID) {
5788       NameID = Lex.getUIntVal();
5789       Lex.Lex();
5790       if (parseToken(lltok::equal, "expected '=' after instruction id"))
5791         return true;
5792     } else if (Lex.getKind() == lltok::LocalVar) {
5793       NameStr = Lex.getStrVal();
5794       Lex.Lex();
5795       if (parseToken(lltok::equal, "expected '=' after instruction name"))
5796         return true;
5797     }
5798 
5799     switch (parseInstruction(Inst, BB, PFS)) {
5800     default:
5801       llvm_unreachable("Unknown parseInstruction result!");
5802     case InstError: return true;
5803     case InstNormal:
5804       BB->getInstList().push_back(Inst);
5805 
5806       // With a normal result, we check to see if the instruction is followed by
5807       // a comma and metadata.
5808       if (EatIfPresent(lltok::comma))
5809         if (parseInstructionMetadata(*Inst))
5810           return true;
5811       break;
5812     case InstExtraComma:
5813       BB->getInstList().push_back(Inst);
5814 
5815       // If the instruction parser ate an extra comma at the end of it, it
5816       // *must* be followed by metadata.
5817       if (parseInstructionMetadata(*Inst))
5818         return true;
5819       break;
5820     }
5821 
5822     // Set the name on the instruction.
5823     if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
5824       return true;
5825   } while (!Inst->isTerminator());
5826 
5827   return false;
5828 }
5829 
5830 //===----------------------------------------------------------------------===//
5831 // Instruction Parsing.
5832 //===----------------------------------------------------------------------===//
5833 
5834 /// parseInstruction - parse one of the many different instructions.
5835 ///
5836 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
5837                                PerFunctionState &PFS) {
5838   lltok::Kind Token = Lex.getKind();
5839   if (Token == lltok::Eof)
5840     return tokError("found end of file when expecting more instructions");
5841   LocTy Loc = Lex.getLoc();
5842   unsigned KeywordVal = Lex.getUIntVal();
5843   Lex.Lex();  // Eat the keyword.
5844 
5845   switch (Token) {
5846   default:
5847     return error(Loc, "expected instruction opcode");
5848   // Terminator Instructions.
5849   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5850   case lltok::kw_ret:
5851     return parseRet(Inst, BB, PFS);
5852   case lltok::kw_br:
5853     return parseBr(Inst, PFS);
5854   case lltok::kw_switch:
5855     return parseSwitch(Inst, PFS);
5856   case lltok::kw_indirectbr:
5857     return parseIndirectBr(Inst, PFS);
5858   case lltok::kw_invoke:
5859     return parseInvoke(Inst, PFS);
5860   case lltok::kw_resume:
5861     return parseResume(Inst, PFS);
5862   case lltok::kw_cleanupret:
5863     return parseCleanupRet(Inst, PFS);
5864   case lltok::kw_catchret:
5865     return parseCatchRet(Inst, PFS);
5866   case lltok::kw_catchswitch:
5867     return parseCatchSwitch(Inst, PFS);
5868   case lltok::kw_catchpad:
5869     return parseCatchPad(Inst, PFS);
5870   case lltok::kw_cleanuppad:
5871     return parseCleanupPad(Inst, PFS);
5872   case lltok::kw_callbr:
5873     return parseCallBr(Inst, PFS);
5874   // Unary Operators.
5875   case lltok::kw_fneg: {
5876     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5877     int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
5878     if (Res != 0)
5879       return Res;
5880     if (FMF.any())
5881       Inst->setFastMathFlags(FMF);
5882     return false;
5883   }
5884   // Binary Operators.
5885   case lltok::kw_add:
5886   case lltok::kw_sub:
5887   case lltok::kw_mul:
5888   case lltok::kw_shl: {
5889     bool NUW = EatIfPresent(lltok::kw_nuw);
5890     bool NSW = EatIfPresent(lltok::kw_nsw);
5891     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5892 
5893     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
5894       return true;
5895 
5896     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5897     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5898     return false;
5899   }
5900   case lltok::kw_fadd:
5901   case lltok::kw_fsub:
5902   case lltok::kw_fmul:
5903   case lltok::kw_fdiv:
5904   case lltok::kw_frem: {
5905     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5906     int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
5907     if (Res != 0)
5908       return Res;
5909     if (FMF.any())
5910       Inst->setFastMathFlags(FMF);
5911     return 0;
5912   }
5913 
5914   case lltok::kw_sdiv:
5915   case lltok::kw_udiv:
5916   case lltok::kw_lshr:
5917   case lltok::kw_ashr: {
5918     bool Exact = EatIfPresent(lltok::kw_exact);
5919 
5920     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
5921       return true;
5922     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5923     return false;
5924   }
5925 
5926   case lltok::kw_urem:
5927   case lltok::kw_srem:
5928     return parseArithmetic(Inst, PFS, KeywordVal,
5929                            /*IsFP*/ false);
5930   case lltok::kw_and:
5931   case lltok::kw_or:
5932   case lltok::kw_xor:
5933     return parseLogical(Inst, PFS, KeywordVal);
5934   case lltok::kw_icmp:
5935     return parseCompare(Inst, PFS, KeywordVal);
5936   case lltok::kw_fcmp: {
5937     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5938     int Res = parseCompare(Inst, PFS, KeywordVal);
5939     if (Res != 0)
5940       return Res;
5941     if (FMF.any())
5942       Inst->setFastMathFlags(FMF);
5943     return 0;
5944   }
5945 
5946   // Casts.
5947   case lltok::kw_trunc:
5948   case lltok::kw_zext:
5949   case lltok::kw_sext:
5950   case lltok::kw_fptrunc:
5951   case lltok::kw_fpext:
5952   case lltok::kw_bitcast:
5953   case lltok::kw_addrspacecast:
5954   case lltok::kw_uitofp:
5955   case lltok::kw_sitofp:
5956   case lltok::kw_fptoui:
5957   case lltok::kw_fptosi:
5958   case lltok::kw_inttoptr:
5959   case lltok::kw_ptrtoint:
5960     return parseCast(Inst, PFS, KeywordVal);
5961   // Other.
5962   case lltok::kw_select: {
5963     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5964     int Res = parseSelect(Inst, PFS);
5965     if (Res != 0)
5966       return Res;
5967     if (FMF.any()) {
5968       if (!isa<FPMathOperator>(Inst))
5969         return error(Loc, "fast-math-flags specified for select without "
5970                           "floating-point scalar or vector return type");
5971       Inst->setFastMathFlags(FMF);
5972     }
5973     return 0;
5974   }
5975   case lltok::kw_va_arg:
5976     return parseVAArg(Inst, PFS);
5977   case lltok::kw_extractelement:
5978     return parseExtractElement(Inst, PFS);
5979   case lltok::kw_insertelement:
5980     return parseInsertElement(Inst, PFS);
5981   case lltok::kw_shufflevector:
5982     return parseShuffleVector(Inst, PFS);
5983   case lltok::kw_phi: {
5984     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5985     int Res = parsePHI(Inst, PFS);
5986     if (Res != 0)
5987       return Res;
5988     if (FMF.any()) {
5989       if (!isa<FPMathOperator>(Inst))
5990         return error(Loc, "fast-math-flags specified for phi without "
5991                           "floating-point scalar or vector return type");
5992       Inst->setFastMathFlags(FMF);
5993     }
5994     return 0;
5995   }
5996   case lltok::kw_landingpad:
5997     return parseLandingPad(Inst, PFS);
5998   case lltok::kw_freeze:
5999     return parseFreeze(Inst, PFS);
6000   // Call.
6001   case lltok::kw_call:
6002     return parseCall(Inst, PFS, CallInst::TCK_None);
6003   case lltok::kw_tail:
6004     return parseCall(Inst, PFS, CallInst::TCK_Tail);
6005   case lltok::kw_musttail:
6006     return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6007   case lltok::kw_notail:
6008     return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6009   // Memory.
6010   case lltok::kw_alloca:
6011     return parseAlloc(Inst, PFS);
6012   case lltok::kw_load:
6013     return parseLoad(Inst, PFS);
6014   case lltok::kw_store:
6015     return parseStore(Inst, PFS);
6016   case lltok::kw_cmpxchg:
6017     return parseCmpXchg(Inst, PFS);
6018   case lltok::kw_atomicrmw:
6019     return parseAtomicRMW(Inst, PFS);
6020   case lltok::kw_fence:
6021     return parseFence(Inst, PFS);
6022   case lltok::kw_getelementptr:
6023     return parseGetElementPtr(Inst, PFS);
6024   case lltok::kw_extractvalue:
6025     return parseExtractValue(Inst, PFS);
6026   case lltok::kw_insertvalue:
6027     return parseInsertValue(Inst, PFS);
6028   }
6029 }
6030 
6031 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6032 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6033   if (Opc == Instruction::FCmp) {
6034     switch (Lex.getKind()) {
6035     default:
6036       return tokError("expected fcmp predicate (e.g. 'oeq')");
6037     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6038     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6039     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6040     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6041     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6042     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6043     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6044     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6045     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6046     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6047     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6048     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6049     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6050     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6051     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6052     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6053     }
6054   } else {
6055     switch (Lex.getKind()) {
6056     default:
6057       return tokError("expected icmp predicate (e.g. 'eq')");
6058     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
6059     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
6060     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6061     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6062     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6063     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6064     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6065     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6066     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6067     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6068     }
6069   }
6070   Lex.Lex();
6071   return false;
6072 }
6073 
6074 //===----------------------------------------------------------------------===//
6075 // Terminator Instructions.
6076 //===----------------------------------------------------------------------===//
6077 
6078 /// parseRet - parse a return instruction.
6079 ///   ::= 'ret' void (',' !dbg, !1)*
6080 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
6081 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6082                         PerFunctionState &PFS) {
6083   SMLoc TypeLoc = Lex.getLoc();
6084   Type *Ty = nullptr;
6085   if (parseType(Ty, true /*void allowed*/))
6086     return true;
6087 
6088   Type *ResType = PFS.getFunction().getReturnType();
6089 
6090   if (Ty->isVoidTy()) {
6091     if (!ResType->isVoidTy())
6092       return error(TypeLoc, "value doesn't match function result type '" +
6093                                 getTypeString(ResType) + "'");
6094 
6095     Inst = ReturnInst::Create(Context);
6096     return false;
6097   }
6098 
6099   Value *RV;
6100   if (parseValue(Ty, RV, PFS))
6101     return true;
6102 
6103   if (ResType != RV->getType())
6104     return error(TypeLoc, "value doesn't match function result type '" +
6105                               getTypeString(ResType) + "'");
6106 
6107   Inst = ReturnInst::Create(Context, RV);
6108   return false;
6109 }
6110 
6111 /// parseBr
6112 ///   ::= 'br' TypeAndValue
6113 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6114 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6115   LocTy Loc, Loc2;
6116   Value *Op0;
6117   BasicBlock *Op1, *Op2;
6118   if (parseTypeAndValue(Op0, Loc, PFS))
6119     return true;
6120 
6121   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6122     Inst = BranchInst::Create(BB);
6123     return false;
6124   }
6125 
6126   if (Op0->getType() != Type::getInt1Ty(Context))
6127     return error(Loc, "branch condition must have 'i1' type");
6128 
6129   if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6130       parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6131       parseToken(lltok::comma, "expected ',' after true destination") ||
6132       parseTypeAndBasicBlock(Op2, Loc2, PFS))
6133     return true;
6134 
6135   Inst = BranchInst::Create(Op1, Op2, Op0);
6136   return false;
6137 }
6138 
6139 /// parseSwitch
6140 ///  Instruction
6141 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6142 ///  JumpTable
6143 ///    ::= (TypeAndValue ',' TypeAndValue)*
6144 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6145   LocTy CondLoc, BBLoc;
6146   Value *Cond;
6147   BasicBlock *DefaultBB;
6148   if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6149       parseToken(lltok::comma, "expected ',' after switch condition") ||
6150       parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6151       parseToken(lltok::lsquare, "expected '[' with switch table"))
6152     return true;
6153 
6154   if (!Cond->getType()->isIntegerTy())
6155     return error(CondLoc, "switch condition must have integer type");
6156 
6157   // parse the jump table pairs.
6158   SmallPtrSet<Value*, 32> SeenCases;
6159   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6160   while (Lex.getKind() != lltok::rsquare) {
6161     Value *Constant;
6162     BasicBlock *DestBB;
6163 
6164     if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6165         parseToken(lltok::comma, "expected ',' after case value") ||
6166         parseTypeAndBasicBlock(DestBB, PFS))
6167       return true;
6168 
6169     if (!SeenCases.insert(Constant).second)
6170       return error(CondLoc, "duplicate case value in switch");
6171     if (!isa<ConstantInt>(Constant))
6172       return error(CondLoc, "case value is not a constant integer");
6173 
6174     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6175   }
6176 
6177   Lex.Lex();  // Eat the ']'.
6178 
6179   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6180   for (unsigned i = 0, e = Table.size(); i != e; ++i)
6181     SI->addCase(Table[i].first, Table[i].second);
6182   Inst = SI;
6183   return false;
6184 }
6185 
6186 /// parseIndirectBr
6187 ///  Instruction
6188 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6189 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6190   LocTy AddrLoc;
6191   Value *Address;
6192   if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6193       parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6194       parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6195     return true;
6196 
6197   if (!Address->getType()->isPointerTy())
6198     return error(AddrLoc, "indirectbr address must have pointer type");
6199 
6200   // parse the destination list.
6201   SmallVector<BasicBlock*, 16> DestList;
6202 
6203   if (Lex.getKind() != lltok::rsquare) {
6204     BasicBlock *DestBB;
6205     if (parseTypeAndBasicBlock(DestBB, PFS))
6206       return true;
6207     DestList.push_back(DestBB);
6208 
6209     while (EatIfPresent(lltok::comma)) {
6210       if (parseTypeAndBasicBlock(DestBB, PFS))
6211         return true;
6212       DestList.push_back(DestBB);
6213     }
6214   }
6215 
6216   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6217     return true;
6218 
6219   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6220   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6221     IBI->addDestination(DestList[i]);
6222   Inst = IBI;
6223   return false;
6224 }
6225 
6226 /// parseInvoke
6227 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6228 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6229 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6230   LocTy CallLoc = Lex.getLoc();
6231   AttrBuilder RetAttrs, FnAttrs;
6232   std::vector<unsigned> FwdRefAttrGrps;
6233   LocTy NoBuiltinLoc;
6234   unsigned CC;
6235   unsigned InvokeAddrSpace;
6236   Type *RetType = nullptr;
6237   LocTy RetTypeLoc;
6238   ValID CalleeID;
6239   SmallVector<ParamInfo, 16> ArgList;
6240   SmallVector<OperandBundleDef, 2> BundleList;
6241 
6242   BasicBlock *NormalBB, *UnwindBB;
6243   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6244       parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6245       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6246       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6247       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6248                                  NoBuiltinLoc) ||
6249       parseOptionalOperandBundles(BundleList, PFS) ||
6250       parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6251       parseTypeAndBasicBlock(NormalBB, PFS) ||
6252       parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6253       parseTypeAndBasicBlock(UnwindBB, PFS))
6254     return true;
6255 
6256   // If RetType is a non-function pointer type, then this is the short syntax
6257   // for the call, which means that RetType is just the return type.  Infer the
6258   // rest of the function argument types from the arguments that are present.
6259   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6260   if (!Ty) {
6261     // Pull out the types of all of the arguments...
6262     std::vector<Type*> ParamTypes;
6263     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6264       ParamTypes.push_back(ArgList[i].V->getType());
6265 
6266     if (!FunctionType::isValidReturnType(RetType))
6267       return error(RetTypeLoc, "Invalid result type for LLVM function");
6268 
6269     Ty = FunctionType::get(RetType, ParamTypes, false);
6270   }
6271 
6272   CalleeID.FTy = Ty;
6273 
6274   // Look up the callee.
6275   Value *Callee;
6276   if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6277                           Callee, &PFS))
6278     return true;
6279 
6280   // Set up the Attribute for the function.
6281   SmallVector<Value *, 8> Args;
6282   SmallVector<AttributeSet, 8> ArgAttrs;
6283 
6284   // Loop through FunctionType's arguments and ensure they are specified
6285   // correctly.  Also, gather any parameter attributes.
6286   FunctionType::param_iterator I = Ty->param_begin();
6287   FunctionType::param_iterator E = Ty->param_end();
6288   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6289     Type *ExpectedTy = nullptr;
6290     if (I != E) {
6291       ExpectedTy = *I++;
6292     } else if (!Ty->isVarArg()) {
6293       return error(ArgList[i].Loc, "too many arguments specified");
6294     }
6295 
6296     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6297       return error(ArgList[i].Loc, "argument is not of expected type '" +
6298                                        getTypeString(ExpectedTy) + "'");
6299     Args.push_back(ArgList[i].V);
6300     ArgAttrs.push_back(ArgList[i].Attrs);
6301   }
6302 
6303   if (I != E)
6304     return error(CallLoc, "not enough parameters specified for call");
6305 
6306   if (FnAttrs.hasAlignmentAttr())
6307     return error(CallLoc, "invoke instructions may not have an alignment");
6308 
6309   // Finish off the Attribute and check them
6310   AttributeList PAL =
6311       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6312                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6313 
6314   InvokeInst *II =
6315       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6316   II->setCallingConv(CC);
6317   II->setAttributes(PAL);
6318   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6319   Inst = II;
6320   return false;
6321 }
6322 
6323 /// parseResume
6324 ///   ::= 'resume' TypeAndValue
6325 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6326   Value *Exn; LocTy ExnLoc;
6327   if (parseTypeAndValue(Exn, ExnLoc, PFS))
6328     return true;
6329 
6330   ResumeInst *RI = ResumeInst::Create(Exn);
6331   Inst = RI;
6332   return false;
6333 }
6334 
6335 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6336                                   PerFunctionState &PFS) {
6337   if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6338     return true;
6339 
6340   while (Lex.getKind() != lltok::rsquare) {
6341     // If this isn't the first argument, we need a comma.
6342     if (!Args.empty() &&
6343         parseToken(lltok::comma, "expected ',' in argument list"))
6344       return true;
6345 
6346     // parse the argument.
6347     LocTy ArgLoc;
6348     Type *ArgTy = nullptr;
6349     if (parseType(ArgTy, ArgLoc))
6350       return true;
6351 
6352     Value *V;
6353     if (ArgTy->isMetadataTy()) {
6354       if (parseMetadataAsValue(V, PFS))
6355         return true;
6356     } else {
6357       if (parseValue(ArgTy, V, PFS))
6358         return true;
6359     }
6360     Args.push_back(V);
6361   }
6362 
6363   Lex.Lex();  // Lex the ']'.
6364   return false;
6365 }
6366 
6367 /// parseCleanupRet
6368 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6369 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6370   Value *CleanupPad = nullptr;
6371 
6372   if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6373     return true;
6374 
6375   if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6376     return true;
6377 
6378   if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6379     return true;
6380 
6381   BasicBlock *UnwindBB = nullptr;
6382   if (Lex.getKind() == lltok::kw_to) {
6383     Lex.Lex();
6384     if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6385       return true;
6386   } else {
6387     if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6388       return true;
6389     }
6390   }
6391 
6392   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6393   return false;
6394 }
6395 
6396 /// parseCatchRet
6397 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
6398 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6399   Value *CatchPad = nullptr;
6400 
6401   if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6402     return true;
6403 
6404   if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6405     return true;
6406 
6407   BasicBlock *BB;
6408   if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6409       parseTypeAndBasicBlock(BB, PFS))
6410     return true;
6411 
6412   Inst = CatchReturnInst::Create(CatchPad, BB);
6413   return false;
6414 }
6415 
6416 /// parseCatchSwitch
6417 ///   ::= 'catchswitch' within Parent
6418 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6419   Value *ParentPad;
6420 
6421   if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6422     return true;
6423 
6424   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6425       Lex.getKind() != lltok::LocalVarID)
6426     return tokError("expected scope value for catchswitch");
6427 
6428   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6429     return true;
6430 
6431   if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6432     return true;
6433 
6434   SmallVector<BasicBlock *, 32> Table;
6435   do {
6436     BasicBlock *DestBB;
6437     if (parseTypeAndBasicBlock(DestBB, PFS))
6438       return true;
6439     Table.push_back(DestBB);
6440   } while (EatIfPresent(lltok::comma));
6441 
6442   if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6443     return true;
6444 
6445   if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6446     return true;
6447 
6448   BasicBlock *UnwindBB = nullptr;
6449   if (EatIfPresent(lltok::kw_to)) {
6450     if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6451       return true;
6452   } else {
6453     if (parseTypeAndBasicBlock(UnwindBB, PFS))
6454       return true;
6455   }
6456 
6457   auto *CatchSwitch =
6458       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6459   for (BasicBlock *DestBB : Table)
6460     CatchSwitch->addHandler(DestBB);
6461   Inst = CatchSwitch;
6462   return false;
6463 }
6464 
6465 /// parseCatchPad
6466 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6467 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6468   Value *CatchSwitch = nullptr;
6469 
6470   if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6471     return true;
6472 
6473   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6474     return tokError("expected scope value for catchpad");
6475 
6476   if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6477     return true;
6478 
6479   SmallVector<Value *, 8> Args;
6480   if (parseExceptionArgs(Args, PFS))
6481     return true;
6482 
6483   Inst = CatchPadInst::Create(CatchSwitch, Args);
6484   return false;
6485 }
6486 
6487 /// parseCleanupPad
6488 ///   ::= 'cleanuppad' within Parent ParamList
6489 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6490   Value *ParentPad = nullptr;
6491 
6492   if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6493     return true;
6494 
6495   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6496       Lex.getKind() != lltok::LocalVarID)
6497     return tokError("expected scope value for cleanuppad");
6498 
6499   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6500     return true;
6501 
6502   SmallVector<Value *, 8> Args;
6503   if (parseExceptionArgs(Args, PFS))
6504     return true;
6505 
6506   Inst = CleanupPadInst::Create(ParentPad, Args);
6507   return false;
6508 }
6509 
6510 //===----------------------------------------------------------------------===//
6511 // Unary Operators.
6512 //===----------------------------------------------------------------------===//
6513 
6514 /// parseUnaryOp
6515 ///  ::= UnaryOp TypeAndValue ',' Value
6516 ///
6517 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6518 /// operand is allowed.
6519 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6520                             unsigned Opc, bool IsFP) {
6521   LocTy Loc; Value *LHS;
6522   if (parseTypeAndValue(LHS, Loc, PFS))
6523     return true;
6524 
6525   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6526                     : LHS->getType()->isIntOrIntVectorTy();
6527 
6528   if (!Valid)
6529     return error(Loc, "invalid operand type for instruction");
6530 
6531   Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6532   return false;
6533 }
6534 
6535 /// parseCallBr
6536 ///   ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6537 ///       OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6538 ///       '[' LabelList ']'
6539 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6540   LocTy CallLoc = Lex.getLoc();
6541   AttrBuilder RetAttrs, FnAttrs;
6542   std::vector<unsigned> FwdRefAttrGrps;
6543   LocTy NoBuiltinLoc;
6544   unsigned CC;
6545   Type *RetType = nullptr;
6546   LocTy RetTypeLoc;
6547   ValID CalleeID;
6548   SmallVector<ParamInfo, 16> ArgList;
6549   SmallVector<OperandBundleDef, 2> BundleList;
6550 
6551   BasicBlock *DefaultDest;
6552   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6553       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6554       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6555       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6556                                  NoBuiltinLoc) ||
6557       parseOptionalOperandBundles(BundleList, PFS) ||
6558       parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6559       parseTypeAndBasicBlock(DefaultDest, PFS) ||
6560       parseToken(lltok::lsquare, "expected '[' in callbr"))
6561     return true;
6562 
6563   // parse the destination list.
6564   SmallVector<BasicBlock *, 16> IndirectDests;
6565 
6566   if (Lex.getKind() != lltok::rsquare) {
6567     BasicBlock *DestBB;
6568     if (parseTypeAndBasicBlock(DestBB, PFS))
6569       return true;
6570     IndirectDests.push_back(DestBB);
6571 
6572     while (EatIfPresent(lltok::comma)) {
6573       if (parseTypeAndBasicBlock(DestBB, PFS))
6574         return true;
6575       IndirectDests.push_back(DestBB);
6576     }
6577   }
6578 
6579   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6580     return true;
6581 
6582   // If RetType is a non-function pointer type, then this is the short syntax
6583   // for the call, which means that RetType is just the return type.  Infer the
6584   // rest of the function argument types from the arguments that are present.
6585   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6586   if (!Ty) {
6587     // Pull out the types of all of the arguments...
6588     std::vector<Type *> ParamTypes;
6589     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6590       ParamTypes.push_back(ArgList[i].V->getType());
6591 
6592     if (!FunctionType::isValidReturnType(RetType))
6593       return error(RetTypeLoc, "Invalid result type for LLVM function");
6594 
6595     Ty = FunctionType::get(RetType, ParamTypes, false);
6596   }
6597 
6598   CalleeID.FTy = Ty;
6599 
6600   // Look up the callee.
6601   Value *Callee;
6602   if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6603     return true;
6604 
6605   // Set up the Attribute for the function.
6606   SmallVector<Value *, 8> Args;
6607   SmallVector<AttributeSet, 8> ArgAttrs;
6608 
6609   // Loop through FunctionType's arguments and ensure they are specified
6610   // correctly.  Also, gather any parameter attributes.
6611   FunctionType::param_iterator I = Ty->param_begin();
6612   FunctionType::param_iterator E = Ty->param_end();
6613   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6614     Type *ExpectedTy = nullptr;
6615     if (I != E) {
6616       ExpectedTy = *I++;
6617     } else if (!Ty->isVarArg()) {
6618       return error(ArgList[i].Loc, "too many arguments specified");
6619     }
6620 
6621     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6622       return error(ArgList[i].Loc, "argument is not of expected type '" +
6623                                        getTypeString(ExpectedTy) + "'");
6624     Args.push_back(ArgList[i].V);
6625     ArgAttrs.push_back(ArgList[i].Attrs);
6626   }
6627 
6628   if (I != E)
6629     return error(CallLoc, "not enough parameters specified for call");
6630 
6631   if (FnAttrs.hasAlignmentAttr())
6632     return error(CallLoc, "callbr instructions may not have an alignment");
6633 
6634   // Finish off the Attribute and check them
6635   AttributeList PAL =
6636       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6637                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6638 
6639   CallBrInst *CBI =
6640       CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6641                          BundleList);
6642   CBI->setCallingConv(CC);
6643   CBI->setAttributes(PAL);
6644   ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6645   Inst = CBI;
6646   return false;
6647 }
6648 
6649 //===----------------------------------------------------------------------===//
6650 // Binary Operators.
6651 //===----------------------------------------------------------------------===//
6652 
6653 /// parseArithmetic
6654 ///  ::= ArithmeticOps TypeAndValue ',' Value
6655 ///
6656 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6657 /// operand is allowed.
6658 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6659                                unsigned Opc, bool IsFP) {
6660   LocTy Loc; Value *LHS, *RHS;
6661   if (parseTypeAndValue(LHS, Loc, PFS) ||
6662       parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6663       parseValue(LHS->getType(), RHS, PFS))
6664     return true;
6665 
6666   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6667                     : LHS->getType()->isIntOrIntVectorTy();
6668 
6669   if (!Valid)
6670     return error(Loc, "invalid operand type for instruction");
6671 
6672   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6673   return false;
6674 }
6675 
6676 /// parseLogical
6677 ///  ::= ArithmeticOps TypeAndValue ',' Value {
6678 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6679                             unsigned Opc) {
6680   LocTy Loc; Value *LHS, *RHS;
6681   if (parseTypeAndValue(LHS, Loc, PFS) ||
6682       parseToken(lltok::comma, "expected ',' in logical operation") ||
6683       parseValue(LHS->getType(), RHS, PFS))
6684     return true;
6685 
6686   if (!LHS->getType()->isIntOrIntVectorTy())
6687     return error(Loc,
6688                  "instruction requires integer or integer vector operands");
6689 
6690   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6691   return false;
6692 }
6693 
6694 /// parseCompare
6695 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
6696 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
6697 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
6698                             unsigned Opc) {
6699   // parse the integer/fp comparison predicate.
6700   LocTy Loc;
6701   unsigned Pred;
6702   Value *LHS, *RHS;
6703   if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
6704       parseToken(lltok::comma, "expected ',' after compare value") ||
6705       parseValue(LHS->getType(), RHS, PFS))
6706     return true;
6707 
6708   if (Opc == Instruction::FCmp) {
6709     if (!LHS->getType()->isFPOrFPVectorTy())
6710       return error(Loc, "fcmp requires floating point operands");
6711     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6712   } else {
6713     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6714     if (!LHS->getType()->isIntOrIntVectorTy() &&
6715         !LHS->getType()->isPtrOrPtrVectorTy())
6716       return error(Loc, "icmp requires integer operands");
6717     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6718   }
6719   return false;
6720 }
6721 
6722 //===----------------------------------------------------------------------===//
6723 // Other Instructions.
6724 //===----------------------------------------------------------------------===//
6725 
6726 /// parseCast
6727 ///   ::= CastOpc TypeAndValue 'to' Type
6728 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
6729                          unsigned Opc) {
6730   LocTy Loc;
6731   Value *Op;
6732   Type *DestTy = nullptr;
6733   if (parseTypeAndValue(Op, Loc, PFS) ||
6734       parseToken(lltok::kw_to, "expected 'to' after cast value") ||
6735       parseType(DestTy))
6736     return true;
6737 
6738   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6739     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6740     return error(Loc, "invalid cast opcode for cast from '" +
6741                           getTypeString(Op->getType()) + "' to '" +
6742                           getTypeString(DestTy) + "'");
6743   }
6744   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6745   return false;
6746 }
6747 
6748 /// parseSelect
6749 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6750 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6751   LocTy Loc;
6752   Value *Op0, *Op1, *Op2;
6753   if (parseTypeAndValue(Op0, Loc, PFS) ||
6754       parseToken(lltok::comma, "expected ',' after select condition") ||
6755       parseTypeAndValue(Op1, PFS) ||
6756       parseToken(lltok::comma, "expected ',' after select value") ||
6757       parseTypeAndValue(Op2, PFS))
6758     return true;
6759 
6760   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6761     return error(Loc, Reason);
6762 
6763   Inst = SelectInst::Create(Op0, Op1, Op2);
6764   return false;
6765 }
6766 
6767 /// parseVAArg
6768 ///   ::= 'va_arg' TypeAndValue ',' Type
6769 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
6770   Value *Op;
6771   Type *EltTy = nullptr;
6772   LocTy TypeLoc;
6773   if (parseTypeAndValue(Op, PFS) ||
6774       parseToken(lltok::comma, "expected ',' after vaarg operand") ||
6775       parseType(EltTy, TypeLoc))
6776     return true;
6777 
6778   if (!EltTy->isFirstClassType())
6779     return error(TypeLoc, "va_arg requires operand with first class type");
6780 
6781   Inst = new VAArgInst(Op, EltTy);
6782   return false;
6783 }
6784 
6785 /// parseExtractElement
6786 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
6787 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6788   LocTy Loc;
6789   Value *Op0, *Op1;
6790   if (parseTypeAndValue(Op0, Loc, PFS) ||
6791       parseToken(lltok::comma, "expected ',' after extract value") ||
6792       parseTypeAndValue(Op1, PFS))
6793     return true;
6794 
6795   if (!ExtractElementInst::isValidOperands(Op0, Op1))
6796     return error(Loc, "invalid extractelement operands");
6797 
6798   Inst = ExtractElementInst::Create(Op0, Op1);
6799   return false;
6800 }
6801 
6802 /// parseInsertElement
6803 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6804 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6805   LocTy Loc;
6806   Value *Op0, *Op1, *Op2;
6807   if (parseTypeAndValue(Op0, Loc, PFS) ||
6808       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6809       parseTypeAndValue(Op1, PFS) ||
6810       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6811       parseTypeAndValue(Op2, PFS))
6812     return true;
6813 
6814   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6815     return error(Loc, "invalid insertelement operands");
6816 
6817   Inst = InsertElementInst::Create(Op0, Op1, Op2);
6818   return false;
6819 }
6820 
6821 /// parseShuffleVector
6822 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6823 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6824   LocTy Loc;
6825   Value *Op0, *Op1, *Op2;
6826   if (parseTypeAndValue(Op0, Loc, PFS) ||
6827       parseToken(lltok::comma, "expected ',' after shuffle mask") ||
6828       parseTypeAndValue(Op1, PFS) ||
6829       parseToken(lltok::comma, "expected ',' after shuffle value") ||
6830       parseTypeAndValue(Op2, PFS))
6831     return true;
6832 
6833   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6834     return error(Loc, "invalid shufflevector operands");
6835 
6836   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6837   return false;
6838 }
6839 
6840 /// parsePHI
6841 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6842 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6843   Type *Ty = nullptr;  LocTy TypeLoc;
6844   Value *Op0, *Op1;
6845 
6846   if (parseType(Ty, TypeLoc) ||
6847       parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6848       parseValue(Ty, Op0, PFS) ||
6849       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6850       parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6851       parseToken(lltok::rsquare, "expected ']' in phi value list"))
6852     return true;
6853 
6854   bool AteExtraComma = false;
6855   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6856 
6857   while (true) {
6858     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6859 
6860     if (!EatIfPresent(lltok::comma))
6861       break;
6862 
6863     if (Lex.getKind() == lltok::MetadataVar) {
6864       AteExtraComma = true;
6865       break;
6866     }
6867 
6868     if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6869         parseValue(Ty, Op0, PFS) ||
6870         parseToken(lltok::comma, "expected ',' after insertelement value") ||
6871         parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6872         parseToken(lltok::rsquare, "expected ']' in phi value list"))
6873       return true;
6874   }
6875 
6876   if (!Ty->isFirstClassType())
6877     return error(TypeLoc, "phi node must have first class type");
6878 
6879   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6880   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6881     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6882   Inst = PN;
6883   return AteExtraComma ? InstExtraComma : InstNormal;
6884 }
6885 
6886 /// parseLandingPad
6887 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6888 /// Clause
6889 ///   ::= 'catch' TypeAndValue
6890 ///   ::= 'filter'
6891 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6892 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6893   Type *Ty = nullptr; LocTy TyLoc;
6894 
6895   if (parseType(Ty, TyLoc))
6896     return true;
6897 
6898   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6899   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6900 
6901   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6902     LandingPadInst::ClauseType CT;
6903     if (EatIfPresent(lltok::kw_catch))
6904       CT = LandingPadInst::Catch;
6905     else if (EatIfPresent(lltok::kw_filter))
6906       CT = LandingPadInst::Filter;
6907     else
6908       return tokError("expected 'catch' or 'filter' clause type");
6909 
6910     Value *V;
6911     LocTy VLoc;
6912     if (parseTypeAndValue(V, VLoc, PFS))
6913       return true;
6914 
6915     // A 'catch' type expects a non-array constant. A filter clause expects an
6916     // array constant.
6917     if (CT == LandingPadInst::Catch) {
6918       if (isa<ArrayType>(V->getType()))
6919         error(VLoc, "'catch' clause has an invalid type");
6920     } else {
6921       if (!isa<ArrayType>(V->getType()))
6922         error(VLoc, "'filter' clause has an invalid type");
6923     }
6924 
6925     Constant *CV = dyn_cast<Constant>(V);
6926     if (!CV)
6927       return error(VLoc, "clause argument must be a constant");
6928     LP->addClause(CV);
6929   }
6930 
6931   Inst = LP.release();
6932   return false;
6933 }
6934 
6935 /// parseFreeze
6936 ///   ::= 'freeze' Type Value
6937 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
6938   LocTy Loc;
6939   Value *Op;
6940   if (parseTypeAndValue(Op, Loc, PFS))
6941     return true;
6942 
6943   Inst = new FreezeInst(Op);
6944   return false;
6945 }
6946 
6947 /// parseCall
6948 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
6949 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
6950 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6951 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
6952 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6953 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
6954 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
6955 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
6956 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
6957                          CallInst::TailCallKind TCK) {
6958   AttrBuilder RetAttrs, FnAttrs;
6959   std::vector<unsigned> FwdRefAttrGrps;
6960   LocTy BuiltinLoc;
6961   unsigned CallAddrSpace;
6962   unsigned CC;
6963   Type *RetType = nullptr;
6964   LocTy RetTypeLoc;
6965   ValID CalleeID;
6966   SmallVector<ParamInfo, 16> ArgList;
6967   SmallVector<OperandBundleDef, 2> BundleList;
6968   LocTy CallLoc = Lex.getLoc();
6969 
6970   if (TCK != CallInst::TCK_None &&
6971       parseToken(lltok::kw_call,
6972                  "expected 'tail call', 'musttail call', or 'notail call'"))
6973     return true;
6974 
6975   FastMathFlags FMF = EatFastMathFlagsIfPresent();
6976 
6977   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6978       parseOptionalProgramAddrSpace(CallAddrSpace) ||
6979       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6980       parseValID(CalleeID, &PFS) ||
6981       parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6982                          PFS.getFunction().isVarArg()) ||
6983       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6984       parseOptionalOperandBundles(BundleList, PFS))
6985     return true;
6986 
6987   // If RetType is a non-function pointer type, then this is the short syntax
6988   // for the call, which means that RetType is just the return type.  Infer the
6989   // rest of the function argument types from the arguments that are present.
6990   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6991   if (!Ty) {
6992     // Pull out the types of all of the arguments...
6993     std::vector<Type*> ParamTypes;
6994     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6995       ParamTypes.push_back(ArgList[i].V->getType());
6996 
6997     if (!FunctionType::isValidReturnType(RetType))
6998       return error(RetTypeLoc, "Invalid result type for LLVM function");
6999 
7000     Ty = FunctionType::get(RetType, ParamTypes, false);
7001   }
7002 
7003   CalleeID.FTy = Ty;
7004 
7005   // Look up the callee.
7006   Value *Callee;
7007   if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7008                           &PFS))
7009     return true;
7010 
7011   // Set up the Attribute for the function.
7012   SmallVector<AttributeSet, 8> Attrs;
7013 
7014   SmallVector<Value*, 8> Args;
7015 
7016   // Loop through FunctionType's arguments and ensure they are specified
7017   // correctly.  Also, gather any parameter attributes.
7018   FunctionType::param_iterator I = Ty->param_begin();
7019   FunctionType::param_iterator E = Ty->param_end();
7020   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7021     Type *ExpectedTy = nullptr;
7022     if (I != E) {
7023       ExpectedTy = *I++;
7024     } else if (!Ty->isVarArg()) {
7025       return error(ArgList[i].Loc, "too many arguments specified");
7026     }
7027 
7028     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7029       return error(ArgList[i].Loc, "argument is not of expected type '" +
7030                                        getTypeString(ExpectedTy) + "'");
7031     Args.push_back(ArgList[i].V);
7032     Attrs.push_back(ArgList[i].Attrs);
7033   }
7034 
7035   if (I != E)
7036     return error(CallLoc, "not enough parameters specified for call");
7037 
7038   if (FnAttrs.hasAlignmentAttr())
7039     return error(CallLoc, "call instructions may not have an alignment");
7040 
7041   // Finish off the Attribute and check them
7042   AttributeList PAL =
7043       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7044                          AttributeSet::get(Context, RetAttrs), Attrs);
7045 
7046   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7047   CI->setTailCallKind(TCK);
7048   CI->setCallingConv(CC);
7049   if (FMF.any()) {
7050     if (!isa<FPMathOperator>(CI)) {
7051       CI->deleteValue();
7052       return error(CallLoc, "fast-math-flags specified for call without "
7053                             "floating-point scalar or vector return type");
7054     }
7055     CI->setFastMathFlags(FMF);
7056   }
7057   CI->setAttributes(PAL);
7058   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7059   Inst = CI;
7060   return false;
7061 }
7062 
7063 //===----------------------------------------------------------------------===//
7064 // Memory Instructions.
7065 //===----------------------------------------------------------------------===//
7066 
7067 /// parseAlloc
7068 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7069 ///       (',' 'align' i32)? (',', 'addrspace(n))?
7070 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7071   Value *Size = nullptr;
7072   LocTy SizeLoc, TyLoc, ASLoc;
7073   MaybeAlign Alignment;
7074   unsigned AddrSpace = 0;
7075   Type *Ty = nullptr;
7076 
7077   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7078   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7079 
7080   if (parseType(Ty, TyLoc))
7081     return true;
7082 
7083   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7084     return error(TyLoc, "invalid type for alloca");
7085 
7086   bool AteExtraComma = false;
7087   if (EatIfPresent(lltok::comma)) {
7088     if (Lex.getKind() == lltok::kw_align) {
7089       if (parseOptionalAlignment(Alignment))
7090         return true;
7091       if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7092         return true;
7093     } else if (Lex.getKind() == lltok::kw_addrspace) {
7094       ASLoc = Lex.getLoc();
7095       if (parseOptionalAddrSpace(AddrSpace))
7096         return true;
7097     } else if (Lex.getKind() == lltok::MetadataVar) {
7098       AteExtraComma = true;
7099     } else {
7100       if (parseTypeAndValue(Size, SizeLoc, PFS))
7101         return true;
7102       if (EatIfPresent(lltok::comma)) {
7103         if (Lex.getKind() == lltok::kw_align) {
7104           if (parseOptionalAlignment(Alignment))
7105             return true;
7106           if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7107             return true;
7108         } else if (Lex.getKind() == lltok::kw_addrspace) {
7109           ASLoc = Lex.getLoc();
7110           if (parseOptionalAddrSpace(AddrSpace))
7111             return true;
7112         } else if (Lex.getKind() == lltok::MetadataVar) {
7113           AteExtraComma = true;
7114         }
7115       }
7116     }
7117   }
7118 
7119   if (Size && !Size->getType()->isIntegerTy())
7120     return error(SizeLoc, "element count must have integer type");
7121 
7122   SmallPtrSet<Type *, 4> Visited;
7123   if (!Alignment && !Ty->isSized(&Visited))
7124     return error(TyLoc, "Cannot allocate unsized type");
7125   if (!Alignment)
7126     Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7127   AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7128   AI->setUsedWithInAlloca(IsInAlloca);
7129   AI->setSwiftError(IsSwiftError);
7130   Inst = AI;
7131   return AteExtraComma ? InstExtraComma : InstNormal;
7132 }
7133 
7134 /// parseLoad
7135 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7136 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
7137 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7138 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7139   Value *Val; LocTy Loc;
7140   MaybeAlign Alignment;
7141   bool AteExtraComma = false;
7142   bool isAtomic = false;
7143   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7144   SyncScope::ID SSID = SyncScope::System;
7145 
7146   if (Lex.getKind() == lltok::kw_atomic) {
7147     isAtomic = true;
7148     Lex.Lex();
7149   }
7150 
7151   bool isVolatile = false;
7152   if (Lex.getKind() == lltok::kw_volatile) {
7153     isVolatile = true;
7154     Lex.Lex();
7155   }
7156 
7157   Type *Ty;
7158   LocTy ExplicitTypeLoc = Lex.getLoc();
7159   if (parseType(Ty) ||
7160       parseToken(lltok::comma, "expected comma after load's type") ||
7161       parseTypeAndValue(Val, Loc, PFS) ||
7162       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7163       parseOptionalCommaAlign(Alignment, AteExtraComma))
7164     return true;
7165 
7166   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7167     return error(Loc, "load operand must be a pointer to a first class type");
7168   if (isAtomic && !Alignment)
7169     return error(Loc, "atomic load must have explicit non-zero alignment");
7170   if (Ordering == AtomicOrdering::Release ||
7171       Ordering == AtomicOrdering::AcquireRelease)
7172     return error(Loc, "atomic load cannot use Release ordering");
7173 
7174   if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
7175     return error(
7176         ExplicitTypeLoc,
7177         typeComparisonErrorMessage(
7178             "explicit pointee type doesn't match operand's pointee type", Ty,
7179             cast<PointerType>(Val->getType())->getElementType()));
7180   }
7181   SmallPtrSet<Type *, 4> Visited;
7182   if (!Alignment && !Ty->isSized(&Visited))
7183     return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7184   if (!Alignment)
7185     Alignment = M->getDataLayout().getABITypeAlign(Ty);
7186   Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7187   return AteExtraComma ? InstExtraComma : InstNormal;
7188 }
7189 
7190 /// parseStore
7191 
7192 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7193 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7194 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7195 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7196   Value *Val, *Ptr; LocTy Loc, PtrLoc;
7197   MaybeAlign Alignment;
7198   bool AteExtraComma = false;
7199   bool isAtomic = false;
7200   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7201   SyncScope::ID SSID = SyncScope::System;
7202 
7203   if (Lex.getKind() == lltok::kw_atomic) {
7204     isAtomic = true;
7205     Lex.Lex();
7206   }
7207 
7208   bool isVolatile = false;
7209   if (Lex.getKind() == lltok::kw_volatile) {
7210     isVolatile = true;
7211     Lex.Lex();
7212   }
7213 
7214   if (parseTypeAndValue(Val, Loc, PFS) ||
7215       parseToken(lltok::comma, "expected ',' after store operand") ||
7216       parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7217       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7218       parseOptionalCommaAlign(Alignment, AteExtraComma))
7219     return true;
7220 
7221   if (!Ptr->getType()->isPointerTy())
7222     return error(PtrLoc, "store operand must be a pointer");
7223   if (!Val->getType()->isFirstClassType())
7224     return error(Loc, "store operand must be a first class value");
7225   if (!cast<PointerType>(Ptr->getType())
7226            ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7227     return error(Loc, "stored value and pointer type do not match");
7228   if (isAtomic && !Alignment)
7229     return error(Loc, "atomic store must have explicit non-zero alignment");
7230   if (Ordering == AtomicOrdering::Acquire ||
7231       Ordering == AtomicOrdering::AcquireRelease)
7232     return error(Loc, "atomic store cannot use Acquire ordering");
7233   SmallPtrSet<Type *, 4> Visited;
7234   if (!Alignment && !Val->getType()->isSized(&Visited))
7235     return error(Loc, "storing unsized types is not allowed");
7236   if (!Alignment)
7237     Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7238 
7239   Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7240   return AteExtraComma ? InstExtraComma : InstNormal;
7241 }
7242 
7243 /// parseCmpXchg
7244 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7245 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7246 ///       'Align'?
7247 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7248   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7249   bool AteExtraComma = false;
7250   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7251   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7252   SyncScope::ID SSID = SyncScope::System;
7253   bool isVolatile = false;
7254   bool isWeak = false;
7255   MaybeAlign Alignment;
7256 
7257   if (EatIfPresent(lltok::kw_weak))
7258     isWeak = true;
7259 
7260   if (EatIfPresent(lltok::kw_volatile))
7261     isVolatile = true;
7262 
7263   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7264       parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7265       parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7266       parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7267       parseTypeAndValue(New, NewLoc, PFS) ||
7268       parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7269       parseOrdering(FailureOrdering) ||
7270       parseOptionalCommaAlign(Alignment, AteExtraComma))
7271     return true;
7272 
7273   if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7274     return tokError("invalid cmpxchg success ordering");
7275   if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7276     return tokError("invalid cmpxchg failure ordering");
7277   if (!Ptr->getType()->isPointerTy())
7278     return error(PtrLoc, "cmpxchg operand must be a pointer");
7279   if (!cast<PointerType>(Ptr->getType())
7280            ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
7281     return error(CmpLoc, "compare value and pointer type do not match");
7282   if (!cast<PointerType>(Ptr->getType())
7283            ->isOpaqueOrPointeeTypeMatches(New->getType()))
7284     return error(NewLoc, "new value and pointer type do not match");
7285   if (Cmp->getType() != New->getType())
7286     return error(NewLoc, "compare value and new value type do not match");
7287   if (!New->getType()->isFirstClassType())
7288     return error(NewLoc, "cmpxchg operand must be a first class value");
7289 
7290   const Align DefaultAlignment(
7291       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7292           Cmp->getType()));
7293 
7294   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
7295       Ptr, Cmp, New, Alignment.getValueOr(DefaultAlignment), SuccessOrdering,
7296       FailureOrdering, SSID);
7297   CXI->setVolatile(isVolatile);
7298   CXI->setWeak(isWeak);
7299 
7300   Inst = CXI;
7301   return AteExtraComma ? InstExtraComma : InstNormal;
7302 }
7303 
7304 /// parseAtomicRMW
7305 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7306 ///       'singlethread'? AtomicOrdering
7307 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7308   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7309   bool AteExtraComma = false;
7310   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7311   SyncScope::ID SSID = SyncScope::System;
7312   bool isVolatile = false;
7313   bool IsFP = false;
7314   AtomicRMWInst::BinOp Operation;
7315   MaybeAlign Alignment;
7316 
7317   if (EatIfPresent(lltok::kw_volatile))
7318     isVolatile = true;
7319 
7320   switch (Lex.getKind()) {
7321   default:
7322     return tokError("expected binary operation in atomicrmw");
7323   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7324   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7325   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7326   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7327   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7328   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7329   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7330   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7331   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7332   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7333   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7334   case lltok::kw_fadd:
7335     Operation = AtomicRMWInst::FAdd;
7336     IsFP = true;
7337     break;
7338   case lltok::kw_fsub:
7339     Operation = AtomicRMWInst::FSub;
7340     IsFP = true;
7341     break;
7342   }
7343   Lex.Lex();  // Eat the operation.
7344 
7345   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7346       parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7347       parseTypeAndValue(Val, ValLoc, PFS) ||
7348       parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7349       parseOptionalCommaAlign(Alignment, AteExtraComma))
7350     return true;
7351 
7352   if (Ordering == AtomicOrdering::Unordered)
7353     return tokError("atomicrmw cannot be unordered");
7354   if (!Ptr->getType()->isPointerTy())
7355     return error(PtrLoc, "atomicrmw operand must be a pointer");
7356   if (!cast<PointerType>(Ptr->getType())
7357            ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7358     return error(ValLoc, "atomicrmw value and pointer type do not match");
7359 
7360   if (Operation == AtomicRMWInst::Xchg) {
7361     if (!Val->getType()->isIntegerTy() &&
7362         !Val->getType()->isFloatingPointTy()) {
7363       return error(ValLoc,
7364                    "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7365                        " operand must be an integer or floating point type");
7366     }
7367   } else if (IsFP) {
7368     if (!Val->getType()->isFloatingPointTy()) {
7369       return error(ValLoc, "atomicrmw " +
7370                                AtomicRMWInst::getOperationName(Operation) +
7371                                " operand must be a floating point type");
7372     }
7373   } else {
7374     if (!Val->getType()->isIntegerTy()) {
7375       return error(ValLoc, "atomicrmw " +
7376                                AtomicRMWInst::getOperationName(Operation) +
7377                                " operand must be an integer");
7378     }
7379   }
7380 
7381   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7382   if (Size < 8 || (Size & (Size - 1)))
7383     return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7384                          " integer");
7385   const Align DefaultAlignment(
7386       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7387           Val->getType()));
7388   AtomicRMWInst *RMWI =
7389       new AtomicRMWInst(Operation, Ptr, Val,
7390                         Alignment.getValueOr(DefaultAlignment), Ordering, SSID);
7391   RMWI->setVolatile(isVolatile);
7392   Inst = RMWI;
7393   return AteExtraComma ? InstExtraComma : InstNormal;
7394 }
7395 
7396 /// parseFence
7397 ///   ::= 'fence' 'singlethread'? AtomicOrdering
7398 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7399   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7400   SyncScope::ID SSID = SyncScope::System;
7401   if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7402     return true;
7403 
7404   if (Ordering == AtomicOrdering::Unordered)
7405     return tokError("fence cannot be unordered");
7406   if (Ordering == AtomicOrdering::Monotonic)
7407     return tokError("fence cannot be monotonic");
7408 
7409   Inst = new FenceInst(Context, Ordering, SSID);
7410   return InstNormal;
7411 }
7412 
7413 /// parseGetElementPtr
7414 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7415 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7416   Value *Ptr = nullptr;
7417   Value *Val = nullptr;
7418   LocTy Loc, EltLoc;
7419 
7420   bool InBounds = EatIfPresent(lltok::kw_inbounds);
7421 
7422   Type *Ty = nullptr;
7423   LocTy ExplicitTypeLoc = Lex.getLoc();
7424   if (parseType(Ty) ||
7425       parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7426       parseTypeAndValue(Ptr, Loc, PFS))
7427     return true;
7428 
7429   Type *BaseType = Ptr->getType();
7430   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7431   if (!BasePointerType)
7432     return error(Loc, "base of getelementptr must be a pointer");
7433 
7434   if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
7435     return error(
7436         ExplicitTypeLoc,
7437         typeComparisonErrorMessage(
7438             "explicit pointee type doesn't match operand's pointee type", Ty,
7439             BasePointerType->getElementType()));
7440   }
7441 
7442   SmallVector<Value*, 16> Indices;
7443   bool AteExtraComma = false;
7444   // GEP returns a vector of pointers if at least one of parameters is a vector.
7445   // All vector parameters should have the same vector width.
7446   ElementCount GEPWidth = BaseType->isVectorTy()
7447                               ? cast<VectorType>(BaseType)->getElementCount()
7448                               : ElementCount::getFixed(0);
7449 
7450   while (EatIfPresent(lltok::comma)) {
7451     if (Lex.getKind() == lltok::MetadataVar) {
7452       AteExtraComma = true;
7453       break;
7454     }
7455     if (parseTypeAndValue(Val, EltLoc, PFS))
7456       return true;
7457     if (!Val->getType()->isIntOrIntVectorTy())
7458       return error(EltLoc, "getelementptr index must be an integer");
7459 
7460     if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7461       ElementCount ValNumEl = ValVTy->getElementCount();
7462       if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7463         return error(
7464             EltLoc,
7465             "getelementptr vector index has a wrong number of elements");
7466       GEPWidth = ValNumEl;
7467     }
7468     Indices.push_back(Val);
7469   }
7470 
7471   SmallPtrSet<Type*, 4> Visited;
7472   if (!Indices.empty() && !Ty->isSized(&Visited))
7473     return error(Loc, "base element of getelementptr must be sized");
7474 
7475   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7476     return error(Loc, "invalid getelementptr indices");
7477   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7478   if (InBounds)
7479     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7480   return AteExtraComma ? InstExtraComma : InstNormal;
7481 }
7482 
7483 /// parseExtractValue
7484 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
7485 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7486   Value *Val; LocTy Loc;
7487   SmallVector<unsigned, 4> Indices;
7488   bool AteExtraComma;
7489   if (parseTypeAndValue(Val, Loc, PFS) ||
7490       parseIndexList(Indices, AteExtraComma))
7491     return true;
7492 
7493   if (!Val->getType()->isAggregateType())
7494     return error(Loc, "extractvalue operand must be aggregate type");
7495 
7496   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7497     return error(Loc, "invalid indices for extractvalue");
7498   Inst = ExtractValueInst::Create(Val, Indices);
7499   return AteExtraComma ? InstExtraComma : InstNormal;
7500 }
7501 
7502 /// parseInsertValue
7503 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7504 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7505   Value *Val0, *Val1; LocTy Loc0, Loc1;
7506   SmallVector<unsigned, 4> Indices;
7507   bool AteExtraComma;
7508   if (parseTypeAndValue(Val0, Loc0, PFS) ||
7509       parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7510       parseTypeAndValue(Val1, Loc1, PFS) ||
7511       parseIndexList(Indices, AteExtraComma))
7512     return true;
7513 
7514   if (!Val0->getType()->isAggregateType())
7515     return error(Loc0, "insertvalue operand must be aggregate type");
7516 
7517   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7518   if (!IndexedType)
7519     return error(Loc0, "invalid indices for insertvalue");
7520   if (IndexedType != Val1->getType())
7521     return error(Loc1, "insertvalue operand and field disagree in type: '" +
7522                            getTypeString(Val1->getType()) + "' instead of '" +
7523                            getTypeString(IndexedType) + "'");
7524   Inst = InsertValueInst::Create(Val0, Val1, Indices);
7525   return AteExtraComma ? InstExtraComma : InstNormal;
7526 }
7527 
7528 //===----------------------------------------------------------------------===//
7529 // Embedded metadata.
7530 //===----------------------------------------------------------------------===//
7531 
7532 /// parseMDNodeVector
7533 ///   ::= { Element (',' Element)* }
7534 /// Element
7535 ///   ::= 'null' | TypeAndValue
7536 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7537   if (parseToken(lltok::lbrace, "expected '{' here"))
7538     return true;
7539 
7540   // Check for an empty list.
7541   if (EatIfPresent(lltok::rbrace))
7542     return false;
7543 
7544   do {
7545     // Null is a special case since it is typeless.
7546     if (EatIfPresent(lltok::kw_null)) {
7547       Elts.push_back(nullptr);
7548       continue;
7549     }
7550 
7551     Metadata *MD;
7552     if (parseMetadata(MD, nullptr))
7553       return true;
7554     Elts.push_back(MD);
7555   } while (EatIfPresent(lltok::comma));
7556 
7557   return parseToken(lltok::rbrace, "expected end of metadata node");
7558 }
7559 
7560 //===----------------------------------------------------------------------===//
7561 // Use-list order directives.
7562 //===----------------------------------------------------------------------===//
7563 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7564                                 SMLoc Loc) {
7565   if (V->use_empty())
7566     return error(Loc, "value has no uses");
7567 
7568   unsigned NumUses = 0;
7569   SmallDenseMap<const Use *, unsigned, 16> Order;
7570   for (const Use &U : V->uses()) {
7571     if (++NumUses > Indexes.size())
7572       break;
7573     Order[&U] = Indexes[NumUses - 1];
7574   }
7575   if (NumUses < 2)
7576     return error(Loc, "value only has one use");
7577   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7578     return error(Loc,
7579                  "wrong number of indexes, expected " + Twine(V->getNumUses()));
7580 
7581   V->sortUseList([&](const Use &L, const Use &R) {
7582     return Order.lookup(&L) < Order.lookup(&R);
7583   });
7584   return false;
7585 }
7586 
7587 /// parseUseListOrderIndexes
7588 ///   ::= '{' uint32 (',' uint32)+ '}'
7589 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7590   SMLoc Loc = Lex.getLoc();
7591   if (parseToken(lltok::lbrace, "expected '{' here"))
7592     return true;
7593   if (Lex.getKind() == lltok::rbrace)
7594     return Lex.Error("expected non-empty list of uselistorder indexes");
7595 
7596   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
7597   // indexes should be distinct numbers in the range [0, size-1], and should
7598   // not be in order.
7599   unsigned Offset = 0;
7600   unsigned Max = 0;
7601   bool IsOrdered = true;
7602   assert(Indexes.empty() && "Expected empty order vector");
7603   do {
7604     unsigned Index;
7605     if (parseUInt32(Index))
7606       return true;
7607 
7608     // Update consistency checks.
7609     Offset += Index - Indexes.size();
7610     Max = std::max(Max, Index);
7611     IsOrdered &= Index == Indexes.size();
7612 
7613     Indexes.push_back(Index);
7614   } while (EatIfPresent(lltok::comma));
7615 
7616   if (parseToken(lltok::rbrace, "expected '}' here"))
7617     return true;
7618 
7619   if (Indexes.size() < 2)
7620     return error(Loc, "expected >= 2 uselistorder indexes");
7621   if (Offset != 0 || Max >= Indexes.size())
7622     return error(Loc,
7623                  "expected distinct uselistorder indexes in range [0, size)");
7624   if (IsOrdered)
7625     return error(Loc, "expected uselistorder indexes to change the order");
7626 
7627   return false;
7628 }
7629 
7630 /// parseUseListOrder
7631 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7632 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7633   SMLoc Loc = Lex.getLoc();
7634   if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7635     return true;
7636 
7637   Value *V;
7638   SmallVector<unsigned, 16> Indexes;
7639   if (parseTypeAndValue(V, PFS) ||
7640       parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7641       parseUseListOrderIndexes(Indexes))
7642     return true;
7643 
7644   return sortUseListOrder(V, Indexes, Loc);
7645 }
7646 
7647 /// parseUseListOrderBB
7648 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7649 bool LLParser::parseUseListOrderBB() {
7650   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7651   SMLoc Loc = Lex.getLoc();
7652   Lex.Lex();
7653 
7654   ValID Fn, Label;
7655   SmallVector<unsigned, 16> Indexes;
7656   if (parseValID(Fn, /*PFS=*/nullptr) ||
7657       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7658       parseValID(Label, /*PFS=*/nullptr) ||
7659       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7660       parseUseListOrderIndexes(Indexes))
7661     return true;
7662 
7663   // Check the function.
7664   GlobalValue *GV;
7665   if (Fn.Kind == ValID::t_GlobalName)
7666     GV = M->getNamedValue(Fn.StrVal);
7667   else if (Fn.Kind == ValID::t_GlobalID)
7668     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7669   else
7670     return error(Fn.Loc, "expected function name in uselistorder_bb");
7671   if (!GV)
7672     return error(Fn.Loc,
7673                  "invalid function forward reference in uselistorder_bb");
7674   auto *F = dyn_cast<Function>(GV);
7675   if (!F)
7676     return error(Fn.Loc, "expected function name in uselistorder_bb");
7677   if (F->isDeclaration())
7678     return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7679 
7680   // Check the basic block.
7681   if (Label.Kind == ValID::t_LocalID)
7682     return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7683   if (Label.Kind != ValID::t_LocalName)
7684     return error(Label.Loc, "expected basic block name in uselistorder_bb");
7685   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7686   if (!V)
7687     return error(Label.Loc, "invalid basic block in uselistorder_bb");
7688   if (!isa<BasicBlock>(V))
7689     return error(Label.Loc, "expected basic block in uselistorder_bb");
7690 
7691   return sortUseListOrder(V, Indexes, Loc);
7692 }
7693 
7694 /// ModuleEntry
7695 ///   ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7696 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7697 bool LLParser::parseModuleEntry(unsigned ID) {
7698   assert(Lex.getKind() == lltok::kw_module);
7699   Lex.Lex();
7700 
7701   std::string Path;
7702   if (parseToken(lltok::colon, "expected ':' here") ||
7703       parseToken(lltok::lparen, "expected '(' here") ||
7704       parseToken(lltok::kw_path, "expected 'path' here") ||
7705       parseToken(lltok::colon, "expected ':' here") ||
7706       parseStringConstant(Path) ||
7707       parseToken(lltok::comma, "expected ',' here") ||
7708       parseToken(lltok::kw_hash, "expected 'hash' here") ||
7709       parseToken(lltok::colon, "expected ':' here") ||
7710       parseToken(lltok::lparen, "expected '(' here"))
7711     return true;
7712 
7713   ModuleHash Hash;
7714   if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
7715       parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
7716       parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
7717       parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
7718       parseUInt32(Hash[4]))
7719     return true;
7720 
7721   if (parseToken(lltok::rparen, "expected ')' here") ||
7722       parseToken(lltok::rparen, "expected ')' here"))
7723     return true;
7724 
7725   auto ModuleEntry = Index->addModule(Path, ID, Hash);
7726   ModuleIdMap[ID] = ModuleEntry->first();
7727 
7728   return false;
7729 }
7730 
7731 /// TypeIdEntry
7732 ///   ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7733 bool LLParser::parseTypeIdEntry(unsigned ID) {
7734   assert(Lex.getKind() == lltok::kw_typeid);
7735   Lex.Lex();
7736 
7737   std::string Name;
7738   if (parseToken(lltok::colon, "expected ':' here") ||
7739       parseToken(lltok::lparen, "expected '(' here") ||
7740       parseToken(lltok::kw_name, "expected 'name' here") ||
7741       parseToken(lltok::colon, "expected ':' here") ||
7742       parseStringConstant(Name))
7743     return true;
7744 
7745   TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7746   if (parseToken(lltok::comma, "expected ',' here") ||
7747       parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
7748     return true;
7749 
7750   // Check if this ID was forward referenced, and if so, update the
7751   // corresponding GUIDs.
7752   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7753   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7754     for (auto TIDRef : FwdRefTIDs->second) {
7755       assert(!*TIDRef.first &&
7756              "Forward referenced type id GUID expected to be 0");
7757       *TIDRef.first = GlobalValue::getGUID(Name);
7758     }
7759     ForwardRefTypeIds.erase(FwdRefTIDs);
7760   }
7761 
7762   return false;
7763 }
7764 
7765 /// TypeIdSummary
7766 ///   ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7767 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
7768   if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
7769       parseToken(lltok::colon, "expected ':' here") ||
7770       parseToken(lltok::lparen, "expected '(' here") ||
7771       parseTypeTestResolution(TIS.TTRes))
7772     return true;
7773 
7774   if (EatIfPresent(lltok::comma)) {
7775     // Expect optional wpdResolutions field
7776     if (parseOptionalWpdResolutions(TIS.WPDRes))
7777       return true;
7778   }
7779 
7780   if (parseToken(lltok::rparen, "expected ')' here"))
7781     return true;
7782 
7783   return false;
7784 }
7785 
7786 static ValueInfo EmptyVI =
7787     ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7788 
7789 /// TypeIdCompatibleVtableEntry
7790 ///   ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7791 ///   TypeIdCompatibleVtableInfo
7792 ///   ')'
7793 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
7794   assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7795   Lex.Lex();
7796 
7797   std::string Name;
7798   if (parseToken(lltok::colon, "expected ':' here") ||
7799       parseToken(lltok::lparen, "expected '(' here") ||
7800       parseToken(lltok::kw_name, "expected 'name' here") ||
7801       parseToken(lltok::colon, "expected ':' here") ||
7802       parseStringConstant(Name))
7803     return true;
7804 
7805   TypeIdCompatibleVtableInfo &TI =
7806       Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7807   if (parseToken(lltok::comma, "expected ',' here") ||
7808       parseToken(lltok::kw_summary, "expected 'summary' here") ||
7809       parseToken(lltok::colon, "expected ':' here") ||
7810       parseToken(lltok::lparen, "expected '(' here"))
7811     return true;
7812 
7813   IdToIndexMapType IdToIndexMap;
7814   // parse each call edge
7815   do {
7816     uint64_t Offset;
7817     if (parseToken(lltok::lparen, "expected '(' here") ||
7818         parseToken(lltok::kw_offset, "expected 'offset' here") ||
7819         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7820         parseToken(lltok::comma, "expected ',' here"))
7821       return true;
7822 
7823     LocTy Loc = Lex.getLoc();
7824     unsigned GVId;
7825     ValueInfo VI;
7826     if (parseGVReference(VI, GVId))
7827       return true;
7828 
7829     // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7830     // forward reference. We will save the location of the ValueInfo needing an
7831     // update, but can only do so once the std::vector is finalized.
7832     if (VI == EmptyVI)
7833       IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7834     TI.push_back({Offset, VI});
7835 
7836     if (parseToken(lltok::rparen, "expected ')' in call"))
7837       return true;
7838   } while (EatIfPresent(lltok::comma));
7839 
7840   // Now that the TI vector is finalized, it is safe to save the locations
7841   // of any forward GV references that need updating later.
7842   for (auto I : IdToIndexMap) {
7843     auto &Infos = ForwardRefValueInfos[I.first];
7844     for (auto P : I.second) {
7845       assert(TI[P.first].VTableVI == EmptyVI &&
7846              "Forward referenced ValueInfo expected to be empty");
7847       Infos.emplace_back(&TI[P.first].VTableVI, P.second);
7848     }
7849   }
7850 
7851   if (parseToken(lltok::rparen, "expected ')' here") ||
7852       parseToken(lltok::rparen, "expected ')' here"))
7853     return true;
7854 
7855   // Check if this ID was forward referenced, and if so, update the
7856   // corresponding GUIDs.
7857   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7858   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7859     for (auto TIDRef : FwdRefTIDs->second) {
7860       assert(!*TIDRef.first &&
7861              "Forward referenced type id GUID expected to be 0");
7862       *TIDRef.first = GlobalValue::getGUID(Name);
7863     }
7864     ForwardRefTypeIds.erase(FwdRefTIDs);
7865   }
7866 
7867   return false;
7868 }
7869 
7870 /// TypeTestResolution
7871 ///   ::= 'typeTestRes' ':' '(' 'kind' ':'
7872 ///         ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7873 ///         'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7874 ///         [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7875 ///         [',' 'inlinesBits' ':' UInt64]? ')'
7876 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
7877   if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7878       parseToken(lltok::colon, "expected ':' here") ||
7879       parseToken(lltok::lparen, "expected '(' here") ||
7880       parseToken(lltok::kw_kind, "expected 'kind' here") ||
7881       parseToken(lltok::colon, "expected ':' here"))
7882     return true;
7883 
7884   switch (Lex.getKind()) {
7885   case lltok::kw_unknown:
7886     TTRes.TheKind = TypeTestResolution::Unknown;
7887     break;
7888   case lltok::kw_unsat:
7889     TTRes.TheKind = TypeTestResolution::Unsat;
7890     break;
7891   case lltok::kw_byteArray:
7892     TTRes.TheKind = TypeTestResolution::ByteArray;
7893     break;
7894   case lltok::kw_inline:
7895     TTRes.TheKind = TypeTestResolution::Inline;
7896     break;
7897   case lltok::kw_single:
7898     TTRes.TheKind = TypeTestResolution::Single;
7899     break;
7900   case lltok::kw_allOnes:
7901     TTRes.TheKind = TypeTestResolution::AllOnes;
7902     break;
7903   default:
7904     return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7905   }
7906   Lex.Lex();
7907 
7908   if (parseToken(lltok::comma, "expected ',' here") ||
7909       parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7910       parseToken(lltok::colon, "expected ':' here") ||
7911       parseUInt32(TTRes.SizeM1BitWidth))
7912     return true;
7913 
7914   // parse optional fields
7915   while (EatIfPresent(lltok::comma)) {
7916     switch (Lex.getKind()) {
7917     case lltok::kw_alignLog2:
7918       Lex.Lex();
7919       if (parseToken(lltok::colon, "expected ':'") ||
7920           parseUInt64(TTRes.AlignLog2))
7921         return true;
7922       break;
7923     case lltok::kw_sizeM1:
7924       Lex.Lex();
7925       if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
7926         return true;
7927       break;
7928     case lltok::kw_bitMask: {
7929       unsigned Val;
7930       Lex.Lex();
7931       if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
7932         return true;
7933       assert(Val <= 0xff);
7934       TTRes.BitMask = (uint8_t)Val;
7935       break;
7936     }
7937     case lltok::kw_inlineBits:
7938       Lex.Lex();
7939       if (parseToken(lltok::colon, "expected ':'") ||
7940           parseUInt64(TTRes.InlineBits))
7941         return true;
7942       break;
7943     default:
7944       return error(Lex.getLoc(), "expected optional TypeTestResolution field");
7945     }
7946   }
7947 
7948   if (parseToken(lltok::rparen, "expected ')' here"))
7949     return true;
7950 
7951   return false;
7952 }
7953 
7954 /// OptionalWpdResolutions
7955 ///   ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7956 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7957 bool LLParser::parseOptionalWpdResolutions(
7958     std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7959   if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7960       parseToken(lltok::colon, "expected ':' here") ||
7961       parseToken(lltok::lparen, "expected '(' here"))
7962     return true;
7963 
7964   do {
7965     uint64_t Offset;
7966     WholeProgramDevirtResolution WPDRes;
7967     if (parseToken(lltok::lparen, "expected '(' here") ||
7968         parseToken(lltok::kw_offset, "expected 'offset' here") ||
7969         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7970         parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
7971         parseToken(lltok::rparen, "expected ')' here"))
7972       return true;
7973     WPDResMap[Offset] = WPDRes;
7974   } while (EatIfPresent(lltok::comma));
7975 
7976   if (parseToken(lltok::rparen, "expected ')' here"))
7977     return true;
7978 
7979   return false;
7980 }
7981 
7982 /// WpdRes
7983 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7984 ///         [',' OptionalResByArg]? ')'
7985 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7986 ///         ',' 'singleImplName' ':' STRINGCONSTANT ','
7987 ///         [',' OptionalResByArg]? ')'
7988 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7989 ///         [',' OptionalResByArg]? ')'
7990 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7991   if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7992       parseToken(lltok::colon, "expected ':' here") ||
7993       parseToken(lltok::lparen, "expected '(' here") ||
7994       parseToken(lltok::kw_kind, "expected 'kind' here") ||
7995       parseToken(lltok::colon, "expected ':' here"))
7996     return true;
7997 
7998   switch (Lex.getKind()) {
7999   case lltok::kw_indir:
8000     WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8001     break;
8002   case lltok::kw_singleImpl:
8003     WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8004     break;
8005   case lltok::kw_branchFunnel:
8006     WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8007     break;
8008   default:
8009     return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8010   }
8011   Lex.Lex();
8012 
8013   // parse optional fields
8014   while (EatIfPresent(lltok::comma)) {
8015     switch (Lex.getKind()) {
8016     case lltok::kw_singleImplName:
8017       Lex.Lex();
8018       if (parseToken(lltok::colon, "expected ':' here") ||
8019           parseStringConstant(WPDRes.SingleImplName))
8020         return true;
8021       break;
8022     case lltok::kw_resByArg:
8023       if (parseOptionalResByArg(WPDRes.ResByArg))
8024         return true;
8025       break;
8026     default:
8027       return error(Lex.getLoc(),
8028                    "expected optional WholeProgramDevirtResolution field");
8029     }
8030   }
8031 
8032   if (parseToken(lltok::rparen, "expected ')' here"))
8033     return true;
8034 
8035   return false;
8036 }
8037 
8038 /// OptionalResByArg
8039 ///   ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8040 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8041 ///                ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8042 ///                  'virtualConstProp' )
8043 ///                [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8044 ///                [',' 'bit' ':' UInt32]? ')'
8045 bool LLParser::parseOptionalResByArg(
8046     std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8047         &ResByArg) {
8048   if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8049       parseToken(lltok::colon, "expected ':' here") ||
8050       parseToken(lltok::lparen, "expected '(' here"))
8051     return true;
8052 
8053   do {
8054     std::vector<uint64_t> Args;
8055     if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8056         parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8057         parseToken(lltok::colon, "expected ':' here") ||
8058         parseToken(lltok::lparen, "expected '(' here") ||
8059         parseToken(lltok::kw_kind, "expected 'kind' here") ||
8060         parseToken(lltok::colon, "expected ':' here"))
8061       return true;
8062 
8063     WholeProgramDevirtResolution::ByArg ByArg;
8064     switch (Lex.getKind()) {
8065     case lltok::kw_indir:
8066       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8067       break;
8068     case lltok::kw_uniformRetVal:
8069       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8070       break;
8071     case lltok::kw_uniqueRetVal:
8072       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8073       break;
8074     case lltok::kw_virtualConstProp:
8075       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8076       break;
8077     default:
8078       return error(Lex.getLoc(),
8079                    "unexpected WholeProgramDevirtResolution::ByArg kind");
8080     }
8081     Lex.Lex();
8082 
8083     // parse optional fields
8084     while (EatIfPresent(lltok::comma)) {
8085       switch (Lex.getKind()) {
8086       case lltok::kw_info:
8087         Lex.Lex();
8088         if (parseToken(lltok::colon, "expected ':' here") ||
8089             parseUInt64(ByArg.Info))
8090           return true;
8091         break;
8092       case lltok::kw_byte:
8093         Lex.Lex();
8094         if (parseToken(lltok::colon, "expected ':' here") ||
8095             parseUInt32(ByArg.Byte))
8096           return true;
8097         break;
8098       case lltok::kw_bit:
8099         Lex.Lex();
8100         if (parseToken(lltok::colon, "expected ':' here") ||
8101             parseUInt32(ByArg.Bit))
8102           return true;
8103         break;
8104       default:
8105         return error(Lex.getLoc(),
8106                      "expected optional whole program devirt field");
8107       }
8108     }
8109 
8110     if (parseToken(lltok::rparen, "expected ')' here"))
8111       return true;
8112 
8113     ResByArg[Args] = ByArg;
8114   } while (EatIfPresent(lltok::comma));
8115 
8116   if (parseToken(lltok::rparen, "expected ')' here"))
8117     return true;
8118 
8119   return false;
8120 }
8121 
8122 /// OptionalResByArg
8123 ///   ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8124 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8125   if (parseToken(lltok::kw_args, "expected 'args' here") ||
8126       parseToken(lltok::colon, "expected ':' here") ||
8127       parseToken(lltok::lparen, "expected '(' here"))
8128     return true;
8129 
8130   do {
8131     uint64_t Val;
8132     if (parseUInt64(Val))
8133       return true;
8134     Args.push_back(Val);
8135   } while (EatIfPresent(lltok::comma));
8136 
8137   if (parseToken(lltok::rparen, "expected ')' here"))
8138     return true;
8139 
8140   return false;
8141 }
8142 
8143 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8144 
8145 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8146   bool ReadOnly = Fwd->isReadOnly();
8147   bool WriteOnly = Fwd->isWriteOnly();
8148   assert(!(ReadOnly && WriteOnly));
8149   *Fwd = Resolved;
8150   if (ReadOnly)
8151     Fwd->setReadOnly();
8152   if (WriteOnly)
8153     Fwd->setWriteOnly();
8154 }
8155 
8156 /// Stores the given Name/GUID and associated summary into the Index.
8157 /// Also updates any forward references to the associated entry ID.
8158 void LLParser::addGlobalValueToIndex(
8159     std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8160     unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8161   // First create the ValueInfo utilizing the Name or GUID.
8162   ValueInfo VI;
8163   if (GUID != 0) {
8164     assert(Name.empty());
8165     VI = Index->getOrInsertValueInfo(GUID);
8166   } else {
8167     assert(!Name.empty());
8168     if (M) {
8169       auto *GV = M->getNamedValue(Name);
8170       assert(GV);
8171       VI = Index->getOrInsertValueInfo(GV);
8172     } else {
8173       assert(
8174           (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8175           "Need a source_filename to compute GUID for local");
8176       GUID = GlobalValue::getGUID(
8177           GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8178       VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8179     }
8180   }
8181 
8182   // Resolve forward references from calls/refs
8183   auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8184   if (FwdRefVIs != ForwardRefValueInfos.end()) {
8185     for (auto VIRef : FwdRefVIs->second) {
8186       assert(VIRef.first->getRef() == FwdVIRef &&
8187              "Forward referenced ValueInfo expected to be empty");
8188       resolveFwdRef(VIRef.first, VI);
8189     }
8190     ForwardRefValueInfos.erase(FwdRefVIs);
8191   }
8192 
8193   // Resolve forward references from aliases
8194   auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8195   if (FwdRefAliasees != ForwardRefAliasees.end()) {
8196     for (auto AliaseeRef : FwdRefAliasees->second) {
8197       assert(!AliaseeRef.first->hasAliasee() &&
8198              "Forward referencing alias already has aliasee");
8199       assert(Summary && "Aliasee must be a definition");
8200       AliaseeRef.first->setAliasee(VI, Summary.get());
8201     }
8202     ForwardRefAliasees.erase(FwdRefAliasees);
8203   }
8204 
8205   // Add the summary if one was provided.
8206   if (Summary)
8207     Index->addGlobalValueSummary(VI, std::move(Summary));
8208 
8209   // Save the associated ValueInfo for use in later references by ID.
8210   if (ID == NumberedValueInfos.size())
8211     NumberedValueInfos.push_back(VI);
8212   else {
8213     // Handle non-continuous numbers (to make test simplification easier).
8214     if (ID > NumberedValueInfos.size())
8215       NumberedValueInfos.resize(ID + 1);
8216     NumberedValueInfos[ID] = VI;
8217   }
8218 }
8219 
8220 /// parseSummaryIndexFlags
8221 ///   ::= 'flags' ':' UInt64
8222 bool LLParser::parseSummaryIndexFlags() {
8223   assert(Lex.getKind() == lltok::kw_flags);
8224   Lex.Lex();
8225 
8226   if (parseToken(lltok::colon, "expected ':' here"))
8227     return true;
8228   uint64_t Flags;
8229   if (parseUInt64(Flags))
8230     return true;
8231   if (Index)
8232     Index->setFlags(Flags);
8233   return false;
8234 }
8235 
8236 /// parseBlockCount
8237 ///   ::= 'blockcount' ':' UInt64
8238 bool LLParser::parseBlockCount() {
8239   assert(Lex.getKind() == lltok::kw_blockcount);
8240   Lex.Lex();
8241 
8242   if (parseToken(lltok::colon, "expected ':' here"))
8243     return true;
8244   uint64_t BlockCount;
8245   if (parseUInt64(BlockCount))
8246     return true;
8247   if (Index)
8248     Index->setBlockCount(BlockCount);
8249   return false;
8250 }
8251 
8252 /// parseGVEntry
8253 ///   ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8254 ///         [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8255 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8256 bool LLParser::parseGVEntry(unsigned ID) {
8257   assert(Lex.getKind() == lltok::kw_gv);
8258   Lex.Lex();
8259 
8260   if (parseToken(lltok::colon, "expected ':' here") ||
8261       parseToken(lltok::lparen, "expected '(' here"))
8262     return true;
8263 
8264   std::string Name;
8265   GlobalValue::GUID GUID = 0;
8266   switch (Lex.getKind()) {
8267   case lltok::kw_name:
8268     Lex.Lex();
8269     if (parseToken(lltok::colon, "expected ':' here") ||
8270         parseStringConstant(Name))
8271       return true;
8272     // Can't create GUID/ValueInfo until we have the linkage.
8273     break;
8274   case lltok::kw_guid:
8275     Lex.Lex();
8276     if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8277       return true;
8278     break;
8279   default:
8280     return error(Lex.getLoc(), "expected name or guid tag");
8281   }
8282 
8283   if (!EatIfPresent(lltok::comma)) {
8284     // No summaries. Wrap up.
8285     if (parseToken(lltok::rparen, "expected ')' here"))
8286       return true;
8287     // This was created for a call to an external or indirect target.
8288     // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8289     // created for indirect calls with VP. A Name with no GUID came from
8290     // an external definition. We pass ExternalLinkage since that is only
8291     // used when the GUID must be computed from Name, and in that case
8292     // the symbol must have external linkage.
8293     addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8294                           nullptr);
8295     return false;
8296   }
8297 
8298   // Have a list of summaries
8299   if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8300       parseToken(lltok::colon, "expected ':' here") ||
8301       parseToken(lltok::lparen, "expected '(' here"))
8302     return true;
8303   do {
8304     switch (Lex.getKind()) {
8305     case lltok::kw_function:
8306       if (parseFunctionSummary(Name, GUID, ID))
8307         return true;
8308       break;
8309     case lltok::kw_variable:
8310       if (parseVariableSummary(Name, GUID, ID))
8311         return true;
8312       break;
8313     case lltok::kw_alias:
8314       if (parseAliasSummary(Name, GUID, ID))
8315         return true;
8316       break;
8317     default:
8318       return error(Lex.getLoc(), "expected summary type");
8319     }
8320   } while (EatIfPresent(lltok::comma));
8321 
8322   if (parseToken(lltok::rparen, "expected ')' here") ||
8323       parseToken(lltok::rparen, "expected ')' here"))
8324     return true;
8325 
8326   return false;
8327 }
8328 
8329 /// FunctionSummary
8330 ///   ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8331 ///         ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8332 ///         [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8333 ///         [',' OptionalRefs]? ')'
8334 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8335                                     unsigned ID) {
8336   assert(Lex.getKind() == lltok::kw_function);
8337   Lex.Lex();
8338 
8339   StringRef ModulePath;
8340   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8341       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8342       /*NotEligibleToImport=*/false,
8343       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8344   unsigned InstCount;
8345   std::vector<FunctionSummary::EdgeTy> Calls;
8346   FunctionSummary::TypeIdInfo TypeIdInfo;
8347   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8348   std::vector<ValueInfo> Refs;
8349   // Default is all-zeros (conservative values).
8350   FunctionSummary::FFlags FFlags = {};
8351   if (parseToken(lltok::colon, "expected ':' here") ||
8352       parseToken(lltok::lparen, "expected '(' here") ||
8353       parseModuleReference(ModulePath) ||
8354       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8355       parseToken(lltok::comma, "expected ',' here") ||
8356       parseToken(lltok::kw_insts, "expected 'insts' here") ||
8357       parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8358     return true;
8359 
8360   // parse optional fields
8361   while (EatIfPresent(lltok::comma)) {
8362     switch (Lex.getKind()) {
8363     case lltok::kw_funcFlags:
8364       if (parseOptionalFFlags(FFlags))
8365         return true;
8366       break;
8367     case lltok::kw_calls:
8368       if (parseOptionalCalls(Calls))
8369         return true;
8370       break;
8371     case lltok::kw_typeIdInfo:
8372       if (parseOptionalTypeIdInfo(TypeIdInfo))
8373         return true;
8374       break;
8375     case lltok::kw_refs:
8376       if (parseOptionalRefs(Refs))
8377         return true;
8378       break;
8379     case lltok::kw_params:
8380       if (parseOptionalParamAccesses(ParamAccesses))
8381         return true;
8382       break;
8383     default:
8384       return error(Lex.getLoc(), "expected optional function summary field");
8385     }
8386   }
8387 
8388   if (parseToken(lltok::rparen, "expected ')' here"))
8389     return true;
8390 
8391   auto FS = std::make_unique<FunctionSummary>(
8392       GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8393       std::move(Calls), std::move(TypeIdInfo.TypeTests),
8394       std::move(TypeIdInfo.TypeTestAssumeVCalls),
8395       std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8396       std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8397       std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8398       std::move(ParamAccesses));
8399 
8400   FS->setModulePath(ModulePath);
8401 
8402   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8403                         ID, std::move(FS));
8404 
8405   return false;
8406 }
8407 
8408 /// VariableSummary
8409 ///   ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8410 ///         [',' OptionalRefs]? ')'
8411 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8412                                     unsigned ID) {
8413   assert(Lex.getKind() == lltok::kw_variable);
8414   Lex.Lex();
8415 
8416   StringRef ModulePath;
8417   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8418       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8419       /*NotEligibleToImport=*/false,
8420       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8421   GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8422                                         /* WriteOnly */ false,
8423                                         /* Constant */ false,
8424                                         GlobalObject::VCallVisibilityPublic);
8425   std::vector<ValueInfo> Refs;
8426   VTableFuncList VTableFuncs;
8427   if (parseToken(lltok::colon, "expected ':' here") ||
8428       parseToken(lltok::lparen, "expected '(' here") ||
8429       parseModuleReference(ModulePath) ||
8430       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8431       parseToken(lltok::comma, "expected ',' here") ||
8432       parseGVarFlags(GVarFlags))
8433     return true;
8434 
8435   // parse optional fields
8436   while (EatIfPresent(lltok::comma)) {
8437     switch (Lex.getKind()) {
8438     case lltok::kw_vTableFuncs:
8439       if (parseOptionalVTableFuncs(VTableFuncs))
8440         return true;
8441       break;
8442     case lltok::kw_refs:
8443       if (parseOptionalRefs(Refs))
8444         return true;
8445       break;
8446     default:
8447       return error(Lex.getLoc(), "expected optional variable summary field");
8448     }
8449   }
8450 
8451   if (parseToken(lltok::rparen, "expected ')' here"))
8452     return true;
8453 
8454   auto GS =
8455       std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8456 
8457   GS->setModulePath(ModulePath);
8458   GS->setVTableFuncs(std::move(VTableFuncs));
8459 
8460   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8461                         ID, std::move(GS));
8462 
8463   return false;
8464 }
8465 
8466 /// AliasSummary
8467 ///   ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8468 ///         'aliasee' ':' GVReference ')'
8469 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8470                                  unsigned ID) {
8471   assert(Lex.getKind() == lltok::kw_alias);
8472   LocTy Loc = Lex.getLoc();
8473   Lex.Lex();
8474 
8475   StringRef ModulePath;
8476   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8477       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8478       /*NotEligibleToImport=*/false,
8479       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8480   if (parseToken(lltok::colon, "expected ':' here") ||
8481       parseToken(lltok::lparen, "expected '(' here") ||
8482       parseModuleReference(ModulePath) ||
8483       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8484       parseToken(lltok::comma, "expected ',' here") ||
8485       parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8486       parseToken(lltok::colon, "expected ':' here"))
8487     return true;
8488 
8489   ValueInfo AliaseeVI;
8490   unsigned GVId;
8491   if (parseGVReference(AliaseeVI, GVId))
8492     return true;
8493 
8494   if (parseToken(lltok::rparen, "expected ')' here"))
8495     return true;
8496 
8497   auto AS = std::make_unique<AliasSummary>(GVFlags);
8498 
8499   AS->setModulePath(ModulePath);
8500 
8501   // Record forward reference if the aliasee is not parsed yet.
8502   if (AliaseeVI.getRef() == FwdVIRef) {
8503     ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8504   } else {
8505     auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8506     assert(Summary && "Aliasee must be a definition");
8507     AS->setAliasee(AliaseeVI, Summary);
8508   }
8509 
8510   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8511                         ID, std::move(AS));
8512 
8513   return false;
8514 }
8515 
8516 /// Flag
8517 ///   ::= [0|1]
8518 bool LLParser::parseFlag(unsigned &Val) {
8519   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8520     return tokError("expected integer");
8521   Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8522   Lex.Lex();
8523   return false;
8524 }
8525 
8526 /// OptionalFFlags
8527 ///   := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8528 ///        [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8529 ///        [',' 'returnDoesNotAlias' ':' Flag]? ')'
8530 ///        [',' 'noInline' ':' Flag]? ')'
8531 ///        [',' 'alwaysInline' ':' Flag]? ')'
8532 ///        [',' 'noUnwind' ':' Flag]? ')'
8533 ///        [',' 'mayThrow' ':' Flag]? ')'
8534 ///        [',' 'hasUnknownCall' ':' Flag]? ')'
8535 
8536 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8537   assert(Lex.getKind() == lltok::kw_funcFlags);
8538   Lex.Lex();
8539 
8540   if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
8541       parseToken(lltok::lparen, "expected '(' in funcFlags"))
8542     return true;
8543 
8544   do {
8545     unsigned Val = 0;
8546     switch (Lex.getKind()) {
8547     case lltok::kw_readNone:
8548       Lex.Lex();
8549       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8550         return true;
8551       FFlags.ReadNone = Val;
8552       break;
8553     case lltok::kw_readOnly:
8554       Lex.Lex();
8555       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8556         return true;
8557       FFlags.ReadOnly = Val;
8558       break;
8559     case lltok::kw_noRecurse:
8560       Lex.Lex();
8561       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8562         return true;
8563       FFlags.NoRecurse = Val;
8564       break;
8565     case lltok::kw_returnDoesNotAlias:
8566       Lex.Lex();
8567       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8568         return true;
8569       FFlags.ReturnDoesNotAlias = Val;
8570       break;
8571     case lltok::kw_noInline:
8572       Lex.Lex();
8573       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8574         return true;
8575       FFlags.NoInline = Val;
8576       break;
8577     case lltok::kw_alwaysInline:
8578       Lex.Lex();
8579       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8580         return true;
8581       FFlags.AlwaysInline = Val;
8582       break;
8583     case lltok::kw_noUnwind:
8584       Lex.Lex();
8585       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8586         return true;
8587       FFlags.NoUnwind = Val;
8588       break;
8589     case lltok::kw_mayThrow:
8590       Lex.Lex();
8591       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8592         return true;
8593       FFlags.MayThrow = Val;
8594       break;
8595     case lltok::kw_hasUnknownCall:
8596       Lex.Lex();
8597       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8598         return true;
8599       FFlags.HasUnknownCall = Val;
8600       break;
8601     default:
8602       return error(Lex.getLoc(), "expected function flag type");
8603     }
8604   } while (EatIfPresent(lltok::comma));
8605 
8606   if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8607     return true;
8608 
8609   return false;
8610 }
8611 
8612 /// OptionalCalls
8613 ///   := 'calls' ':' '(' Call [',' Call]* ')'
8614 /// Call ::= '(' 'callee' ':' GVReference
8615 ///            [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8616 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8617   assert(Lex.getKind() == lltok::kw_calls);
8618   Lex.Lex();
8619 
8620   if (parseToken(lltok::colon, "expected ':' in calls") ||
8621       parseToken(lltok::lparen, "expected '(' in calls"))
8622     return true;
8623 
8624   IdToIndexMapType IdToIndexMap;
8625   // parse each call edge
8626   do {
8627     ValueInfo VI;
8628     if (parseToken(lltok::lparen, "expected '(' in call") ||
8629         parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8630         parseToken(lltok::colon, "expected ':'"))
8631       return true;
8632 
8633     LocTy Loc = Lex.getLoc();
8634     unsigned GVId;
8635     if (parseGVReference(VI, GVId))
8636       return true;
8637 
8638     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8639     unsigned RelBF = 0;
8640     if (EatIfPresent(lltok::comma)) {
8641       // Expect either hotness or relbf
8642       if (EatIfPresent(lltok::kw_hotness)) {
8643         if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8644           return true;
8645       } else {
8646         if (parseToken(lltok::kw_relbf, "expected relbf") ||
8647             parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8648           return true;
8649       }
8650     }
8651     // Keep track of the Call array index needing a forward reference.
8652     // We will save the location of the ValueInfo needing an update, but
8653     // can only do so once the std::vector is finalized.
8654     if (VI.getRef() == FwdVIRef)
8655       IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8656     Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8657 
8658     if (parseToken(lltok::rparen, "expected ')' in call"))
8659       return true;
8660   } while (EatIfPresent(lltok::comma));
8661 
8662   // Now that the Calls vector is finalized, it is safe to save the locations
8663   // of any forward GV references that need updating later.
8664   for (auto I : IdToIndexMap) {
8665     auto &Infos = ForwardRefValueInfos[I.first];
8666     for (auto P : I.second) {
8667       assert(Calls[P.first].first.getRef() == FwdVIRef &&
8668              "Forward referenced ValueInfo expected to be empty");
8669       Infos.emplace_back(&Calls[P.first].first, P.second);
8670     }
8671   }
8672 
8673   if (parseToken(lltok::rparen, "expected ')' in calls"))
8674     return true;
8675 
8676   return false;
8677 }
8678 
8679 /// Hotness
8680 ///   := ('unknown'|'cold'|'none'|'hot'|'critical')
8681 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8682   switch (Lex.getKind()) {
8683   case lltok::kw_unknown:
8684     Hotness = CalleeInfo::HotnessType::Unknown;
8685     break;
8686   case lltok::kw_cold:
8687     Hotness = CalleeInfo::HotnessType::Cold;
8688     break;
8689   case lltok::kw_none:
8690     Hotness = CalleeInfo::HotnessType::None;
8691     break;
8692   case lltok::kw_hot:
8693     Hotness = CalleeInfo::HotnessType::Hot;
8694     break;
8695   case lltok::kw_critical:
8696     Hotness = CalleeInfo::HotnessType::Critical;
8697     break;
8698   default:
8699     return error(Lex.getLoc(), "invalid call edge hotness");
8700   }
8701   Lex.Lex();
8702   return false;
8703 }
8704 
8705 /// OptionalVTableFuncs
8706 ///   := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8707 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8708 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8709   assert(Lex.getKind() == lltok::kw_vTableFuncs);
8710   Lex.Lex();
8711 
8712   if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
8713       parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8714     return true;
8715 
8716   IdToIndexMapType IdToIndexMap;
8717   // parse each virtual function pair
8718   do {
8719     ValueInfo VI;
8720     if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8721         parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8722         parseToken(lltok::colon, "expected ':'"))
8723       return true;
8724 
8725     LocTy Loc = Lex.getLoc();
8726     unsigned GVId;
8727     if (parseGVReference(VI, GVId))
8728       return true;
8729 
8730     uint64_t Offset;
8731     if (parseToken(lltok::comma, "expected comma") ||
8732         parseToken(lltok::kw_offset, "expected offset") ||
8733         parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
8734       return true;
8735 
8736     // Keep track of the VTableFuncs array index needing a forward reference.
8737     // We will save the location of the ValueInfo needing an update, but
8738     // can only do so once the std::vector is finalized.
8739     if (VI == EmptyVI)
8740       IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8741     VTableFuncs.push_back({VI, Offset});
8742 
8743     if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
8744       return true;
8745   } while (EatIfPresent(lltok::comma));
8746 
8747   // Now that the VTableFuncs vector is finalized, it is safe to save the
8748   // locations of any forward GV references that need updating later.
8749   for (auto I : IdToIndexMap) {
8750     auto &Infos = ForwardRefValueInfos[I.first];
8751     for (auto P : I.second) {
8752       assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8753              "Forward referenced ValueInfo expected to be empty");
8754       Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
8755     }
8756   }
8757 
8758   if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8759     return true;
8760 
8761   return false;
8762 }
8763 
8764 /// ParamNo := 'param' ':' UInt64
8765 bool LLParser::parseParamNo(uint64_t &ParamNo) {
8766   if (parseToken(lltok::kw_param, "expected 'param' here") ||
8767       parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
8768     return true;
8769   return false;
8770 }
8771 
8772 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
8773 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
8774   APSInt Lower;
8775   APSInt Upper;
8776   auto ParseAPSInt = [&](APSInt &Val) {
8777     if (Lex.getKind() != lltok::APSInt)
8778       return tokError("expected integer");
8779     Val = Lex.getAPSIntVal();
8780     Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
8781     Val.setIsSigned(true);
8782     Lex.Lex();
8783     return false;
8784   };
8785   if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
8786       parseToken(lltok::colon, "expected ':' here") ||
8787       parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
8788       parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
8789       parseToken(lltok::rsquare, "expected ']' here"))
8790     return true;
8791 
8792   ++Upper;
8793   Range =
8794       (Lower == Upper && !Lower.isMaxValue())
8795           ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
8796           : ConstantRange(Lower, Upper);
8797 
8798   return false;
8799 }
8800 
8801 /// ParamAccessCall
8802 ///   := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
8803 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
8804                                     IdLocListType &IdLocList) {
8805   if (parseToken(lltok::lparen, "expected '(' here") ||
8806       parseToken(lltok::kw_callee, "expected 'callee' here") ||
8807       parseToken(lltok::colon, "expected ':' here"))
8808     return true;
8809 
8810   unsigned GVId;
8811   ValueInfo VI;
8812   LocTy Loc = Lex.getLoc();
8813   if (parseGVReference(VI, GVId))
8814     return true;
8815 
8816   Call.Callee = VI;
8817   IdLocList.emplace_back(GVId, Loc);
8818 
8819   if (parseToken(lltok::comma, "expected ',' here") ||
8820       parseParamNo(Call.ParamNo) ||
8821       parseToken(lltok::comma, "expected ',' here") ||
8822       parseParamAccessOffset(Call.Offsets))
8823     return true;
8824 
8825   if (parseToken(lltok::rparen, "expected ')' here"))
8826     return true;
8827 
8828   return false;
8829 }
8830 
8831 /// ParamAccess
8832 ///   := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
8833 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
8834 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
8835                                 IdLocListType &IdLocList) {
8836   if (parseToken(lltok::lparen, "expected '(' here") ||
8837       parseParamNo(Param.ParamNo) ||
8838       parseToken(lltok::comma, "expected ',' here") ||
8839       parseParamAccessOffset(Param.Use))
8840     return true;
8841 
8842   if (EatIfPresent(lltok::comma)) {
8843     if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
8844         parseToken(lltok::colon, "expected ':' here") ||
8845         parseToken(lltok::lparen, "expected '(' here"))
8846       return true;
8847     do {
8848       FunctionSummary::ParamAccess::Call Call;
8849       if (parseParamAccessCall(Call, IdLocList))
8850         return true;
8851       Param.Calls.push_back(Call);
8852     } while (EatIfPresent(lltok::comma));
8853 
8854     if (parseToken(lltok::rparen, "expected ')' here"))
8855       return true;
8856   }
8857 
8858   if (parseToken(lltok::rparen, "expected ')' here"))
8859     return true;
8860 
8861   return false;
8862 }
8863 
8864 /// OptionalParamAccesses
8865 ///   := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
8866 bool LLParser::parseOptionalParamAccesses(
8867     std::vector<FunctionSummary::ParamAccess> &Params) {
8868   assert(Lex.getKind() == lltok::kw_params);
8869   Lex.Lex();
8870 
8871   if (parseToken(lltok::colon, "expected ':' here") ||
8872       parseToken(lltok::lparen, "expected '(' here"))
8873     return true;
8874 
8875   IdLocListType VContexts;
8876   size_t CallsNum = 0;
8877   do {
8878     FunctionSummary::ParamAccess ParamAccess;
8879     if (parseParamAccess(ParamAccess, VContexts))
8880       return true;
8881     CallsNum += ParamAccess.Calls.size();
8882     assert(VContexts.size() == CallsNum);
8883     (void)CallsNum;
8884     Params.emplace_back(std::move(ParamAccess));
8885   } while (EatIfPresent(lltok::comma));
8886 
8887   if (parseToken(lltok::rparen, "expected ')' here"))
8888     return true;
8889 
8890   // Now that the Params is finalized, it is safe to save the locations
8891   // of any forward GV references that need updating later.
8892   IdLocListType::const_iterator ItContext = VContexts.begin();
8893   for (auto &PA : Params) {
8894     for (auto &C : PA.Calls) {
8895       if (C.Callee.getRef() == FwdVIRef)
8896         ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
8897                                                             ItContext->second);
8898       ++ItContext;
8899     }
8900   }
8901   assert(ItContext == VContexts.end());
8902 
8903   return false;
8904 }
8905 
8906 /// OptionalRefs
8907 ///   := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8908 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
8909   assert(Lex.getKind() == lltok::kw_refs);
8910   Lex.Lex();
8911 
8912   if (parseToken(lltok::colon, "expected ':' in refs") ||
8913       parseToken(lltok::lparen, "expected '(' in refs"))
8914     return true;
8915 
8916   struct ValueContext {
8917     ValueInfo VI;
8918     unsigned GVId;
8919     LocTy Loc;
8920   };
8921   std::vector<ValueContext> VContexts;
8922   // parse each ref edge
8923   do {
8924     ValueContext VC;
8925     VC.Loc = Lex.getLoc();
8926     if (parseGVReference(VC.VI, VC.GVId))
8927       return true;
8928     VContexts.push_back(VC);
8929   } while (EatIfPresent(lltok::comma));
8930 
8931   // Sort value contexts so that ones with writeonly
8932   // and readonly ValueInfo  are at the end of VContexts vector.
8933   // See FunctionSummary::specialRefCounts()
8934   llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
8935     return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
8936   });
8937 
8938   IdToIndexMapType IdToIndexMap;
8939   for (auto &VC : VContexts) {
8940     // Keep track of the Refs array index needing a forward reference.
8941     // We will save the location of the ValueInfo needing an update, but
8942     // can only do so once the std::vector is finalized.
8943     if (VC.VI.getRef() == FwdVIRef)
8944       IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8945     Refs.push_back(VC.VI);
8946   }
8947 
8948   // Now that the Refs vector is finalized, it is safe to save the locations
8949   // of any forward GV references that need updating later.
8950   for (auto I : IdToIndexMap) {
8951     auto &Infos = ForwardRefValueInfos[I.first];
8952     for (auto P : I.second) {
8953       assert(Refs[P.first].getRef() == FwdVIRef &&
8954              "Forward referenced ValueInfo expected to be empty");
8955       Infos.emplace_back(&Refs[P.first], P.second);
8956     }
8957   }
8958 
8959   if (parseToken(lltok::rparen, "expected ')' in refs"))
8960     return true;
8961 
8962   return false;
8963 }
8964 
8965 /// OptionalTypeIdInfo
8966 ///   := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8967 ///         [',' TypeCheckedLoadVCalls]?  [',' TypeTestAssumeConstVCalls]?
8968 ///         [',' TypeCheckedLoadConstVCalls]? ')'
8969 bool LLParser::parseOptionalTypeIdInfo(
8970     FunctionSummary::TypeIdInfo &TypeIdInfo) {
8971   assert(Lex.getKind() == lltok::kw_typeIdInfo);
8972   Lex.Lex();
8973 
8974   if (parseToken(lltok::colon, "expected ':' here") ||
8975       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8976     return true;
8977 
8978   do {
8979     switch (Lex.getKind()) {
8980     case lltok::kw_typeTests:
8981       if (parseTypeTests(TypeIdInfo.TypeTests))
8982         return true;
8983       break;
8984     case lltok::kw_typeTestAssumeVCalls:
8985       if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8986                            TypeIdInfo.TypeTestAssumeVCalls))
8987         return true;
8988       break;
8989     case lltok::kw_typeCheckedLoadVCalls:
8990       if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8991                            TypeIdInfo.TypeCheckedLoadVCalls))
8992         return true;
8993       break;
8994     case lltok::kw_typeTestAssumeConstVCalls:
8995       if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8996                               TypeIdInfo.TypeTestAssumeConstVCalls))
8997         return true;
8998       break;
8999     case lltok::kw_typeCheckedLoadConstVCalls:
9000       if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9001                               TypeIdInfo.TypeCheckedLoadConstVCalls))
9002         return true;
9003       break;
9004     default:
9005       return error(Lex.getLoc(), "invalid typeIdInfo list type");
9006     }
9007   } while (EatIfPresent(lltok::comma));
9008 
9009   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9010     return true;
9011 
9012   return false;
9013 }
9014 
9015 /// TypeTests
9016 ///   ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9017 ///         [',' (SummaryID | UInt64)]* ')'
9018 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9019   assert(Lex.getKind() == lltok::kw_typeTests);
9020   Lex.Lex();
9021 
9022   if (parseToken(lltok::colon, "expected ':' here") ||
9023       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9024     return true;
9025 
9026   IdToIndexMapType IdToIndexMap;
9027   do {
9028     GlobalValue::GUID GUID = 0;
9029     if (Lex.getKind() == lltok::SummaryID) {
9030       unsigned ID = Lex.getUIntVal();
9031       LocTy Loc = Lex.getLoc();
9032       // Keep track of the TypeTests array index needing a forward reference.
9033       // We will save the location of the GUID needing an update, but
9034       // can only do so once the std::vector is finalized.
9035       IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9036       Lex.Lex();
9037     } else if (parseUInt64(GUID))
9038       return true;
9039     TypeTests.push_back(GUID);
9040   } while (EatIfPresent(lltok::comma));
9041 
9042   // Now that the TypeTests vector is finalized, it is safe to save the
9043   // locations of any forward GV references that need updating later.
9044   for (auto I : IdToIndexMap) {
9045     auto &Ids = ForwardRefTypeIds[I.first];
9046     for (auto P : I.second) {
9047       assert(TypeTests[P.first] == 0 &&
9048              "Forward referenced type id GUID expected to be 0");
9049       Ids.emplace_back(&TypeTests[P.first], P.second);
9050     }
9051   }
9052 
9053   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9054     return true;
9055 
9056   return false;
9057 }
9058 
9059 /// VFuncIdList
9060 ///   ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9061 bool LLParser::parseVFuncIdList(
9062     lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9063   assert(Lex.getKind() == Kind);
9064   Lex.Lex();
9065 
9066   if (parseToken(lltok::colon, "expected ':' here") ||
9067       parseToken(lltok::lparen, "expected '(' here"))
9068     return true;
9069 
9070   IdToIndexMapType IdToIndexMap;
9071   do {
9072     FunctionSummary::VFuncId VFuncId;
9073     if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9074       return true;
9075     VFuncIdList.push_back(VFuncId);
9076   } while (EatIfPresent(lltok::comma));
9077 
9078   if (parseToken(lltok::rparen, "expected ')' here"))
9079     return true;
9080 
9081   // Now that the VFuncIdList vector is finalized, it is safe to save the
9082   // locations of any forward GV references that need updating later.
9083   for (auto I : IdToIndexMap) {
9084     auto &Ids = ForwardRefTypeIds[I.first];
9085     for (auto P : I.second) {
9086       assert(VFuncIdList[P.first].GUID == 0 &&
9087              "Forward referenced type id GUID expected to be 0");
9088       Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9089     }
9090   }
9091 
9092   return false;
9093 }
9094 
9095 /// ConstVCallList
9096 ///   ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9097 bool LLParser::parseConstVCallList(
9098     lltok::Kind Kind,
9099     std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9100   assert(Lex.getKind() == Kind);
9101   Lex.Lex();
9102 
9103   if (parseToken(lltok::colon, "expected ':' here") ||
9104       parseToken(lltok::lparen, "expected '(' here"))
9105     return true;
9106 
9107   IdToIndexMapType IdToIndexMap;
9108   do {
9109     FunctionSummary::ConstVCall ConstVCall;
9110     if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9111       return true;
9112     ConstVCallList.push_back(ConstVCall);
9113   } while (EatIfPresent(lltok::comma));
9114 
9115   if (parseToken(lltok::rparen, "expected ')' here"))
9116     return true;
9117 
9118   // Now that the ConstVCallList vector is finalized, it is safe to save the
9119   // locations of any forward GV references that need updating later.
9120   for (auto I : IdToIndexMap) {
9121     auto &Ids = ForwardRefTypeIds[I.first];
9122     for (auto P : I.second) {
9123       assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9124              "Forward referenced type id GUID expected to be 0");
9125       Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9126     }
9127   }
9128 
9129   return false;
9130 }
9131 
9132 /// ConstVCall
9133 ///   ::= '(' VFuncId ',' Args ')'
9134 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9135                                IdToIndexMapType &IdToIndexMap, unsigned Index) {
9136   if (parseToken(lltok::lparen, "expected '(' here") ||
9137       parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9138     return true;
9139 
9140   if (EatIfPresent(lltok::comma))
9141     if (parseArgs(ConstVCall.Args))
9142       return true;
9143 
9144   if (parseToken(lltok::rparen, "expected ')' here"))
9145     return true;
9146 
9147   return false;
9148 }
9149 
9150 /// VFuncId
9151 ///   ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9152 ///         'offset' ':' UInt64 ')'
9153 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9154                             IdToIndexMapType &IdToIndexMap, unsigned Index) {
9155   assert(Lex.getKind() == lltok::kw_vFuncId);
9156   Lex.Lex();
9157 
9158   if (parseToken(lltok::colon, "expected ':' here") ||
9159       parseToken(lltok::lparen, "expected '(' here"))
9160     return true;
9161 
9162   if (Lex.getKind() == lltok::SummaryID) {
9163     VFuncId.GUID = 0;
9164     unsigned ID = Lex.getUIntVal();
9165     LocTy Loc = Lex.getLoc();
9166     // Keep track of the array index needing a forward reference.
9167     // We will save the location of the GUID needing an update, but
9168     // can only do so once the caller's std::vector is finalized.
9169     IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9170     Lex.Lex();
9171   } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9172              parseToken(lltok::colon, "expected ':' here") ||
9173              parseUInt64(VFuncId.GUID))
9174     return true;
9175 
9176   if (parseToken(lltok::comma, "expected ',' here") ||
9177       parseToken(lltok::kw_offset, "expected 'offset' here") ||
9178       parseToken(lltok::colon, "expected ':' here") ||
9179       parseUInt64(VFuncId.Offset) ||
9180       parseToken(lltok::rparen, "expected ')' here"))
9181     return true;
9182 
9183   return false;
9184 }
9185 
9186 /// GVFlags
9187 ///   ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9188 ///         'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9189 ///         'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9190 ///         'canAutoHide' ':' Flag ',' ')'
9191 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9192   assert(Lex.getKind() == lltok::kw_flags);
9193   Lex.Lex();
9194 
9195   if (parseToken(lltok::colon, "expected ':' here") ||
9196       parseToken(lltok::lparen, "expected '(' here"))
9197     return true;
9198 
9199   do {
9200     unsigned Flag = 0;
9201     switch (Lex.getKind()) {
9202     case lltok::kw_linkage:
9203       Lex.Lex();
9204       if (parseToken(lltok::colon, "expected ':'"))
9205         return true;
9206       bool HasLinkage;
9207       GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9208       assert(HasLinkage && "Linkage not optional in summary entry");
9209       Lex.Lex();
9210       break;
9211     case lltok::kw_visibility:
9212       Lex.Lex();
9213       if (parseToken(lltok::colon, "expected ':'"))
9214         return true;
9215       parseOptionalVisibility(Flag);
9216       GVFlags.Visibility = Flag;
9217       break;
9218     case lltok::kw_notEligibleToImport:
9219       Lex.Lex();
9220       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9221         return true;
9222       GVFlags.NotEligibleToImport = Flag;
9223       break;
9224     case lltok::kw_live:
9225       Lex.Lex();
9226       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9227         return true;
9228       GVFlags.Live = Flag;
9229       break;
9230     case lltok::kw_dsoLocal:
9231       Lex.Lex();
9232       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9233         return true;
9234       GVFlags.DSOLocal = Flag;
9235       break;
9236     case lltok::kw_canAutoHide:
9237       Lex.Lex();
9238       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9239         return true;
9240       GVFlags.CanAutoHide = Flag;
9241       break;
9242     default:
9243       return error(Lex.getLoc(), "expected gv flag type");
9244     }
9245   } while (EatIfPresent(lltok::comma));
9246 
9247   if (parseToken(lltok::rparen, "expected ')' here"))
9248     return true;
9249 
9250   return false;
9251 }
9252 
9253 /// GVarFlags
9254 ///   ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9255 ///                      ',' 'writeonly' ':' Flag
9256 ///                      ',' 'constant' ':' Flag ')'
9257 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9258   assert(Lex.getKind() == lltok::kw_varFlags);
9259   Lex.Lex();
9260 
9261   if (parseToken(lltok::colon, "expected ':' here") ||
9262       parseToken(lltok::lparen, "expected '(' here"))
9263     return true;
9264 
9265   auto ParseRest = [this](unsigned int &Val) {
9266     Lex.Lex();
9267     if (parseToken(lltok::colon, "expected ':'"))
9268       return true;
9269     return parseFlag(Val);
9270   };
9271 
9272   do {
9273     unsigned Flag = 0;
9274     switch (Lex.getKind()) {
9275     case lltok::kw_readonly:
9276       if (ParseRest(Flag))
9277         return true;
9278       GVarFlags.MaybeReadOnly = Flag;
9279       break;
9280     case lltok::kw_writeonly:
9281       if (ParseRest(Flag))
9282         return true;
9283       GVarFlags.MaybeWriteOnly = Flag;
9284       break;
9285     case lltok::kw_constant:
9286       if (ParseRest(Flag))
9287         return true;
9288       GVarFlags.Constant = Flag;
9289       break;
9290     case lltok::kw_vcall_visibility:
9291       if (ParseRest(Flag))
9292         return true;
9293       GVarFlags.VCallVisibility = Flag;
9294       break;
9295     default:
9296       return error(Lex.getLoc(), "expected gvar flag type");
9297     }
9298   } while (EatIfPresent(lltok::comma));
9299   return parseToken(lltok::rparen, "expected ')' here");
9300 }
9301 
9302 /// ModuleReference
9303 ///   ::= 'module' ':' UInt
9304 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9305   // parse module id.
9306   if (parseToken(lltok::kw_module, "expected 'module' here") ||
9307       parseToken(lltok::colon, "expected ':' here") ||
9308       parseToken(lltok::SummaryID, "expected module ID"))
9309     return true;
9310 
9311   unsigned ModuleID = Lex.getUIntVal();
9312   auto I = ModuleIdMap.find(ModuleID);
9313   // We should have already parsed all module IDs
9314   assert(I != ModuleIdMap.end());
9315   ModulePath = I->second;
9316   return false;
9317 }
9318 
9319 /// GVReference
9320 ///   ::= SummaryID
9321 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9322   bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9323   if (!ReadOnly)
9324     WriteOnly = EatIfPresent(lltok::kw_writeonly);
9325   if (parseToken(lltok::SummaryID, "expected GV ID"))
9326     return true;
9327 
9328   GVId = Lex.getUIntVal();
9329   // Check if we already have a VI for this GV
9330   if (GVId < NumberedValueInfos.size()) {
9331     assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9332     VI = NumberedValueInfos[GVId];
9333   } else
9334     // We will create a forward reference to the stored location.
9335     VI = ValueInfo(false, FwdVIRef);
9336 
9337   if (ReadOnly)
9338     VI.setReadOnly();
9339   if (WriteOnly)
9340     VI.setWriteOnly();
9341   return false;
9342 }
9343