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