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