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