xref: /llvm-project/llvm/lib/AsmParser/LLParser.cpp (revision 7fa0d05a04056aac4365c69c4b515f613a43e454)
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 = Intrinsic::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, {}), 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) {
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[std::move(Fn)][std::move(Label)];
4004       if (!FwdRef) {
4005         unsigned FwdDeclAS;
4006         if (ExpectedTy) {
4007           // If we know the type that the blockaddress is being assigned to,
4008           // we can use the address space of that type.
4009           if (!ExpectedTy->isPointerTy())
4010             return error(ID.Loc,
4011                          "type of blockaddress must be a pointer and not '" +
4012                              getTypeString(ExpectedTy) + "'");
4013           FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4014         } else if (PFS) {
4015           // Otherwise, we default the address space of the current function.
4016           FwdDeclAS = PFS->getFunction().getAddressSpace();
4017         } else {
4018           llvm_unreachable("Unknown address space for blockaddress");
4019         }
4020         FwdRef = new GlobalVariable(
4021             *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4022             nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4023       }
4024 
4025       ID.ConstantVal = FwdRef;
4026       ID.Kind = ValID::t_Constant;
4027       return false;
4028     }
4029 
4030     // We found the function; now find the basic block.  Don't use PFS, since we
4031     // might be inside a constant expression.
4032     BasicBlock *BB;
4033     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4034       if (Label.Kind == ValID::t_LocalID)
4035         BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4036       else
4037         BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4038       if (!BB)
4039         return error(Label.Loc, "referenced value is not a basic block");
4040     } else {
4041       if (Label.Kind == ValID::t_LocalID)
4042         return error(Label.Loc, "cannot take address of numeric label after "
4043                                 "the function is defined");
4044       BB = dyn_cast_or_null<BasicBlock>(
4045           F->getValueSymbolTable()->lookup(Label.StrVal));
4046       if (!BB)
4047         return error(Label.Loc, "referenced value is not a basic block");
4048     }
4049 
4050     ID.ConstantVal = BlockAddress::get(F, BB);
4051     ID.Kind = ValID::t_Constant;
4052     return false;
4053   }
4054 
4055   case lltok::kw_dso_local_equivalent: {
4056     // ValID ::= 'dso_local_equivalent' @foo
4057     Lex.Lex();
4058 
4059     ValID Fn;
4060 
4061     if (parseValID(Fn, PFS))
4062       return true;
4063 
4064     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
4065       return error(Fn.Loc,
4066                    "expected global value name in dso_local_equivalent");
4067 
4068     // Try to find the function (but skip it if it's forward-referenced).
4069     GlobalValue *GV = nullptr;
4070     if (Fn.Kind == ValID::t_GlobalID) {
4071       GV = NumberedVals.get(Fn.UIntVal);
4072     } else if (!ForwardRefVals.count(Fn.StrVal)) {
4073       GV = M->getNamedValue(Fn.StrVal);
4074     }
4075 
4076     if (!GV) {
4077       // Make a placeholder global variable as a placeholder for this reference.
4078       auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4079                             ? ForwardRefDSOLocalEquivalentIDs
4080                             : ForwardRefDSOLocalEquivalentNames;
4081       GlobalValue *&FwdRef = FwdRefMap[Fn];
4082       if (!FwdRef) {
4083         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4084                                     GlobalValue::InternalLinkage, nullptr, "",
4085                                     nullptr, GlobalValue::NotThreadLocal);
4086       }
4087 
4088       ID.ConstantVal = FwdRef;
4089       ID.Kind = ValID::t_Constant;
4090       return false;
4091     }
4092 
4093     if (!GV->getValueType()->isFunctionTy())
4094       return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4095                            "in dso_local_equivalent");
4096 
4097     ID.ConstantVal = DSOLocalEquivalent::get(GV);
4098     ID.Kind = ValID::t_Constant;
4099     return false;
4100   }
4101 
4102   case lltok::kw_no_cfi: {
4103     // ValID ::= 'no_cfi' @foo
4104     Lex.Lex();
4105 
4106     if (parseValID(ID, PFS))
4107       return true;
4108 
4109     if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4110       return error(ID.Loc, "expected global value name in no_cfi");
4111 
4112     ID.NoCFI = true;
4113     return false;
4114   }
4115   case lltok::kw_ptrauth: {
4116     // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4117     //                         (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4118     Lex.Lex();
4119 
4120     Constant *Ptr, *Key;
4121     Constant *Disc = nullptr, *AddrDisc = nullptr;
4122 
4123     if (parseToken(lltok::lparen,
4124                    "expected '(' in constant ptrauth expression") ||
4125         parseGlobalTypeAndValue(Ptr) ||
4126         parseToken(lltok::comma,
4127                    "expected comma in constant ptrauth expression") ||
4128         parseGlobalTypeAndValue(Key))
4129       return true;
4130     // If present, parse the optional disc/addrdisc.
4131     if (EatIfPresent(lltok::comma))
4132       if (parseGlobalTypeAndValue(Disc) ||
4133           (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4134         return true;
4135     if (parseToken(lltok::rparen,
4136                    "expected ')' in constant ptrauth expression"))
4137       return true;
4138 
4139     if (!Ptr->getType()->isPointerTy())
4140       return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4141 
4142     auto *KeyC = dyn_cast<ConstantInt>(Key);
4143     if (!KeyC || KeyC->getBitWidth() != 32)
4144       return error(ID.Loc, "constant ptrauth key must be i32 constant");
4145 
4146     ConstantInt *DiscC = nullptr;
4147     if (Disc) {
4148       DiscC = dyn_cast<ConstantInt>(Disc);
4149       if (!DiscC || DiscC->getBitWidth() != 64)
4150         return error(
4151             ID.Loc,
4152             "constant ptrauth integer discriminator must be i64 constant");
4153     } else {
4154       DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4155     }
4156 
4157     if (AddrDisc) {
4158       if (!AddrDisc->getType()->isPointerTy())
4159         return error(
4160             ID.Loc, "constant ptrauth address discriminator must be a pointer");
4161     } else {
4162       AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4163     }
4164 
4165     ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4166     ID.Kind = ValID::t_Constant;
4167     return false;
4168   }
4169 
4170   case lltok::kw_trunc:
4171   case lltok::kw_bitcast:
4172   case lltok::kw_addrspacecast:
4173   case lltok::kw_inttoptr:
4174   case lltok::kw_ptrtoint: {
4175     unsigned Opc = Lex.getUIntVal();
4176     Type *DestTy = nullptr;
4177     Constant *SrcVal;
4178     Lex.Lex();
4179     if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4180         parseGlobalTypeAndValue(SrcVal) ||
4181         parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4182         parseType(DestTy) ||
4183         parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4184       return true;
4185     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4186       return error(ID.Loc, "invalid cast opcode for cast from '" +
4187                                getTypeString(SrcVal->getType()) + "' to '" +
4188                                getTypeString(DestTy) + "'");
4189     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
4190                                                  SrcVal, DestTy);
4191     ID.Kind = ValID::t_Constant;
4192     return false;
4193   }
4194   case lltok::kw_extractvalue:
4195     return error(ID.Loc, "extractvalue constexprs are no longer supported");
4196   case lltok::kw_insertvalue:
4197     return error(ID.Loc, "insertvalue constexprs are no longer supported");
4198   case lltok::kw_udiv:
4199     return error(ID.Loc, "udiv constexprs are no longer supported");
4200   case lltok::kw_sdiv:
4201     return error(ID.Loc, "sdiv constexprs are no longer supported");
4202   case lltok::kw_urem:
4203     return error(ID.Loc, "urem constexprs are no longer supported");
4204   case lltok::kw_srem:
4205     return error(ID.Loc, "srem constexprs are no longer supported");
4206   case lltok::kw_fadd:
4207     return error(ID.Loc, "fadd constexprs are no longer supported");
4208   case lltok::kw_fsub:
4209     return error(ID.Loc, "fsub constexprs are no longer supported");
4210   case lltok::kw_fmul:
4211     return error(ID.Loc, "fmul constexprs are no longer supported");
4212   case lltok::kw_fdiv:
4213     return error(ID.Loc, "fdiv constexprs are no longer supported");
4214   case lltok::kw_frem:
4215     return error(ID.Loc, "frem constexprs are no longer supported");
4216   case lltok::kw_and:
4217     return error(ID.Loc, "and constexprs are no longer supported");
4218   case lltok::kw_or:
4219     return error(ID.Loc, "or constexprs are no longer supported");
4220   case lltok::kw_lshr:
4221     return error(ID.Loc, "lshr constexprs are no longer supported");
4222   case lltok::kw_ashr:
4223     return error(ID.Loc, "ashr constexprs are no longer supported");
4224   case lltok::kw_shl:
4225     return error(ID.Loc, "shl constexprs are no longer supported");
4226   case lltok::kw_fneg:
4227     return error(ID.Loc, "fneg constexprs are no longer supported");
4228   case lltok::kw_select:
4229     return error(ID.Loc, "select constexprs are no longer supported");
4230   case lltok::kw_zext:
4231     return error(ID.Loc, "zext constexprs are no longer supported");
4232   case lltok::kw_sext:
4233     return error(ID.Loc, "sext constexprs are no longer supported");
4234   case lltok::kw_fptrunc:
4235     return error(ID.Loc, "fptrunc constexprs are no longer supported");
4236   case lltok::kw_fpext:
4237     return error(ID.Loc, "fpext constexprs are no longer supported");
4238   case lltok::kw_uitofp:
4239     return error(ID.Loc, "uitofp constexprs are no longer supported");
4240   case lltok::kw_sitofp:
4241     return error(ID.Loc, "sitofp constexprs are no longer supported");
4242   case lltok::kw_fptoui:
4243     return error(ID.Loc, "fptoui constexprs are no longer supported");
4244   case lltok::kw_fptosi:
4245     return error(ID.Loc, "fptosi constexprs are no longer supported");
4246   case lltok::kw_icmp:
4247     return error(ID.Loc, "icmp constexprs are no longer supported");
4248   case lltok::kw_fcmp:
4249     return error(ID.Loc, "fcmp constexprs are no longer supported");
4250 
4251   // Binary Operators.
4252   case lltok::kw_add:
4253   case lltok::kw_sub:
4254   case lltok::kw_mul:
4255   case lltok::kw_xor: {
4256     bool NUW = false;
4257     bool NSW = false;
4258     unsigned Opc = Lex.getUIntVal();
4259     Constant *Val0, *Val1;
4260     Lex.Lex();
4261     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4262         Opc == Instruction::Mul) {
4263       if (EatIfPresent(lltok::kw_nuw))
4264         NUW = true;
4265       if (EatIfPresent(lltok::kw_nsw)) {
4266         NSW = true;
4267         if (EatIfPresent(lltok::kw_nuw))
4268           NUW = true;
4269       }
4270     }
4271     if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4272         parseGlobalTypeAndValue(Val0) ||
4273         parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4274         parseGlobalTypeAndValue(Val1) ||
4275         parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4276       return true;
4277     if (Val0->getType() != Val1->getType())
4278       return error(ID.Loc, "operands of constexpr must have same type");
4279     // Check that the type is valid for the operator.
4280     if (!Val0->getType()->isIntOrIntVectorTy())
4281       return error(ID.Loc,
4282                    "constexpr requires integer or integer vector operands");
4283     unsigned Flags = 0;
4284     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
4285     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
4286     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4287     ID.Kind = ValID::t_Constant;
4288     return false;
4289   }
4290 
4291   case lltok::kw_splat: {
4292     Lex.Lex();
4293     if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4294       return true;
4295     Constant *C;
4296     if (parseGlobalTypeAndValue(C))
4297       return true;
4298     if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4299       return true;
4300 
4301     ID.ConstantVal = C;
4302     ID.Kind = ValID::t_ConstantSplat;
4303     return false;
4304   }
4305 
4306   case lltok::kw_getelementptr:
4307   case lltok::kw_shufflevector:
4308   case lltok::kw_insertelement:
4309   case lltok::kw_extractelement: {
4310     unsigned Opc = Lex.getUIntVal();
4311     SmallVector<Constant*, 16> Elts;
4312     GEPNoWrapFlags NW;
4313     bool HasInRange = false;
4314     APSInt InRangeStart;
4315     APSInt InRangeEnd;
4316     Type *Ty;
4317     Lex.Lex();
4318 
4319     if (Opc == Instruction::GetElementPtr) {
4320       while (true) {
4321         if (EatIfPresent(lltok::kw_inbounds))
4322           NW |= GEPNoWrapFlags::inBounds();
4323         else if (EatIfPresent(lltok::kw_nusw))
4324           NW |= GEPNoWrapFlags::noUnsignedSignedWrap();
4325         else if (EatIfPresent(lltok::kw_nuw))
4326           NW |= GEPNoWrapFlags::noUnsignedWrap();
4327         else
4328           break;
4329       }
4330 
4331       if (EatIfPresent(lltok::kw_inrange)) {
4332         if (parseToken(lltok::lparen, "expected '('"))
4333           return true;
4334         if (Lex.getKind() != lltok::APSInt)
4335           return tokError("expected integer");
4336         InRangeStart = Lex.getAPSIntVal();
4337         Lex.Lex();
4338         if (parseToken(lltok::comma, "expected ','"))
4339           return true;
4340         if (Lex.getKind() != lltok::APSInt)
4341           return tokError("expected integer");
4342         InRangeEnd = Lex.getAPSIntVal();
4343         Lex.Lex();
4344         if (parseToken(lltok::rparen, "expected ')'"))
4345           return true;
4346         HasInRange = true;
4347       }
4348     }
4349 
4350     if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4351       return true;
4352 
4353     if (Opc == Instruction::GetElementPtr) {
4354       if (parseType(Ty) ||
4355           parseToken(lltok::comma, "expected comma after getelementptr's type"))
4356         return true;
4357     }
4358 
4359     if (parseGlobalValueVector(Elts) ||
4360         parseToken(lltok::rparen, "expected ')' in constantexpr"))
4361       return true;
4362 
4363     if (Opc == Instruction::GetElementPtr) {
4364       if (Elts.size() == 0 ||
4365           !Elts[0]->getType()->isPtrOrPtrVectorTy())
4366         return error(ID.Loc, "base of getelementptr must be a pointer");
4367 
4368       Type *BaseType = Elts[0]->getType();
4369       std::optional<ConstantRange> InRange;
4370       if (HasInRange) {
4371         unsigned IndexWidth =
4372             M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4373         InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4374         InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4375         if (InRangeStart.sge(InRangeEnd))
4376           return error(ID.Loc, "expected end to be larger than start");
4377         InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4378       }
4379 
4380       unsigned GEPWidth =
4381           BaseType->isVectorTy()
4382               ? cast<FixedVectorType>(BaseType)->getNumElements()
4383               : 0;
4384 
4385       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4386       for (Constant *Val : Indices) {
4387         Type *ValTy = Val->getType();
4388         if (!ValTy->isIntOrIntVectorTy())
4389           return error(ID.Loc, "getelementptr index must be an integer");
4390         if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4391           unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4392           if (GEPWidth && (ValNumEl != GEPWidth))
4393             return error(
4394                 ID.Loc,
4395                 "getelementptr vector index has a wrong number of elements");
4396           // GEPWidth may have been unknown because the base is a scalar,
4397           // but it is known now.
4398           GEPWidth = ValNumEl;
4399         }
4400       }
4401 
4402       SmallPtrSet<Type*, 4> Visited;
4403       if (!Indices.empty() && !Ty->isSized(&Visited))
4404         return error(ID.Loc, "base element of getelementptr must be sized");
4405 
4406       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4407         return error(ID.Loc, "invalid getelementptr indices");
4408 
4409       ID.ConstantVal =
4410           ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4411     } else if (Opc == Instruction::ShuffleVector) {
4412       if (Elts.size() != 3)
4413         return error(ID.Loc, "expected three operands to shufflevector");
4414       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4415         return error(ID.Loc, "invalid operands to shufflevector");
4416       SmallVector<int, 16> Mask;
4417       ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
4418       ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4419     } else if (Opc == Instruction::ExtractElement) {
4420       if (Elts.size() != 2)
4421         return error(ID.Loc, "expected two operands to extractelement");
4422       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4423         return error(ID.Loc, "invalid extractelement operands");
4424       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4425     } else {
4426       assert(Opc == Instruction::InsertElement && "Unknown opcode");
4427       if (Elts.size() != 3)
4428         return error(ID.Loc, "expected three operands to insertelement");
4429       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4430         return error(ID.Loc, "invalid insertelement operands");
4431       ID.ConstantVal =
4432                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4433     }
4434 
4435     ID.Kind = ValID::t_Constant;
4436     return false;
4437   }
4438   }
4439 
4440   Lex.Lex();
4441   return false;
4442 }
4443 
4444 /// parseGlobalValue - parse a global value with the specified type.
4445 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4446   C = nullptr;
4447   ValID ID;
4448   Value *V = nullptr;
4449   bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4450                 convertValIDToValue(Ty, ID, V, nullptr);
4451   if (V && !(C = dyn_cast<Constant>(V)))
4452     return error(ID.Loc, "global values must be constants");
4453   return Parsed;
4454 }
4455 
4456 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4457   Type *Ty = nullptr;
4458   return parseType(Ty) || parseGlobalValue(Ty, V);
4459 }
4460 
4461 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4462   C = nullptr;
4463 
4464   LocTy KwLoc = Lex.getLoc();
4465   if (!EatIfPresent(lltok::kw_comdat))
4466     return false;
4467 
4468   if (EatIfPresent(lltok::lparen)) {
4469     if (Lex.getKind() != lltok::ComdatVar)
4470       return tokError("expected comdat variable");
4471     C = getComdat(Lex.getStrVal(), Lex.getLoc());
4472     Lex.Lex();
4473     if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4474       return true;
4475   } else {
4476     if (GlobalName.empty())
4477       return tokError("comdat cannot be unnamed");
4478     C = getComdat(std::string(GlobalName), KwLoc);
4479   }
4480 
4481   return false;
4482 }
4483 
4484 /// parseGlobalValueVector
4485 ///   ::= /*empty*/
4486 ///   ::= TypeAndValue (',' TypeAndValue)*
4487 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4488   // Empty list.
4489   if (Lex.getKind() == lltok::rbrace ||
4490       Lex.getKind() == lltok::rsquare ||
4491       Lex.getKind() == lltok::greater ||
4492       Lex.getKind() == lltok::rparen)
4493     return false;
4494 
4495   do {
4496     // Let the caller deal with inrange.
4497     if (Lex.getKind() == lltok::kw_inrange)
4498       return false;
4499 
4500     Constant *C;
4501     if (parseGlobalTypeAndValue(C))
4502       return true;
4503     Elts.push_back(C);
4504   } while (EatIfPresent(lltok::comma));
4505 
4506   return false;
4507 }
4508 
4509 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4510   SmallVector<Metadata *, 16> Elts;
4511   if (parseMDNodeVector(Elts))
4512     return true;
4513 
4514   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4515   return false;
4516 }
4517 
4518 /// MDNode:
4519 ///  ::= !{ ... }
4520 ///  ::= !7
4521 ///  ::= !DILocation(...)
4522 bool LLParser::parseMDNode(MDNode *&N) {
4523   if (Lex.getKind() == lltok::MetadataVar)
4524     return parseSpecializedMDNode(N);
4525 
4526   return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4527 }
4528 
4529 bool LLParser::parseMDNodeTail(MDNode *&N) {
4530   // !{ ... }
4531   if (Lex.getKind() == lltok::lbrace)
4532     return parseMDTuple(N);
4533 
4534   // !42
4535   return parseMDNodeID(N);
4536 }
4537 
4538 namespace {
4539 
4540 /// Structure to represent an optional metadata field.
4541 template <class FieldTy> struct MDFieldImpl {
4542   typedef MDFieldImpl ImplTy;
4543   FieldTy Val;
4544   bool Seen;
4545 
4546   void assign(FieldTy Val) {
4547     Seen = true;
4548     this->Val = std::move(Val);
4549   }
4550 
4551   explicit MDFieldImpl(FieldTy Default)
4552       : Val(std::move(Default)), Seen(false) {}
4553 };
4554 
4555 /// Structure to represent an optional metadata field that
4556 /// can be of either type (A or B) and encapsulates the
4557 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4558 /// to reimplement the specifics for representing each Field.
4559 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4560   typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4561   FieldTypeA A;
4562   FieldTypeB B;
4563   bool Seen;
4564 
4565   enum {
4566     IsInvalid = 0,
4567     IsTypeA = 1,
4568     IsTypeB = 2
4569   } WhatIs;
4570 
4571   void assign(FieldTypeA A) {
4572     Seen = true;
4573     this->A = std::move(A);
4574     WhatIs = IsTypeA;
4575   }
4576 
4577   void assign(FieldTypeB B) {
4578     Seen = true;
4579     this->B = std::move(B);
4580     WhatIs = IsTypeB;
4581   }
4582 
4583   explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4584       : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4585         WhatIs(IsInvalid) {}
4586 };
4587 
4588 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4589   uint64_t Max;
4590 
4591   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4592       : ImplTy(Default), Max(Max) {}
4593 };
4594 
4595 struct LineField : public MDUnsignedField {
4596   LineField() : MDUnsignedField(0, UINT32_MAX) {}
4597 };
4598 
4599 struct ColumnField : public MDUnsignedField {
4600   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4601 };
4602 
4603 struct DwarfTagField : public MDUnsignedField {
4604   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4605   DwarfTagField(dwarf::Tag DefaultTag)
4606       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4607 };
4608 
4609 struct DwarfMacinfoTypeField : public MDUnsignedField {
4610   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4611   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4612     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4613 };
4614 
4615 struct DwarfAttEncodingField : public MDUnsignedField {
4616   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4617 };
4618 
4619 struct DwarfVirtualityField : public MDUnsignedField {
4620   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4621 };
4622 
4623 struct DwarfLangField : public MDUnsignedField {
4624   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4625 };
4626 
4627 struct DwarfCCField : public MDUnsignedField {
4628   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4629 };
4630 
4631 struct EmissionKindField : public MDUnsignedField {
4632   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4633 };
4634 
4635 struct NameTableKindField : public MDUnsignedField {
4636   NameTableKindField()
4637       : MDUnsignedField(
4638             0, (unsigned)
4639                    DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4640 };
4641 
4642 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4643   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4644 };
4645 
4646 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4647   DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4648 };
4649 
4650 struct MDAPSIntField : public MDFieldImpl<APSInt> {
4651   MDAPSIntField() : ImplTy(APSInt()) {}
4652 };
4653 
4654 struct MDSignedField : public MDFieldImpl<int64_t> {
4655   int64_t Min = INT64_MIN;
4656   int64_t Max = INT64_MAX;
4657 
4658   MDSignedField(int64_t Default = 0)
4659       : ImplTy(Default) {}
4660   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4661       : ImplTy(Default), Min(Min), Max(Max) {}
4662 };
4663 
4664 struct MDBoolField : public MDFieldImpl<bool> {
4665   MDBoolField(bool Default = false) : ImplTy(Default) {}
4666 };
4667 
4668 struct MDField : public MDFieldImpl<Metadata *> {
4669   bool AllowNull;
4670 
4671   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4672 };
4673 
4674 struct MDStringField : public MDFieldImpl<MDString *> {
4675   bool AllowEmpty;
4676   MDStringField(bool AllowEmpty = true)
4677       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4678 };
4679 
4680 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4681   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4682 };
4683 
4684 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4685   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4686 };
4687 
4688 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4689   MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4690       : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4691 
4692   MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4693                     bool AllowNull = true)
4694       : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4695 
4696   bool isMDSignedField() const { return WhatIs == IsTypeA; }
4697   bool isMDField() const { return WhatIs == IsTypeB; }
4698   int64_t getMDSignedValue() const {
4699     assert(isMDSignedField() && "Wrong field type");
4700     return A.Val;
4701   }
4702   Metadata *getMDFieldValue() const {
4703     assert(isMDField() && "Wrong field type");
4704     return B.Val;
4705   }
4706 };
4707 
4708 } // end anonymous namespace
4709 
4710 namespace llvm {
4711 
4712 template <>
4713 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4714   if (Lex.getKind() != lltok::APSInt)
4715     return tokError("expected integer");
4716 
4717   Result.assign(Lex.getAPSIntVal());
4718   Lex.Lex();
4719   return false;
4720 }
4721 
4722 template <>
4723 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4724                             MDUnsignedField &Result) {
4725   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4726     return tokError("expected unsigned integer");
4727 
4728   auto &U = Lex.getAPSIntVal();
4729   if (U.ugt(Result.Max))
4730     return tokError("value for '" + Name + "' too large, limit is " +
4731                     Twine(Result.Max));
4732   Result.assign(U.getZExtValue());
4733   assert(Result.Val <= Result.Max && "Expected value in range");
4734   Lex.Lex();
4735   return false;
4736 }
4737 
4738 template <>
4739 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4740   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4741 }
4742 template <>
4743 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4744   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4745 }
4746 
4747 template <>
4748 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4749   if (Lex.getKind() == lltok::APSInt)
4750     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4751 
4752   if (Lex.getKind() != lltok::DwarfTag)
4753     return tokError("expected DWARF tag");
4754 
4755   unsigned Tag = dwarf::getTag(Lex.getStrVal());
4756   if (Tag == dwarf::DW_TAG_invalid)
4757     return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4758   assert(Tag <= Result.Max && "Expected valid DWARF tag");
4759 
4760   Result.assign(Tag);
4761   Lex.Lex();
4762   return false;
4763 }
4764 
4765 template <>
4766 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4767                             DwarfMacinfoTypeField &Result) {
4768   if (Lex.getKind() == lltok::APSInt)
4769     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4770 
4771   if (Lex.getKind() != lltok::DwarfMacinfo)
4772     return tokError("expected DWARF macinfo type");
4773 
4774   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4775   if (Macinfo == dwarf::DW_MACINFO_invalid)
4776     return tokError("invalid DWARF macinfo type" + Twine(" '") +
4777                     Lex.getStrVal() + "'");
4778   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4779 
4780   Result.assign(Macinfo);
4781   Lex.Lex();
4782   return false;
4783 }
4784 
4785 template <>
4786 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4787                             DwarfVirtualityField &Result) {
4788   if (Lex.getKind() == lltok::APSInt)
4789     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4790 
4791   if (Lex.getKind() != lltok::DwarfVirtuality)
4792     return tokError("expected DWARF virtuality code");
4793 
4794   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4795   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4796     return tokError("invalid DWARF virtuality code" + Twine(" '") +
4797                     Lex.getStrVal() + "'");
4798   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4799   Result.assign(Virtuality);
4800   Lex.Lex();
4801   return false;
4802 }
4803 
4804 template <>
4805 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4806   if (Lex.getKind() == lltok::APSInt)
4807     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4808 
4809   if (Lex.getKind() != lltok::DwarfLang)
4810     return tokError("expected DWARF language");
4811 
4812   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4813   if (!Lang)
4814     return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4815                     "'");
4816   assert(Lang <= Result.Max && "Expected valid DWARF language");
4817   Result.assign(Lang);
4818   Lex.Lex();
4819   return false;
4820 }
4821 
4822 template <>
4823 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4824   if (Lex.getKind() == lltok::APSInt)
4825     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4826 
4827   if (Lex.getKind() != lltok::DwarfCC)
4828     return tokError("expected DWARF calling convention");
4829 
4830   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4831   if (!CC)
4832     return tokError("invalid DWARF calling convention" + Twine(" '") +
4833                     Lex.getStrVal() + "'");
4834   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4835   Result.assign(CC);
4836   Lex.Lex();
4837   return false;
4838 }
4839 
4840 template <>
4841 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4842                             EmissionKindField &Result) {
4843   if (Lex.getKind() == lltok::APSInt)
4844     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4845 
4846   if (Lex.getKind() != lltok::EmissionKind)
4847     return tokError("expected emission kind");
4848 
4849   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4850   if (!Kind)
4851     return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4852                     "'");
4853   assert(*Kind <= Result.Max && "Expected valid emission kind");
4854   Result.assign(*Kind);
4855   Lex.Lex();
4856   return false;
4857 }
4858 
4859 template <>
4860 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4861                             NameTableKindField &Result) {
4862   if (Lex.getKind() == lltok::APSInt)
4863     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4864 
4865   if (Lex.getKind() != lltok::NameTableKind)
4866     return tokError("expected nameTable kind");
4867 
4868   auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4869   if (!Kind)
4870     return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4871                     "'");
4872   assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4873   Result.assign((unsigned)*Kind);
4874   Lex.Lex();
4875   return false;
4876 }
4877 
4878 template <>
4879 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4880                             DwarfAttEncodingField &Result) {
4881   if (Lex.getKind() == lltok::APSInt)
4882     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4883 
4884   if (Lex.getKind() != lltok::DwarfAttEncoding)
4885     return tokError("expected DWARF type attribute encoding");
4886 
4887   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4888   if (!Encoding)
4889     return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4890                     Lex.getStrVal() + "'");
4891   assert(Encoding <= Result.Max && "Expected valid DWARF language");
4892   Result.assign(Encoding);
4893   Lex.Lex();
4894   return false;
4895 }
4896 
4897 /// DIFlagField
4898 ///  ::= uint32
4899 ///  ::= DIFlagVector
4900 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4901 template <>
4902 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4903 
4904   // parser for a single flag.
4905   auto parseFlag = [&](DINode::DIFlags &Val) {
4906     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4907       uint32_t TempVal = static_cast<uint32_t>(Val);
4908       bool Res = parseUInt32(TempVal);
4909       Val = static_cast<DINode::DIFlags>(TempVal);
4910       return Res;
4911     }
4912 
4913     if (Lex.getKind() != lltok::DIFlag)
4914       return tokError("expected debug info flag");
4915 
4916     Val = DINode::getFlag(Lex.getStrVal());
4917     if (!Val)
4918       return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4919                       "'");
4920     Lex.Lex();
4921     return false;
4922   };
4923 
4924   // parse the flags and combine them together.
4925   DINode::DIFlags Combined = DINode::FlagZero;
4926   do {
4927     DINode::DIFlags Val;
4928     if (parseFlag(Val))
4929       return true;
4930     Combined |= Val;
4931   } while (EatIfPresent(lltok::bar));
4932 
4933   Result.assign(Combined);
4934   return false;
4935 }
4936 
4937 /// DISPFlagField
4938 ///  ::= uint32
4939 ///  ::= DISPFlagVector
4940 ///  ::= DISPFlagVector '|' DISPFlag* '|' uint32
4941 template <>
4942 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4943 
4944   // parser for a single flag.
4945   auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4946     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4947       uint32_t TempVal = static_cast<uint32_t>(Val);
4948       bool Res = parseUInt32(TempVal);
4949       Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4950       return Res;
4951     }
4952 
4953     if (Lex.getKind() != lltok::DISPFlag)
4954       return tokError("expected debug info flag");
4955 
4956     Val = DISubprogram::getFlag(Lex.getStrVal());
4957     if (!Val)
4958       return tokError(Twine("invalid subprogram debug info flag '") +
4959                       Lex.getStrVal() + "'");
4960     Lex.Lex();
4961     return false;
4962   };
4963 
4964   // parse the flags and combine them together.
4965   DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4966   do {
4967     DISubprogram::DISPFlags Val;
4968     if (parseFlag(Val))
4969       return true;
4970     Combined |= Val;
4971   } while (EatIfPresent(lltok::bar));
4972 
4973   Result.assign(Combined);
4974   return false;
4975 }
4976 
4977 template <>
4978 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4979   if (Lex.getKind() != lltok::APSInt)
4980     return tokError("expected signed integer");
4981 
4982   auto &S = Lex.getAPSIntVal();
4983   if (S < Result.Min)
4984     return tokError("value for '" + Name + "' too small, limit is " +
4985                     Twine(Result.Min));
4986   if (S > Result.Max)
4987     return tokError("value for '" + Name + "' too large, limit is " +
4988                     Twine(Result.Max));
4989   Result.assign(S.getExtValue());
4990   assert(Result.Val >= Result.Min && "Expected value in range");
4991   assert(Result.Val <= Result.Max && "Expected value in range");
4992   Lex.Lex();
4993   return false;
4994 }
4995 
4996 template <>
4997 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4998   switch (Lex.getKind()) {
4999   default:
5000     return tokError("expected 'true' or 'false'");
5001   case lltok::kw_true:
5002     Result.assign(true);
5003     break;
5004   case lltok::kw_false:
5005     Result.assign(false);
5006     break;
5007   }
5008   Lex.Lex();
5009   return false;
5010 }
5011 
5012 template <>
5013 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5014   if (Lex.getKind() == lltok::kw_null) {
5015     if (!Result.AllowNull)
5016       return tokError("'" + Name + "' cannot be null");
5017     Lex.Lex();
5018     Result.assign(nullptr);
5019     return false;
5020   }
5021 
5022   Metadata *MD;
5023   if (parseMetadata(MD, nullptr))
5024     return true;
5025 
5026   Result.assign(MD);
5027   return false;
5028 }
5029 
5030 template <>
5031 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5032                             MDSignedOrMDField &Result) {
5033   // Try to parse a signed int.
5034   if (Lex.getKind() == lltok::APSInt) {
5035     MDSignedField Res = Result.A;
5036     if (!parseMDField(Loc, Name, Res)) {
5037       Result.assign(Res);
5038       return false;
5039     }
5040     return true;
5041   }
5042 
5043   // Otherwise, try to parse as an MDField.
5044   MDField Res = Result.B;
5045   if (!parseMDField(Loc, Name, Res)) {
5046     Result.assign(Res);
5047     return false;
5048   }
5049 
5050   return true;
5051 }
5052 
5053 template <>
5054 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5055   LocTy ValueLoc = Lex.getLoc();
5056   std::string S;
5057   if (parseStringConstant(S))
5058     return true;
5059 
5060   if (!Result.AllowEmpty && S.empty())
5061     return error(ValueLoc, "'" + Name + "' cannot be empty");
5062 
5063   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
5064   return false;
5065 }
5066 
5067 template <>
5068 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5069   SmallVector<Metadata *, 4> MDs;
5070   if (parseMDNodeVector(MDs))
5071     return true;
5072 
5073   Result.assign(std::move(MDs));
5074   return false;
5075 }
5076 
5077 template <>
5078 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5079                             ChecksumKindField &Result) {
5080   std::optional<DIFile::ChecksumKind> CSKind =
5081       DIFile::getChecksumKind(Lex.getStrVal());
5082 
5083   if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5084     return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5085                     "'");
5086 
5087   Result.assign(*CSKind);
5088   Lex.Lex();
5089   return false;
5090 }
5091 
5092 } // end namespace llvm
5093 
5094 template <class ParserTy>
5095 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5096   do {
5097     if (Lex.getKind() != lltok::LabelStr)
5098       return tokError("expected field label here");
5099 
5100     if (ParseField())
5101       return true;
5102   } while (EatIfPresent(lltok::comma));
5103 
5104   return false;
5105 }
5106 
5107 template <class ParserTy>
5108 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5109   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5110   Lex.Lex();
5111 
5112   if (parseToken(lltok::lparen, "expected '(' here"))
5113     return true;
5114   if (Lex.getKind() != lltok::rparen)
5115     if (parseMDFieldsImplBody(ParseField))
5116       return true;
5117 
5118   ClosingLoc = Lex.getLoc();
5119   return parseToken(lltok::rparen, "expected ')' here");
5120 }
5121 
5122 template <class FieldTy>
5123 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5124   if (Result.Seen)
5125     return tokError("field '" + Name + "' cannot be specified more than once");
5126 
5127   LocTy Loc = Lex.getLoc();
5128   Lex.Lex();
5129   return parseMDField(Loc, Name, Result);
5130 }
5131 
5132 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5133   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5134 
5135 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
5136   if (Lex.getStrVal() == #CLASS)                                               \
5137     return parse##CLASS(N, IsDistinct);
5138 #include "llvm/IR/Metadata.def"
5139 
5140   return tokError("expected metadata type");
5141 }
5142 
5143 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5144 #define NOP_FIELD(NAME, TYPE, INIT)
5145 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
5146   if (!NAME.Seen)                                                              \
5147     return error(ClosingLoc, "missing required field '" #NAME "'");
5148 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
5149   if (Lex.getStrVal() == #NAME)                                                \
5150     return parseMDField(#NAME, NAME);
5151 #define PARSE_MD_FIELDS()                                                      \
5152   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
5153   do {                                                                         \
5154     LocTy ClosingLoc;                                                          \
5155     if (parseMDFieldsImpl(                                                     \
5156             [&]() -> bool {                                                    \
5157               VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                  \
5158               return tokError(Twine("invalid field '") + Lex.getStrVal() +     \
5159                               "'");                                            \
5160             },                                                                 \
5161             ClosingLoc))                                                       \
5162       return true;                                                             \
5163     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
5164   } while (false)
5165 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
5166   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5167 
5168 /// parseDILocationFields:
5169 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5170 ///   isImplicitCode: true)
5171 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5172 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5173   OPTIONAL(line, LineField, );                                                 \
5174   OPTIONAL(column, ColumnField, );                                             \
5175   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5176   OPTIONAL(inlinedAt, MDField, );                                              \
5177   OPTIONAL(isImplicitCode, MDBoolField, (false));
5178   PARSE_MD_FIELDS();
5179 #undef VISIT_MD_FIELDS
5180 
5181   Result =
5182       GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5183                                    inlinedAt.Val, isImplicitCode.Val));
5184   return false;
5185 }
5186 
5187 /// parseDIAssignID:
5188 ///   ::= distinct !DIAssignID()
5189 bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5190   if (!IsDistinct)
5191     return tokError("missing 'distinct', required for !DIAssignID()");
5192 
5193   Lex.Lex();
5194 
5195   // Now eat the parens.
5196   if (parseToken(lltok::lparen, "expected '(' here"))
5197     return true;
5198   if (parseToken(lltok::rparen, "expected ')' here"))
5199     return true;
5200 
5201   Result = DIAssignID::getDistinct(Context);
5202   return false;
5203 }
5204 
5205 /// parseGenericDINode:
5206 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5207 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5208 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5209   REQUIRED(tag, DwarfTagField, );                                              \
5210   OPTIONAL(header, MDStringField, );                                           \
5211   OPTIONAL(operands, MDFieldList, );
5212   PARSE_MD_FIELDS();
5213 #undef VISIT_MD_FIELDS
5214 
5215   Result = GET_OR_DISTINCT(GenericDINode,
5216                            (Context, tag.Val, header.Val, operands.Val));
5217   return false;
5218 }
5219 
5220 /// parseDISubrange:
5221 ///   ::= !DISubrange(count: 30, lowerBound: 2)
5222 ///   ::= !DISubrange(count: !node, lowerBound: 2)
5223 ///   ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5224 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5225 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5226   OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false));              \
5227   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
5228   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
5229   OPTIONAL(stride, MDSignedOrMDField, );
5230   PARSE_MD_FIELDS();
5231 #undef VISIT_MD_FIELDS
5232 
5233   Metadata *Count = nullptr;
5234   Metadata *LowerBound = nullptr;
5235   Metadata *UpperBound = nullptr;
5236   Metadata *Stride = nullptr;
5237 
5238   auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5239     if (Bound.isMDSignedField())
5240       return ConstantAsMetadata::get(ConstantInt::getSigned(
5241           Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5242     if (Bound.isMDField())
5243       return Bound.getMDFieldValue();
5244     return nullptr;
5245   };
5246 
5247   Count = convToMetadata(count);
5248   LowerBound = convToMetadata(lowerBound);
5249   UpperBound = convToMetadata(upperBound);
5250   Stride = convToMetadata(stride);
5251 
5252   Result = GET_OR_DISTINCT(DISubrange,
5253                            (Context, Count, LowerBound, UpperBound, Stride));
5254 
5255   return false;
5256 }
5257 
5258 /// parseDIGenericSubrange:
5259 ///   ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5260 ///   !node3)
5261 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5262 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5263   OPTIONAL(count, MDSignedOrMDField, );                                        \
5264   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
5265   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
5266   OPTIONAL(stride, MDSignedOrMDField, );
5267   PARSE_MD_FIELDS();
5268 #undef VISIT_MD_FIELDS
5269 
5270   auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5271     if (Bound.isMDSignedField())
5272       return DIExpression::get(
5273           Context, {dwarf::DW_OP_consts,
5274                     static_cast<uint64_t>(Bound.getMDSignedValue())});
5275     if (Bound.isMDField())
5276       return Bound.getMDFieldValue();
5277     return nullptr;
5278   };
5279 
5280   Metadata *Count = ConvToMetadata(count);
5281   Metadata *LowerBound = ConvToMetadata(lowerBound);
5282   Metadata *UpperBound = ConvToMetadata(upperBound);
5283   Metadata *Stride = ConvToMetadata(stride);
5284 
5285   Result = GET_OR_DISTINCT(DIGenericSubrange,
5286                            (Context, Count, LowerBound, UpperBound, Stride));
5287 
5288   return false;
5289 }
5290 
5291 /// parseDIEnumerator:
5292 ///   ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5293 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5294 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5295   REQUIRED(name, MDStringField, );                                             \
5296   REQUIRED(value, MDAPSIntField, );                                            \
5297   OPTIONAL(isUnsigned, MDBoolField, (false));
5298   PARSE_MD_FIELDS();
5299 #undef VISIT_MD_FIELDS
5300 
5301   if (isUnsigned.Val && value.Val.isNegative())
5302     return tokError("unsigned enumerator with negative value");
5303 
5304   APSInt Value(value.Val);
5305   // Add a leading zero so that unsigned values with the msb set are not
5306   // mistaken for negative values when used for signed enumerators.
5307   if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5308     Value = Value.zext(Value.getBitWidth() + 1);
5309 
5310   Result =
5311       GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5312 
5313   return false;
5314 }
5315 
5316 /// parseDIBasicType:
5317 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5318 ///                    encoding: DW_ATE_encoding, flags: 0)
5319 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5320 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5321   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
5322   OPTIONAL(name, MDStringField, );                                             \
5323   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
5324   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5325   OPTIONAL(encoding, DwarfAttEncodingField, );                                 \
5326   OPTIONAL(flags, DIFlagField, );
5327   PARSE_MD_FIELDS();
5328 #undef VISIT_MD_FIELDS
5329 
5330   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
5331                                          align.Val, encoding.Val, flags.Val));
5332   return false;
5333 }
5334 
5335 /// parseDIStringType:
5336 ///   ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5337 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5338 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5339   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type));                   \
5340   OPTIONAL(name, MDStringField, );                                             \
5341   OPTIONAL(stringLength, MDField, );                                           \
5342   OPTIONAL(stringLengthExpression, MDField, );                                 \
5343   OPTIONAL(stringLocationExpression, MDField, );                               \
5344   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
5345   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5346   OPTIONAL(encoding, DwarfAttEncodingField, );
5347   PARSE_MD_FIELDS();
5348 #undef VISIT_MD_FIELDS
5349 
5350   Result = GET_OR_DISTINCT(
5351       DIStringType,
5352       (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5353        stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
5354   return false;
5355 }
5356 
5357 /// parseDIDerivedType:
5358 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5359 ///                      line: 7, scope: !1, baseType: !2, size: 32,
5360 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
5361 ///                      dwarfAddressSpace: 3, ptrAuthKey: 1,
5362 ///                      ptrAuthIsAddressDiscriminated: true,
5363 ///                      ptrAuthExtraDiscriminator: 0x1234,
5364 ///                      ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5365 ///                      )
5366 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5367 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5368   REQUIRED(tag, DwarfTagField, );                                              \
5369   OPTIONAL(name, MDStringField, );                                             \
5370   OPTIONAL(file, MDField, );                                                   \
5371   OPTIONAL(line, LineField, );                                                 \
5372   OPTIONAL(scope, MDField, );                                                  \
5373   REQUIRED(baseType, MDField, );                                               \
5374   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
5375   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5376   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
5377   OPTIONAL(flags, DIFlagField, );                                              \
5378   OPTIONAL(extraData, MDField, );                                              \
5379   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));      \
5380   OPTIONAL(annotations, MDField, );                                            \
5381   OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7));                               \
5382   OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, );                      \
5383   OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff));           \
5384   OPTIONAL(ptrAuthIsaPointer, MDBoolField, );                                  \
5385   OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5386   PARSE_MD_FIELDS();
5387 #undef VISIT_MD_FIELDS
5388 
5389   std::optional<unsigned> DWARFAddressSpace;
5390   if (dwarfAddressSpace.Val != UINT32_MAX)
5391     DWARFAddressSpace = dwarfAddressSpace.Val;
5392   std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5393   if (ptrAuthKey.Val)
5394     PtrAuthData.emplace(
5395         (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5396         (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5397         ptrAuthAuthenticatesNullValues.Val);
5398 
5399   Result = GET_OR_DISTINCT(DIDerivedType,
5400                            (Context, tag.Val, name.Val, file.Val, line.Val,
5401                             scope.Val, baseType.Val, size.Val, align.Val,
5402                             offset.Val, DWARFAddressSpace, PtrAuthData,
5403                             flags.Val, extraData.Val, annotations.Val));
5404   return false;
5405 }
5406 
5407 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5408 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5409   REQUIRED(tag, DwarfTagField, );                                              \
5410   OPTIONAL(name, MDStringField, );                                             \
5411   OPTIONAL(file, MDField, );                                                   \
5412   OPTIONAL(line, LineField, );                                                 \
5413   OPTIONAL(scope, MDField, );                                                  \
5414   OPTIONAL(baseType, MDField, );                                               \
5415   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
5416   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5417   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
5418   OPTIONAL(flags, DIFlagField, );                                              \
5419   OPTIONAL(elements, MDField, );                                               \
5420   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
5421   OPTIONAL(vtableHolder, MDField, );                                           \
5422   OPTIONAL(templateParams, MDField, );                                         \
5423   OPTIONAL(identifier, MDStringField, );                                       \
5424   OPTIONAL(discriminator, MDField, );                                          \
5425   OPTIONAL(dataLocation, MDField, );                                           \
5426   OPTIONAL(associated, MDField, );                                             \
5427   OPTIONAL(allocated, MDField, );                                              \
5428   OPTIONAL(rank, MDSignedOrMDField, );                                         \
5429   OPTIONAL(annotations, MDField, );
5430   PARSE_MD_FIELDS();
5431 #undef VISIT_MD_FIELDS
5432 
5433   Metadata *Rank = nullptr;
5434   if (rank.isMDSignedField())
5435     Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
5436         Type::getInt64Ty(Context), rank.getMDSignedValue()));
5437   else if (rank.isMDField())
5438     Rank = rank.getMDFieldValue();
5439 
5440   // If this has an identifier try to build an ODR type.
5441   if (identifier.Val)
5442     if (auto *CT = DICompositeType::buildODRType(
5443             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5444             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
5445             elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5446             discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5447             Rank, annotations.Val)) {
5448       Result = CT;
5449       return false;
5450     }
5451 
5452   // Create a new node, and save it in the context if it belongs in the type
5453   // map.
5454   Result = GET_OR_DISTINCT(
5455       DICompositeType,
5456       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5457        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5458        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5459        discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5460        annotations.Val));
5461   return false;
5462 }
5463 
5464 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5465 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5466   OPTIONAL(flags, DIFlagField, );                                              \
5467   OPTIONAL(cc, DwarfCCField, );                                                \
5468   REQUIRED(types, MDField, );
5469   PARSE_MD_FIELDS();
5470 #undef VISIT_MD_FIELDS
5471 
5472   Result = GET_OR_DISTINCT(DISubroutineType,
5473                            (Context, flags.Val, cc.Val, types.Val));
5474   return false;
5475 }
5476 
5477 /// parseDIFileType:
5478 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5479 ///                   checksumkind: CSK_MD5,
5480 ///                   checksum: "000102030405060708090a0b0c0d0e0f",
5481 ///                   source: "source file contents")
5482 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5483   // The default constructed value for checksumkind is required, but will never
5484   // be used, as the parser checks if the field was actually Seen before using
5485   // the Val.
5486 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5487   REQUIRED(filename, MDStringField, );                                         \
5488   REQUIRED(directory, MDStringField, );                                        \
5489   OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5));                \
5490   OPTIONAL(checksum, MDStringField, );                                         \
5491   OPTIONAL(source, MDStringField, );
5492   PARSE_MD_FIELDS();
5493 #undef VISIT_MD_FIELDS
5494 
5495   std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5496   if (checksumkind.Seen && checksum.Seen)
5497     OptChecksum.emplace(checksumkind.Val, checksum.Val);
5498   else if (checksumkind.Seen || checksum.Seen)
5499     return tokError("'checksumkind' and 'checksum' must be provided together");
5500 
5501   MDString *Source = nullptr;
5502   if (source.Seen)
5503     Source = source.Val;
5504   Result = GET_OR_DISTINCT(
5505       DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5506   return false;
5507 }
5508 
5509 /// parseDICompileUnit:
5510 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5511 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
5512 ///                      splitDebugFilename: "abc.debug",
5513 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5514 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5515 ///                      sysroot: "/", sdk: "MacOSX.sdk")
5516 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5517   if (!IsDistinct)
5518     return tokError("missing 'distinct', required for !DICompileUnit");
5519 
5520 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5521   REQUIRED(language, DwarfLangField, );                                        \
5522   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
5523   OPTIONAL(producer, MDStringField, );                                         \
5524   OPTIONAL(isOptimized, MDBoolField, );                                        \
5525   OPTIONAL(flags, MDStringField, );                                            \
5526   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
5527   OPTIONAL(splitDebugFilename, MDStringField, );                               \
5528   OPTIONAL(emissionKind, EmissionKindField, );                                 \
5529   OPTIONAL(enums, MDField, );                                                  \
5530   OPTIONAL(retainedTypes, MDField, );                                          \
5531   OPTIONAL(globals, MDField, );                                                \
5532   OPTIONAL(imports, MDField, );                                                \
5533   OPTIONAL(macros, MDField, );                                                 \
5534   OPTIONAL(dwoId, MDUnsignedField, );                                          \
5535   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
5536   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);                       \
5537   OPTIONAL(nameTableKind, NameTableKindField, );                               \
5538   OPTIONAL(rangesBaseAddress, MDBoolField, = false);                           \
5539   OPTIONAL(sysroot, MDStringField, );                                          \
5540   OPTIONAL(sdk, MDStringField, );
5541   PARSE_MD_FIELDS();
5542 #undef VISIT_MD_FIELDS
5543 
5544   Result = DICompileUnit::getDistinct(
5545       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5546       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5547       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5548       splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5549       rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5550   return false;
5551 }
5552 
5553 /// parseDISubprogram:
5554 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5555 ///                     file: !1, line: 7, type: !2, isLocal: false,
5556 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
5557 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
5558 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
5559 ///                     spFlags: 10, isOptimized: false, templateParams: !4,
5560 ///                     declaration: !5, retainedNodes: !6, thrownTypes: !7,
5561 ///                     annotations: !8)
5562 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5563   auto Loc = Lex.getLoc();
5564 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5565   OPTIONAL(scope, MDField, );                                                  \
5566   OPTIONAL(name, MDStringField, );                                             \
5567   OPTIONAL(linkageName, MDStringField, );                                      \
5568   OPTIONAL(file, MDField, );                                                   \
5569   OPTIONAL(line, LineField, );                                                 \
5570   OPTIONAL(type, MDField, );                                                   \
5571   OPTIONAL(isLocal, MDBoolField, );                                            \
5572   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
5573   OPTIONAL(scopeLine, LineField, );                                            \
5574   OPTIONAL(containingType, MDField, );                                         \
5575   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
5576   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
5577   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
5578   OPTIONAL(flags, DIFlagField, );                                              \
5579   OPTIONAL(spFlags, DISPFlagField, );                                          \
5580   OPTIONAL(isOptimized, MDBoolField, );                                        \
5581   OPTIONAL(unit, MDField, );                                                   \
5582   OPTIONAL(templateParams, MDField, );                                         \
5583   OPTIONAL(declaration, MDField, );                                            \
5584   OPTIONAL(retainedNodes, MDField, );                                          \
5585   OPTIONAL(thrownTypes, MDField, );                                            \
5586   OPTIONAL(annotations, MDField, );                                            \
5587   OPTIONAL(targetFuncName, MDStringField, );
5588   PARSE_MD_FIELDS();
5589 #undef VISIT_MD_FIELDS
5590 
5591   // An explicit spFlags field takes precedence over individual fields in
5592   // older IR versions.
5593   DISubprogram::DISPFlags SPFlags =
5594       spFlags.Seen ? spFlags.Val
5595                    : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5596                                              isOptimized.Val, virtuality.Val);
5597   if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5598     return error(
5599         Loc,
5600         "missing 'distinct', required for !DISubprogram that is a Definition");
5601   Result = GET_OR_DISTINCT(
5602       DISubprogram,
5603       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5604        type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5605        thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5606        declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5607        targetFuncName.Val));
5608   return false;
5609 }
5610 
5611 /// parseDILexicalBlock:
5612 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5613 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5614 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5615   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5616   OPTIONAL(file, MDField, );                                                   \
5617   OPTIONAL(line, LineField, );                                                 \
5618   OPTIONAL(column, ColumnField, );
5619   PARSE_MD_FIELDS();
5620 #undef VISIT_MD_FIELDS
5621 
5622   Result = GET_OR_DISTINCT(
5623       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5624   return false;
5625 }
5626 
5627 /// parseDILexicalBlockFile:
5628 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5629 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5630 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5631   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5632   OPTIONAL(file, MDField, );                                                   \
5633   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5634   PARSE_MD_FIELDS();
5635 #undef VISIT_MD_FIELDS
5636 
5637   Result = GET_OR_DISTINCT(DILexicalBlockFile,
5638                            (Context, scope.Val, file.Val, discriminator.Val));
5639   return false;
5640 }
5641 
5642 /// parseDICommonBlock:
5643 ///   ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5644 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5645 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5646   REQUIRED(scope, MDField, );                                                  \
5647   OPTIONAL(declaration, MDField, );                                            \
5648   OPTIONAL(name, MDStringField, );                                             \
5649   OPTIONAL(file, MDField, );                                                   \
5650   OPTIONAL(line, LineField, );
5651   PARSE_MD_FIELDS();
5652 #undef VISIT_MD_FIELDS
5653 
5654   Result = GET_OR_DISTINCT(DICommonBlock,
5655                            (Context, scope.Val, declaration.Val, name.Val,
5656                             file.Val, line.Val));
5657   return false;
5658 }
5659 
5660 /// parseDINamespace:
5661 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5662 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5663 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5664   REQUIRED(scope, MDField, );                                                  \
5665   OPTIONAL(name, MDStringField, );                                             \
5666   OPTIONAL(exportSymbols, MDBoolField, );
5667   PARSE_MD_FIELDS();
5668 #undef VISIT_MD_FIELDS
5669 
5670   Result = GET_OR_DISTINCT(DINamespace,
5671                            (Context, scope.Val, name.Val, exportSymbols.Val));
5672   return false;
5673 }
5674 
5675 /// parseDIMacro:
5676 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5677 ///   "SomeValue")
5678 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5679 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5680   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
5681   OPTIONAL(line, LineField, );                                                 \
5682   REQUIRED(name, MDStringField, );                                             \
5683   OPTIONAL(value, MDStringField, );
5684   PARSE_MD_FIELDS();
5685 #undef VISIT_MD_FIELDS
5686 
5687   Result = GET_OR_DISTINCT(DIMacro,
5688                            (Context, type.Val, line.Val, name.Val, value.Val));
5689   return false;
5690 }
5691 
5692 /// parseDIMacroFile:
5693 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5694 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5695 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5696   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
5697   OPTIONAL(line, LineField, );                                                 \
5698   REQUIRED(file, MDField, );                                                   \
5699   OPTIONAL(nodes, MDField, );
5700   PARSE_MD_FIELDS();
5701 #undef VISIT_MD_FIELDS
5702 
5703   Result = GET_OR_DISTINCT(DIMacroFile,
5704                            (Context, type.Val, line.Val, file.Val, nodes.Val));
5705   return false;
5706 }
5707 
5708 /// parseDIModule:
5709 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5710 ///   "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5711 ///   file: !1, line: 4, isDecl: false)
5712 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5713 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5714   REQUIRED(scope, MDField, );                                                  \
5715   REQUIRED(name, MDStringField, );                                             \
5716   OPTIONAL(configMacros, MDStringField, );                                     \
5717   OPTIONAL(includePath, MDStringField, );                                      \
5718   OPTIONAL(apinotes, MDStringField, );                                         \
5719   OPTIONAL(file, MDField, );                                                   \
5720   OPTIONAL(line, LineField, );                                                 \
5721   OPTIONAL(isDecl, MDBoolField, );
5722   PARSE_MD_FIELDS();
5723 #undef VISIT_MD_FIELDS
5724 
5725   Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5726                                       configMacros.Val, includePath.Val,
5727                                       apinotes.Val, line.Val, isDecl.Val));
5728   return false;
5729 }
5730 
5731 /// parseDITemplateTypeParameter:
5732 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5733 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5734 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5735   OPTIONAL(name, MDStringField, );                                             \
5736   REQUIRED(type, MDField, );                                                   \
5737   OPTIONAL(defaulted, MDBoolField, );
5738   PARSE_MD_FIELDS();
5739 #undef VISIT_MD_FIELDS
5740 
5741   Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5742                            (Context, name.Val, type.Val, defaulted.Val));
5743   return false;
5744 }
5745 
5746 /// parseDITemplateValueParameter:
5747 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5748 ///                                 name: "V", type: !1, defaulted: false,
5749 ///                                 value: i32 7)
5750 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5751 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5752   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
5753   OPTIONAL(name, MDStringField, );                                             \
5754   OPTIONAL(type, MDField, );                                                   \
5755   OPTIONAL(defaulted, MDBoolField, );                                          \
5756   REQUIRED(value, MDField, );
5757 
5758   PARSE_MD_FIELDS();
5759 #undef VISIT_MD_FIELDS
5760 
5761   Result = GET_OR_DISTINCT(
5762       DITemplateValueParameter,
5763       (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5764   return false;
5765 }
5766 
5767 /// parseDIGlobalVariable:
5768 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5769 ///                         file: !1, line: 7, type: !2, isLocal: false,
5770 ///                         isDefinition: true, templateParams: !3,
5771 ///                         declaration: !4, align: 8)
5772 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5773 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5774   OPTIONAL(name, MDStringField, (/* AllowEmpty */ false));                     \
5775   OPTIONAL(scope, MDField, );                                                  \
5776   OPTIONAL(linkageName, MDStringField, );                                      \
5777   OPTIONAL(file, MDField, );                                                   \
5778   OPTIONAL(line, LineField, );                                                 \
5779   OPTIONAL(type, MDField, );                                                   \
5780   OPTIONAL(isLocal, MDBoolField, );                                            \
5781   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
5782   OPTIONAL(templateParams, MDField, );                                         \
5783   OPTIONAL(declaration, MDField, );                                            \
5784   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5785   OPTIONAL(annotations, MDField, );
5786   PARSE_MD_FIELDS();
5787 #undef VISIT_MD_FIELDS
5788 
5789   Result =
5790       GET_OR_DISTINCT(DIGlobalVariable,
5791                       (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5792                        line.Val, type.Val, isLocal.Val, isDefinition.Val,
5793                        declaration.Val, templateParams.Val, align.Val,
5794                        annotations.Val));
5795   return false;
5796 }
5797 
5798 /// parseDILocalVariable:
5799 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5800 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5801 ///                        align: 8)
5802 ///   ::= !DILocalVariable(scope: !0, name: "foo",
5803 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5804 ///                        align: 8)
5805 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5806 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5807   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5808   OPTIONAL(name, MDStringField, );                                             \
5809   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
5810   OPTIONAL(file, MDField, );                                                   \
5811   OPTIONAL(line, LineField, );                                                 \
5812   OPTIONAL(type, MDField, );                                                   \
5813   OPTIONAL(flags, DIFlagField, );                                              \
5814   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5815   OPTIONAL(annotations, MDField, );
5816   PARSE_MD_FIELDS();
5817 #undef VISIT_MD_FIELDS
5818 
5819   Result = GET_OR_DISTINCT(DILocalVariable,
5820                            (Context, scope.Val, name.Val, file.Val, line.Val,
5821                             type.Val, arg.Val, flags.Val, align.Val,
5822                             annotations.Val));
5823   return false;
5824 }
5825 
5826 /// parseDILabel:
5827 ///   ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5828 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5829 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5830   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5831   REQUIRED(name, MDStringField, );                                             \
5832   REQUIRED(file, MDField, );                                                   \
5833   REQUIRED(line, LineField, );
5834   PARSE_MD_FIELDS();
5835 #undef VISIT_MD_FIELDS
5836 
5837   Result = GET_OR_DISTINCT(DILabel,
5838                            (Context, scope.Val, name.Val, file.Val, line.Val));
5839   return false;
5840 }
5841 
5842 /// parseDIExpressionBody:
5843 ///   ::= (0, 7, -1)
5844 bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
5845   if (parseToken(lltok::lparen, "expected '(' here"))
5846     return true;
5847 
5848   SmallVector<uint64_t, 8> Elements;
5849   if (Lex.getKind() != lltok::rparen)
5850     do {
5851       if (Lex.getKind() == lltok::DwarfOp) {
5852         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5853           Lex.Lex();
5854           Elements.push_back(Op);
5855           continue;
5856         }
5857         return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5858       }
5859 
5860       if (Lex.getKind() == lltok::DwarfAttEncoding) {
5861         if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5862           Lex.Lex();
5863           Elements.push_back(Op);
5864           continue;
5865         }
5866         return tokError(Twine("invalid DWARF attribute encoding '") +
5867                         Lex.getStrVal() + "'");
5868       }
5869 
5870       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5871         return tokError("expected unsigned integer");
5872 
5873       auto &U = Lex.getAPSIntVal();
5874       if (U.ugt(UINT64_MAX))
5875         return tokError("element too large, limit is " + Twine(UINT64_MAX));
5876       Elements.push_back(U.getZExtValue());
5877       Lex.Lex();
5878     } while (EatIfPresent(lltok::comma));
5879 
5880   if (parseToken(lltok::rparen, "expected ')' here"))
5881     return true;
5882 
5883   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5884   return false;
5885 }
5886 
5887 /// parseDIExpression:
5888 ///   ::= !DIExpression(0, 7, -1)
5889 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5890   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5891   assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
5892   Lex.Lex();
5893 
5894   return parseDIExpressionBody(Result, IsDistinct);
5895 }
5896 
5897 /// ParseDIArgList:
5898 ///   ::= !DIArgList(i32 7, i64 %0)
5899 bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
5900   assert(PFS && "Expected valid function state");
5901   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5902   Lex.Lex();
5903 
5904   if (parseToken(lltok::lparen, "expected '(' here"))
5905     return true;
5906 
5907   SmallVector<ValueAsMetadata *, 4> Args;
5908   if (Lex.getKind() != lltok::rparen)
5909     do {
5910       Metadata *MD;
5911       if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5912         return true;
5913       Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5914     } while (EatIfPresent(lltok::comma));
5915 
5916   if (parseToken(lltok::rparen, "expected ')' here"))
5917     return true;
5918 
5919   MD = DIArgList::get(Context, Args);
5920   return false;
5921 }
5922 
5923 /// parseDIGlobalVariableExpression:
5924 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5925 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5926                                                bool IsDistinct) {
5927 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5928   REQUIRED(var, MDField, );                                                    \
5929   REQUIRED(expr, MDField, );
5930   PARSE_MD_FIELDS();
5931 #undef VISIT_MD_FIELDS
5932 
5933   Result =
5934       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5935   return false;
5936 }
5937 
5938 /// parseDIObjCProperty:
5939 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5940 ///                       getter: "getFoo", attributes: 7, type: !2)
5941 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5942 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5943   OPTIONAL(name, MDStringField, );                                             \
5944   OPTIONAL(file, MDField, );                                                   \
5945   OPTIONAL(line, LineField, );                                                 \
5946   OPTIONAL(setter, MDStringField, );                                           \
5947   OPTIONAL(getter, MDStringField, );                                           \
5948   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
5949   OPTIONAL(type, MDField, );
5950   PARSE_MD_FIELDS();
5951 #undef VISIT_MD_FIELDS
5952 
5953   Result = GET_OR_DISTINCT(DIObjCProperty,
5954                            (Context, name.Val, file.Val, line.Val, setter.Val,
5955                             getter.Val, attributes.Val, type.Val));
5956   return false;
5957 }
5958 
5959 /// parseDIImportedEntity:
5960 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5961 ///                         line: 7, name: "foo", elements: !2)
5962 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5963 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5964   REQUIRED(tag, DwarfTagField, );                                              \
5965   REQUIRED(scope, MDField, );                                                  \
5966   OPTIONAL(entity, MDField, );                                                 \
5967   OPTIONAL(file, MDField, );                                                   \
5968   OPTIONAL(line, LineField, );                                                 \
5969   OPTIONAL(name, MDStringField, );                                             \
5970   OPTIONAL(elements, MDField, );
5971   PARSE_MD_FIELDS();
5972 #undef VISIT_MD_FIELDS
5973 
5974   Result = GET_OR_DISTINCT(DIImportedEntity,
5975                            (Context, tag.Val, scope.Val, entity.Val, file.Val,
5976                             line.Val, name.Val, elements.Val));
5977   return false;
5978 }
5979 
5980 #undef PARSE_MD_FIELD
5981 #undef NOP_FIELD
5982 #undef REQUIRE_FIELD
5983 #undef DECLARE_FIELD
5984 
5985 /// parseMetadataAsValue
5986 ///  ::= metadata i32 %local
5987 ///  ::= metadata i32 @global
5988 ///  ::= metadata i32 7
5989 ///  ::= metadata !0
5990 ///  ::= metadata !{...}
5991 ///  ::= metadata !"string"
5992 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5993   // Note: the type 'metadata' has already been parsed.
5994   Metadata *MD;
5995   if (parseMetadata(MD, &PFS))
5996     return true;
5997 
5998   V = MetadataAsValue::get(Context, MD);
5999   return false;
6000 }
6001 
6002 /// parseValueAsMetadata
6003 ///  ::= i32 %local
6004 ///  ::= i32 @global
6005 ///  ::= i32 7
6006 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6007                                     PerFunctionState *PFS) {
6008   Type *Ty;
6009   LocTy Loc;
6010   if (parseType(Ty, TypeMsg, Loc))
6011     return true;
6012   if (Ty->isMetadataTy())
6013     return error(Loc, "invalid metadata-value-metadata roundtrip");
6014 
6015   Value *V;
6016   if (parseValue(Ty, V, PFS))
6017     return true;
6018 
6019   MD = ValueAsMetadata::get(V);
6020   return false;
6021 }
6022 
6023 /// parseMetadata
6024 ///  ::= i32 %local
6025 ///  ::= i32 @global
6026 ///  ::= i32 7
6027 ///  ::= !42
6028 ///  ::= !{...}
6029 ///  ::= !"string"
6030 ///  ::= !DILocation(...)
6031 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6032   if (Lex.getKind() == lltok::MetadataVar) {
6033     // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6034     // so parsing this requires a Function State.
6035     if (Lex.getStrVal() == "DIArgList") {
6036       Metadata *AL;
6037       if (parseDIArgList(AL, PFS))
6038         return true;
6039       MD = AL;
6040       return false;
6041     }
6042     MDNode *N;
6043     if (parseSpecializedMDNode(N)) {
6044       return true;
6045     }
6046     MD = N;
6047     return false;
6048   }
6049 
6050   // ValueAsMetadata:
6051   // <type> <value>
6052   if (Lex.getKind() != lltok::exclaim)
6053     return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6054 
6055   // '!'.
6056   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6057   Lex.Lex();
6058 
6059   // MDString:
6060   //   ::= '!' STRINGCONSTANT
6061   if (Lex.getKind() == lltok::StringConstant) {
6062     MDString *S;
6063     if (parseMDString(S))
6064       return true;
6065     MD = S;
6066     return false;
6067   }
6068 
6069   // MDNode:
6070   // !{ ... }
6071   // !7
6072   MDNode *N;
6073   if (parseMDNodeTail(N))
6074     return true;
6075   MD = N;
6076   return false;
6077 }
6078 
6079 //===----------------------------------------------------------------------===//
6080 // Function Parsing.
6081 //===----------------------------------------------------------------------===//
6082 
6083 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6084                                    PerFunctionState *PFS) {
6085   if (Ty->isFunctionTy())
6086     return error(ID.Loc, "functions are not values, refer to them as pointers");
6087 
6088   switch (ID.Kind) {
6089   case ValID::t_LocalID:
6090     if (!PFS)
6091       return error(ID.Loc, "invalid use of function-local name");
6092     V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6093     return V == nullptr;
6094   case ValID::t_LocalName:
6095     if (!PFS)
6096       return error(ID.Loc, "invalid use of function-local name");
6097     V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6098     return V == nullptr;
6099   case ValID::t_InlineAsm: {
6100     if (!ID.FTy)
6101       return error(ID.Loc, "invalid type for inline asm constraint string");
6102     if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6103       return error(ID.Loc, toString(std::move(Err)));
6104     V = InlineAsm::get(
6105         ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6106         InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6107     return false;
6108   }
6109   case ValID::t_GlobalName:
6110     V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6111     if (V && ID.NoCFI)
6112       V = NoCFIValue::get(cast<GlobalValue>(V));
6113     return V == nullptr;
6114   case ValID::t_GlobalID:
6115     V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6116     if (V && ID.NoCFI)
6117       V = NoCFIValue::get(cast<GlobalValue>(V));
6118     return V == nullptr;
6119   case ValID::t_APSInt:
6120     if (!Ty->isIntegerTy())
6121       return error(ID.Loc, "integer constant must have integer type");
6122     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6123     V = ConstantInt::get(Context, ID.APSIntVal);
6124     return false;
6125   case ValID::t_APFloat:
6126     if (!Ty->isFloatingPointTy() ||
6127         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6128       return error(ID.Loc, "floating point constant invalid for type");
6129 
6130     // The lexer has no type info, so builds all half, bfloat, float, and double
6131     // FP constants as double.  Fix this here.  Long double does not need this.
6132     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6133       // Check for signaling before potentially converting and losing that info.
6134       bool IsSNAN = ID.APFloatVal.isSignaling();
6135       bool Ignored;
6136       if (Ty->isHalfTy())
6137         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6138                               &Ignored);
6139       else if (Ty->isBFloatTy())
6140         ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6141                               &Ignored);
6142       else if (Ty->isFloatTy())
6143         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6144                               &Ignored);
6145       if (IsSNAN) {
6146         // The convert call above may quiet an SNaN, so manufacture another
6147         // SNaN. The bitcast works because the payload (significand) parameter
6148         // is truncated to fit.
6149         APInt Payload = ID.APFloatVal.bitcastToAPInt();
6150         ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6151                                          ID.APFloatVal.isNegative(), &Payload);
6152       }
6153     }
6154     V = ConstantFP::get(Context, ID.APFloatVal);
6155 
6156     if (V->getType() != Ty)
6157       return error(ID.Loc, "floating point constant does not have type '" +
6158                                getTypeString(Ty) + "'");
6159 
6160     return false;
6161   case ValID::t_Null:
6162     if (!Ty->isPointerTy())
6163       return error(ID.Loc, "null must be a pointer type");
6164     V = ConstantPointerNull::get(cast<PointerType>(Ty));
6165     return false;
6166   case ValID::t_Undef:
6167     // FIXME: LabelTy should not be a first-class type.
6168     if (!Ty->isFirstClassType() || Ty->isLabelTy())
6169       return error(ID.Loc, "invalid type for undef constant");
6170     V = UndefValue::get(Ty);
6171     return false;
6172   case ValID::t_EmptyArray:
6173     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6174       return error(ID.Loc, "invalid empty array initializer");
6175     V = UndefValue::get(Ty);
6176     return false;
6177   case ValID::t_Zero:
6178     // FIXME: LabelTy should not be a first-class type.
6179     if (!Ty->isFirstClassType() || Ty->isLabelTy())
6180       return error(ID.Loc, "invalid type for null constant");
6181     if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6182       if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6183         return error(ID.Loc, "invalid type for null constant");
6184     V = Constant::getNullValue(Ty);
6185     return false;
6186   case ValID::t_None:
6187     if (!Ty->isTokenTy())
6188       return error(ID.Loc, "invalid type for none constant");
6189     V = Constant::getNullValue(Ty);
6190     return false;
6191   case ValID::t_Poison:
6192     // FIXME: LabelTy should not be a first-class type.
6193     if (!Ty->isFirstClassType() || Ty->isLabelTy())
6194       return error(ID.Loc, "invalid type for poison constant");
6195     V = PoisonValue::get(Ty);
6196     return false;
6197   case ValID::t_Constant:
6198     if (ID.ConstantVal->getType() != Ty)
6199       return error(ID.Loc, "constant expression type mismatch: got type '" +
6200                                getTypeString(ID.ConstantVal->getType()) +
6201                                "' but expected '" + getTypeString(Ty) + "'");
6202     V = ID.ConstantVal;
6203     return false;
6204   case ValID::t_ConstantSplat:
6205     if (!Ty->isVectorTy())
6206       return error(ID.Loc, "vector constant must have vector type");
6207     if (ID.ConstantVal->getType() != Ty->getScalarType())
6208       return error(ID.Loc, "constant expression type mismatch: got type '" +
6209                                getTypeString(ID.ConstantVal->getType()) +
6210                                "' but expected '" +
6211                                getTypeString(Ty->getScalarType()) + "'");
6212     V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6213                                  ID.ConstantVal);
6214     return false;
6215   case ValID::t_ConstantStruct:
6216   case ValID::t_PackedConstantStruct:
6217     if (StructType *ST = dyn_cast<StructType>(Ty)) {
6218       if (ST->getNumElements() != ID.UIntVal)
6219         return error(ID.Loc,
6220                      "initializer with struct type has wrong # elements");
6221       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6222         return error(ID.Loc, "packed'ness of initializer and type don't match");
6223 
6224       // Verify that the elements are compatible with the structtype.
6225       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6226         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6227           return error(
6228               ID.Loc,
6229               "element " + Twine(i) +
6230                   " of struct initializer doesn't match struct element type");
6231 
6232       V = ConstantStruct::get(
6233           ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6234     } else
6235       return error(ID.Loc, "constant expression type mismatch");
6236     return false;
6237   }
6238   llvm_unreachable("Invalid ValID");
6239 }
6240 
6241 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6242   C = nullptr;
6243   ValID ID;
6244   auto Loc = Lex.getLoc();
6245   if (parseValID(ID, /*PFS=*/nullptr))
6246     return true;
6247   switch (ID.Kind) {
6248   case ValID::t_APSInt:
6249   case ValID::t_APFloat:
6250   case ValID::t_Undef:
6251   case ValID::t_Constant:
6252   case ValID::t_ConstantSplat:
6253   case ValID::t_ConstantStruct:
6254   case ValID::t_PackedConstantStruct: {
6255     Value *V;
6256     if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6257       return true;
6258     assert(isa<Constant>(V) && "Expected a constant value");
6259     C = cast<Constant>(V);
6260     return false;
6261   }
6262   case ValID::t_Null:
6263     C = Constant::getNullValue(Ty);
6264     return false;
6265   default:
6266     return error(Loc, "expected a constant value");
6267   }
6268 }
6269 
6270 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6271   V = nullptr;
6272   ValID ID;
6273   return parseValID(ID, PFS, Ty) ||
6274          convertValIDToValue(Ty, ID, V, PFS);
6275 }
6276 
6277 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6278   Type *Ty = nullptr;
6279   return parseType(Ty) || parseValue(Ty, V, PFS);
6280 }
6281 
6282 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6283                                       PerFunctionState &PFS) {
6284   Value *V;
6285   Loc = Lex.getLoc();
6286   if (parseTypeAndValue(V, PFS))
6287     return true;
6288   if (!isa<BasicBlock>(V))
6289     return error(Loc, "expected a basic block");
6290   BB = cast<BasicBlock>(V);
6291   return false;
6292 }
6293 
6294 bool isOldDbgFormatIntrinsic(StringRef Name) {
6295   // Exit early for the common (non-debug-intrinsic) case.
6296   // We can make this the only check when we begin supporting all "llvm.dbg"
6297   // intrinsics in the new debug info format.
6298   if (!Name.starts_with("llvm.dbg."))
6299     return false;
6300   Intrinsic::ID FnID = Intrinsic::lookupIntrinsicID(Name);
6301   return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6302          FnID == Intrinsic::dbg_assign;
6303 }
6304 
6305 /// FunctionHeader
6306 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6307 ///       OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6308 ///       '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6309 ///       OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6310 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6311                                    unsigned &FunctionNumber,
6312                                    SmallVectorImpl<unsigned> &UnnamedArgNums) {
6313   // parse the linkage.
6314   LocTy LinkageLoc = Lex.getLoc();
6315   unsigned Linkage;
6316   unsigned Visibility;
6317   unsigned DLLStorageClass;
6318   bool DSOLocal;
6319   AttrBuilder RetAttrs(M->getContext());
6320   unsigned CC;
6321   bool HasLinkage;
6322   Type *RetType = nullptr;
6323   LocTy RetTypeLoc = Lex.getLoc();
6324   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6325                            DSOLocal) ||
6326       parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6327       parseType(RetType, RetTypeLoc, true /*void allowed*/))
6328     return true;
6329 
6330   // Verify that the linkage is ok.
6331   switch ((GlobalValue::LinkageTypes)Linkage) {
6332   case GlobalValue::ExternalLinkage:
6333     break; // always ok.
6334   case GlobalValue::ExternalWeakLinkage:
6335     if (IsDefine)
6336       return error(LinkageLoc, "invalid linkage for function definition");
6337     break;
6338   case GlobalValue::PrivateLinkage:
6339   case GlobalValue::InternalLinkage:
6340   case GlobalValue::AvailableExternallyLinkage:
6341   case GlobalValue::LinkOnceAnyLinkage:
6342   case GlobalValue::LinkOnceODRLinkage:
6343   case GlobalValue::WeakAnyLinkage:
6344   case GlobalValue::WeakODRLinkage:
6345     if (!IsDefine)
6346       return error(LinkageLoc, "invalid linkage for function declaration");
6347     break;
6348   case GlobalValue::AppendingLinkage:
6349   case GlobalValue::CommonLinkage:
6350     return error(LinkageLoc, "invalid function linkage type");
6351   }
6352 
6353   if (!isValidVisibilityForLinkage(Visibility, Linkage))
6354     return error(LinkageLoc,
6355                  "symbol with local linkage must have default visibility");
6356 
6357   if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6358     return error(LinkageLoc,
6359                  "symbol with local linkage cannot have a DLL storage class");
6360 
6361   if (!FunctionType::isValidReturnType(RetType))
6362     return error(RetTypeLoc, "invalid function return type");
6363 
6364   LocTy NameLoc = Lex.getLoc();
6365 
6366   std::string FunctionName;
6367   if (Lex.getKind() == lltok::GlobalVar) {
6368     FunctionName = Lex.getStrVal();
6369   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
6370     FunctionNumber = Lex.getUIntVal();
6371     if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6372                      FunctionNumber))
6373       return true;
6374   } else {
6375     return tokError("expected function name");
6376   }
6377 
6378   Lex.Lex();
6379 
6380   if (Lex.getKind() != lltok::lparen)
6381     return tokError("expected '(' in function argument list");
6382 
6383   SmallVector<ArgInfo, 8> ArgList;
6384   bool IsVarArg;
6385   AttrBuilder FuncAttrs(M->getContext());
6386   std::vector<unsigned> FwdRefAttrGrps;
6387   LocTy BuiltinLoc;
6388   std::string Section;
6389   std::string Partition;
6390   MaybeAlign Alignment;
6391   std::string GC;
6392   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
6393   unsigned AddrSpace = 0;
6394   Constant *Prefix = nullptr;
6395   Constant *Prologue = nullptr;
6396   Constant *PersonalityFn = nullptr;
6397   Comdat *C;
6398 
6399   if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6400       parseOptionalUnnamedAddr(UnnamedAddr) ||
6401       parseOptionalProgramAddrSpace(AddrSpace) ||
6402       parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6403                                  BuiltinLoc) ||
6404       (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6405       (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6406       parseOptionalComdat(FunctionName, C) ||
6407       parseOptionalAlignment(Alignment) ||
6408       (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6409       (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6410       (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6411       (EatIfPresent(lltok::kw_personality) &&
6412        parseGlobalTypeAndValue(PersonalityFn)))
6413     return true;
6414 
6415   if (FuncAttrs.contains(Attribute::Builtin))
6416     return error(BuiltinLoc, "'builtin' attribute not valid on function");
6417 
6418   // If the alignment was parsed as an attribute, move to the alignment field.
6419   if (MaybeAlign A = FuncAttrs.getAlignment()) {
6420     Alignment = A;
6421     FuncAttrs.removeAttribute(Attribute::Alignment);
6422   }
6423 
6424   // Okay, if we got here, the function is syntactically valid.  Convert types
6425   // and do semantic checks.
6426   std::vector<Type*> ParamTypeList;
6427   SmallVector<AttributeSet, 8> Attrs;
6428 
6429   for (const ArgInfo &Arg : ArgList) {
6430     ParamTypeList.push_back(Arg.Ty);
6431     Attrs.push_back(Arg.Attrs);
6432   }
6433 
6434   AttributeList PAL =
6435       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6436                          AttributeSet::get(Context, RetAttrs), Attrs);
6437 
6438   if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6439     return error(RetTypeLoc, "functions with 'sret' argument must return void");
6440 
6441   FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6442   PointerType *PFT = PointerType::get(FT, AddrSpace);
6443 
6444   Fn = nullptr;
6445   GlobalValue *FwdFn = nullptr;
6446   if (!FunctionName.empty()) {
6447     // If this was a definition of a forward reference, remove the definition
6448     // from the forward reference table and fill in the forward ref.
6449     auto FRVI = ForwardRefVals.find(FunctionName);
6450     if (FRVI != ForwardRefVals.end()) {
6451       FwdFn = FRVI->second.first;
6452       if (FwdFn->getType() != PFT)
6453         return error(FRVI->second.second,
6454                      "invalid forward reference to "
6455                      "function '" +
6456                          FunctionName +
6457                          "' with wrong type: "
6458                          "expected '" +
6459                          getTypeString(PFT) + "' but was '" +
6460                          getTypeString(FwdFn->getType()) + "'");
6461       ForwardRefVals.erase(FRVI);
6462     } else if ((Fn = M->getFunction(FunctionName))) {
6463       // Reject redefinitions.
6464       return error(NameLoc,
6465                    "invalid redefinition of function '" + FunctionName + "'");
6466     } else if (M->getNamedValue(FunctionName)) {
6467       return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6468     }
6469 
6470   } else {
6471     // Handle @"", where a name is syntactically specified, but semantically
6472     // missing.
6473     if (FunctionNumber == (unsigned)-1)
6474       FunctionNumber = NumberedVals.getNext();
6475 
6476     // If this is a definition of a forward referenced function, make sure the
6477     // types agree.
6478     auto I = ForwardRefValIDs.find(FunctionNumber);
6479     if (I != ForwardRefValIDs.end()) {
6480       FwdFn = I->second.first;
6481       if (FwdFn->getType() != PFT)
6482         return error(NameLoc, "type of definition and forward reference of '@" +
6483                                   Twine(FunctionNumber) +
6484                                   "' disagree: "
6485                                   "expected '" +
6486                                   getTypeString(PFT) + "' but was '" +
6487                                   getTypeString(FwdFn->getType()) + "'");
6488       ForwardRefValIDs.erase(I);
6489     }
6490   }
6491 
6492   Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
6493                         FunctionName, M);
6494 
6495   assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6496 
6497   if (FunctionName.empty())
6498     NumberedVals.add(FunctionNumber, Fn);
6499 
6500   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
6501   maybeSetDSOLocal(DSOLocal, *Fn);
6502   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
6503   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
6504   Fn->setCallingConv(CC);
6505   Fn->setAttributes(PAL);
6506   Fn->setUnnamedAddr(UnnamedAddr);
6507   if (Alignment)
6508     Fn->setAlignment(*Alignment);
6509   Fn->setSection(Section);
6510   Fn->setPartition(Partition);
6511   Fn->setComdat(C);
6512   Fn->setPersonalityFn(PersonalityFn);
6513   if (!GC.empty()) Fn->setGC(GC);
6514   Fn->setPrefixData(Prefix);
6515   Fn->setPrologueData(Prologue);
6516   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6517 
6518   // Add all of the arguments we parsed to the function.
6519   Function::arg_iterator ArgIt = Fn->arg_begin();
6520   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6521     // If the argument has a name, insert it into the argument symbol table.
6522     if (ArgList[i].Name.empty()) continue;
6523 
6524     // Set the name, if it conflicted, it will be auto-renamed.
6525     ArgIt->setName(ArgList[i].Name);
6526 
6527     if (ArgIt->getName() != ArgList[i].Name)
6528       return error(ArgList[i].Loc,
6529                    "redefinition of argument '%" + ArgList[i].Name + "'");
6530   }
6531 
6532   if (FwdFn) {
6533     FwdFn->replaceAllUsesWith(Fn);
6534     FwdFn->eraseFromParent();
6535   }
6536 
6537   if (IsDefine)
6538     return false;
6539 
6540   // Check the declaration has no block address forward references.
6541   ValID ID;
6542   if (FunctionName.empty()) {
6543     ID.Kind = ValID::t_GlobalID;
6544     ID.UIntVal = FunctionNumber;
6545   } else {
6546     ID.Kind = ValID::t_GlobalName;
6547     ID.StrVal = FunctionName;
6548   }
6549   auto Blocks = ForwardRefBlockAddresses.find(ID);
6550   if (Blocks != ForwardRefBlockAddresses.end())
6551     return error(Blocks->first.Loc,
6552                  "cannot take blockaddress inside a declaration");
6553   return false;
6554 }
6555 
6556 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6557   ValID ID;
6558   if (FunctionNumber == -1) {
6559     ID.Kind = ValID::t_GlobalName;
6560     ID.StrVal = std::string(F.getName());
6561   } else {
6562     ID.Kind = ValID::t_GlobalID;
6563     ID.UIntVal = FunctionNumber;
6564   }
6565 
6566   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6567   if (Blocks == P.ForwardRefBlockAddresses.end())
6568     return false;
6569 
6570   for (const auto &I : Blocks->second) {
6571     const ValID &BBID = I.first;
6572     GlobalValue *GV = I.second;
6573 
6574     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6575            "Expected local id or name");
6576     BasicBlock *BB;
6577     if (BBID.Kind == ValID::t_LocalName)
6578       BB = getBB(BBID.StrVal, BBID.Loc);
6579     else
6580       BB = getBB(BBID.UIntVal, BBID.Loc);
6581     if (!BB)
6582       return P.error(BBID.Loc, "referenced value is not a basic block");
6583 
6584     Value *ResolvedVal = BlockAddress::get(&F, BB);
6585     ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6586                                            ResolvedVal);
6587     if (!ResolvedVal)
6588       return true;
6589     GV->replaceAllUsesWith(ResolvedVal);
6590     GV->eraseFromParent();
6591   }
6592 
6593   P.ForwardRefBlockAddresses.erase(Blocks);
6594   return false;
6595 }
6596 
6597 /// parseFunctionBody
6598 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
6599 bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6600                                  ArrayRef<unsigned> UnnamedArgNums) {
6601   if (Lex.getKind() != lltok::lbrace)
6602     return tokError("expected '{' in function body");
6603   Lex.Lex();  // eat the {.
6604 
6605   PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
6606 
6607   // Resolve block addresses and allow basic blocks to be forward-declared
6608   // within this function.
6609   if (PFS.resolveForwardRefBlockAddresses())
6610     return true;
6611   SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6612 
6613   // We need at least one basic block.
6614   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6615     return tokError("function body requires at least one basic block");
6616 
6617   while (Lex.getKind() != lltok::rbrace &&
6618          Lex.getKind() != lltok::kw_uselistorder)
6619     if (parseBasicBlock(PFS))
6620       return true;
6621 
6622   while (Lex.getKind() != lltok::rbrace)
6623     if (parseUseListOrder(&PFS))
6624       return true;
6625 
6626   // Eat the }.
6627   Lex.Lex();
6628 
6629   // Verify function is ok.
6630   return PFS.finishFunction();
6631 }
6632 
6633 /// parseBasicBlock
6634 ///   ::= (LabelStr|LabelID)? Instruction*
6635 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6636   // If this basic block starts out with a name, remember it.
6637   std::string Name;
6638   int NameID = -1;
6639   LocTy NameLoc = Lex.getLoc();
6640   if (Lex.getKind() == lltok::LabelStr) {
6641     Name = Lex.getStrVal();
6642     Lex.Lex();
6643   } else if (Lex.getKind() == lltok::LabelID) {
6644     NameID = Lex.getUIntVal();
6645     Lex.Lex();
6646   }
6647 
6648   BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6649   if (!BB)
6650     return true;
6651 
6652   std::string NameStr;
6653 
6654   // Parse the instructions and debug values in this block until we get a
6655   // terminator.
6656   Instruction *Inst;
6657   auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
6658   using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
6659   SmallVector<DbgRecordPtr> TrailingDbgRecord;
6660   do {
6661     // Handle debug records first - there should always be an instruction
6662     // following the debug records, i.e. they cannot appear after the block
6663     // terminator.
6664     while (Lex.getKind() == lltok::hash) {
6665       if (SeenOldDbgInfoFormat)
6666         return error(Lex.getLoc(), "debug record should not appear in a module "
6667                                    "containing debug info intrinsics");
6668       if (!SeenNewDbgInfoFormat)
6669         M->setNewDbgInfoFormatFlag(true);
6670       SeenNewDbgInfoFormat = true;
6671       Lex.Lex();
6672 
6673       DbgRecord *DR;
6674       if (parseDebugRecord(DR, PFS))
6675         return true;
6676       TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6677     }
6678 
6679     // This instruction may have three possibilities for a name: a) none
6680     // specified, b) name specified "%foo =", c) number specified: "%4 =".
6681     LocTy NameLoc = Lex.getLoc();
6682     int NameID = -1;
6683     NameStr = "";
6684 
6685     if (Lex.getKind() == lltok::LocalVarID) {
6686       NameID = Lex.getUIntVal();
6687       Lex.Lex();
6688       if (parseToken(lltok::equal, "expected '=' after instruction id"))
6689         return true;
6690     } else if (Lex.getKind() == lltok::LocalVar) {
6691       NameStr = Lex.getStrVal();
6692       Lex.Lex();
6693       if (parseToken(lltok::equal, "expected '=' after instruction name"))
6694         return true;
6695     }
6696 
6697     switch (parseInstruction(Inst, BB, PFS)) {
6698     default:
6699       llvm_unreachable("Unknown parseInstruction result!");
6700     case InstError: return true;
6701     case InstNormal:
6702       Inst->insertInto(BB, BB->end());
6703 
6704       // With a normal result, we check to see if the instruction is followed by
6705       // a comma and metadata.
6706       if (EatIfPresent(lltok::comma))
6707         if (parseInstructionMetadata(*Inst))
6708           return true;
6709       break;
6710     case InstExtraComma:
6711       Inst->insertInto(BB, BB->end());
6712 
6713       // If the instruction parser ate an extra comma at the end of it, it
6714       // *must* be followed by metadata.
6715       if (parseInstructionMetadata(*Inst))
6716         return true;
6717       break;
6718     }
6719 
6720     // Set the name on the instruction.
6721     if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6722       return true;
6723 
6724     // Attach any preceding debug values to this instruction.
6725     for (DbgRecordPtr &DR : TrailingDbgRecord)
6726       BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
6727     TrailingDbgRecord.clear();
6728   } while (!Inst->isTerminator());
6729 
6730   assert(TrailingDbgRecord.empty() &&
6731          "All debug values should have been attached to an instruction.");
6732 
6733   return false;
6734 }
6735 
6736 /// parseDebugRecord
6737 ///   ::= #dbg_label '(' MDNode ')'
6738 ///   ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
6739 ///                 (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
6740 bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
6741   using RecordKind = DbgRecord::Kind;
6742   using LocType = DbgVariableRecord::LocationType;
6743   LocTy DVRLoc = Lex.getLoc();
6744   if (Lex.getKind() != lltok::DbgRecordType)
6745     return error(DVRLoc, "expected debug record type here");
6746   RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
6747                               .Case("declare", RecordKind::ValueKind)
6748                               .Case("value", RecordKind::ValueKind)
6749                               .Case("assign", RecordKind::ValueKind)
6750                               .Case("label", RecordKind::LabelKind);
6751 
6752   // Parsing labels is trivial; parse here and early exit, otherwise go into the
6753   // full DbgVariableRecord processing stage.
6754   if (RecordType == RecordKind::LabelKind) {
6755     Lex.Lex();
6756     if (parseToken(lltok::lparen, "Expected '(' here"))
6757       return true;
6758     MDNode *Label;
6759     if (parseMDNode(Label))
6760       return true;
6761     if (parseToken(lltok::comma, "Expected ',' here"))
6762       return true;
6763     MDNode *DbgLoc;
6764     if (parseMDNode(DbgLoc))
6765       return true;
6766     if (parseToken(lltok::rparen, "Expected ')' here"))
6767       return true;
6768     DR = DbgLabelRecord::createUnresolvedDbgLabelRecord(Label, DbgLoc);
6769     return false;
6770   }
6771 
6772   LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
6773                           .Case("declare", LocType::Declare)
6774                           .Case("value", LocType::Value)
6775                           .Case("assign", LocType::Assign);
6776 
6777   Lex.Lex();
6778   if (parseToken(lltok::lparen, "Expected '(' here"))
6779     return true;
6780 
6781   // Parse Value field.
6782   Metadata *ValLocMD;
6783   if (parseMetadata(ValLocMD, &PFS))
6784     return true;
6785   if (parseToken(lltok::comma, "Expected ',' here"))
6786     return true;
6787 
6788   // Parse Variable field.
6789   MDNode *Variable;
6790   if (parseMDNode(Variable))
6791     return true;
6792   if (parseToken(lltok::comma, "Expected ',' here"))
6793     return true;
6794 
6795   // Parse Expression field.
6796   MDNode *Expression;
6797   if (parseMDNode(Expression))
6798     return true;
6799   if (parseToken(lltok::comma, "Expected ',' here"))
6800     return true;
6801 
6802   // Parse additional fields for #dbg_assign.
6803   MDNode *AssignID = nullptr;
6804   Metadata *AddressLocation = nullptr;
6805   MDNode *AddressExpression = nullptr;
6806   if (ValueType == LocType::Assign) {
6807     // Parse DIAssignID.
6808     if (parseMDNode(AssignID))
6809       return true;
6810     if (parseToken(lltok::comma, "Expected ',' here"))
6811       return true;
6812 
6813     // Parse address ValueAsMetadata.
6814     if (parseMetadata(AddressLocation, &PFS))
6815       return true;
6816     if (parseToken(lltok::comma, "Expected ',' here"))
6817       return true;
6818 
6819     // Parse address DIExpression.
6820     if (parseMDNode(AddressExpression))
6821       return true;
6822     if (parseToken(lltok::comma, "Expected ',' here"))
6823       return true;
6824   }
6825 
6826   /// Parse DILocation.
6827   MDNode *DebugLoc;
6828   if (parseMDNode(DebugLoc))
6829     return true;
6830 
6831   if (parseToken(lltok::rparen, "Expected ')' here"))
6832     return true;
6833   DR = DbgVariableRecord::createUnresolvedDbgVariableRecord(
6834       ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
6835       AddressExpression, DebugLoc);
6836   return false;
6837 }
6838 //===----------------------------------------------------------------------===//
6839 // Instruction Parsing.
6840 //===----------------------------------------------------------------------===//
6841 
6842 /// parseInstruction - parse one of the many different instructions.
6843 ///
6844 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6845                                PerFunctionState &PFS) {
6846   lltok::Kind Token = Lex.getKind();
6847   if (Token == lltok::Eof)
6848     return tokError("found end of file when expecting more instructions");
6849   LocTy Loc = Lex.getLoc();
6850   unsigned KeywordVal = Lex.getUIntVal();
6851   Lex.Lex();  // Eat the keyword.
6852 
6853   switch (Token) {
6854   default:
6855     return error(Loc, "expected instruction opcode");
6856   // Terminator Instructions.
6857   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6858   case lltok::kw_ret:
6859     return parseRet(Inst, BB, PFS);
6860   case lltok::kw_br:
6861     return parseBr(Inst, PFS);
6862   case lltok::kw_switch:
6863     return parseSwitch(Inst, PFS);
6864   case lltok::kw_indirectbr:
6865     return parseIndirectBr(Inst, PFS);
6866   case lltok::kw_invoke:
6867     return parseInvoke(Inst, PFS);
6868   case lltok::kw_resume:
6869     return parseResume(Inst, PFS);
6870   case lltok::kw_cleanupret:
6871     return parseCleanupRet(Inst, PFS);
6872   case lltok::kw_catchret:
6873     return parseCatchRet(Inst, PFS);
6874   case lltok::kw_catchswitch:
6875     return parseCatchSwitch(Inst, PFS);
6876   case lltok::kw_catchpad:
6877     return parseCatchPad(Inst, PFS);
6878   case lltok::kw_cleanuppad:
6879     return parseCleanupPad(Inst, PFS);
6880   case lltok::kw_callbr:
6881     return parseCallBr(Inst, PFS);
6882   // Unary Operators.
6883   case lltok::kw_fneg: {
6884     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6885     int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6886     if (Res != 0)
6887       return Res;
6888     if (FMF.any())
6889       Inst->setFastMathFlags(FMF);
6890     return false;
6891   }
6892   // Binary Operators.
6893   case lltok::kw_add:
6894   case lltok::kw_sub:
6895   case lltok::kw_mul:
6896   case lltok::kw_shl: {
6897     bool NUW = EatIfPresent(lltok::kw_nuw);
6898     bool NSW = EatIfPresent(lltok::kw_nsw);
6899     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6900 
6901     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6902       return true;
6903 
6904     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6905     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6906     return false;
6907   }
6908   case lltok::kw_fadd:
6909   case lltok::kw_fsub:
6910   case lltok::kw_fmul:
6911   case lltok::kw_fdiv:
6912   case lltok::kw_frem: {
6913     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6914     int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6915     if (Res != 0)
6916       return Res;
6917     if (FMF.any())
6918       Inst->setFastMathFlags(FMF);
6919     return 0;
6920   }
6921 
6922   case lltok::kw_sdiv:
6923   case lltok::kw_udiv:
6924   case lltok::kw_lshr:
6925   case lltok::kw_ashr: {
6926     bool Exact = EatIfPresent(lltok::kw_exact);
6927 
6928     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6929       return true;
6930     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6931     return false;
6932   }
6933 
6934   case lltok::kw_urem:
6935   case lltok::kw_srem:
6936     return parseArithmetic(Inst, PFS, KeywordVal,
6937                            /*IsFP*/ false);
6938   case lltok::kw_or: {
6939     bool Disjoint = EatIfPresent(lltok::kw_disjoint);
6940     if (parseLogical(Inst, PFS, KeywordVal))
6941       return true;
6942     if (Disjoint)
6943       cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
6944     return false;
6945   }
6946   case lltok::kw_and:
6947   case lltok::kw_xor:
6948     return parseLogical(Inst, PFS, KeywordVal);
6949   case lltok::kw_icmp:
6950     return parseCompare(Inst, PFS, KeywordVal);
6951   case lltok::kw_fcmp: {
6952     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6953     int Res = parseCompare(Inst, PFS, KeywordVal);
6954     if (Res != 0)
6955       return Res;
6956     if (FMF.any())
6957       Inst->setFastMathFlags(FMF);
6958     return 0;
6959   }
6960 
6961   // Casts.
6962   case lltok::kw_uitofp:
6963   case lltok::kw_zext: {
6964     bool NonNeg = EatIfPresent(lltok::kw_nneg);
6965     bool Res = parseCast(Inst, PFS, KeywordVal);
6966     if (Res != 0)
6967       return Res;
6968     if (NonNeg)
6969       Inst->setNonNeg();
6970     return 0;
6971   }
6972   case lltok::kw_trunc: {
6973     bool NUW = EatIfPresent(lltok::kw_nuw);
6974     bool NSW = EatIfPresent(lltok::kw_nsw);
6975     if (!NUW)
6976       NUW = EatIfPresent(lltok::kw_nuw);
6977     if (parseCast(Inst, PFS, KeywordVal))
6978       return true;
6979     if (NUW)
6980       cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
6981     if (NSW)
6982       cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
6983     return false;
6984   }
6985   case lltok::kw_sext:
6986   case lltok::kw_fptrunc:
6987   case lltok::kw_fpext:
6988   case lltok::kw_bitcast:
6989   case lltok::kw_addrspacecast:
6990   case lltok::kw_sitofp:
6991   case lltok::kw_fptoui:
6992   case lltok::kw_fptosi:
6993   case lltok::kw_inttoptr:
6994   case lltok::kw_ptrtoint:
6995     return parseCast(Inst, PFS, KeywordVal);
6996   // Other.
6997   case lltok::kw_select: {
6998     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6999     int Res = parseSelect(Inst, PFS);
7000     if (Res != 0)
7001       return Res;
7002     if (FMF.any()) {
7003       if (!isa<FPMathOperator>(Inst))
7004         return error(Loc, "fast-math-flags specified for select without "
7005                           "floating-point scalar or vector return type");
7006       Inst->setFastMathFlags(FMF);
7007     }
7008     return 0;
7009   }
7010   case lltok::kw_va_arg:
7011     return parseVAArg(Inst, PFS);
7012   case lltok::kw_extractelement:
7013     return parseExtractElement(Inst, PFS);
7014   case lltok::kw_insertelement:
7015     return parseInsertElement(Inst, PFS);
7016   case lltok::kw_shufflevector:
7017     return parseShuffleVector(Inst, PFS);
7018   case lltok::kw_phi: {
7019     FastMathFlags FMF = EatFastMathFlagsIfPresent();
7020     int Res = parsePHI(Inst, PFS);
7021     if (Res != 0)
7022       return Res;
7023     if (FMF.any()) {
7024       if (!isa<FPMathOperator>(Inst))
7025         return error(Loc, "fast-math-flags specified for phi without "
7026                           "floating-point scalar or vector return type");
7027       Inst->setFastMathFlags(FMF);
7028     }
7029     return 0;
7030   }
7031   case lltok::kw_landingpad:
7032     return parseLandingPad(Inst, PFS);
7033   case lltok::kw_freeze:
7034     return parseFreeze(Inst, PFS);
7035   // Call.
7036   case lltok::kw_call:
7037     return parseCall(Inst, PFS, CallInst::TCK_None);
7038   case lltok::kw_tail:
7039     return parseCall(Inst, PFS, CallInst::TCK_Tail);
7040   case lltok::kw_musttail:
7041     return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7042   case lltok::kw_notail:
7043     return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7044   // Memory.
7045   case lltok::kw_alloca:
7046     return parseAlloc(Inst, PFS);
7047   case lltok::kw_load:
7048     return parseLoad(Inst, PFS);
7049   case lltok::kw_store:
7050     return parseStore(Inst, PFS);
7051   case lltok::kw_cmpxchg:
7052     return parseCmpXchg(Inst, PFS);
7053   case lltok::kw_atomicrmw:
7054     return parseAtomicRMW(Inst, PFS);
7055   case lltok::kw_fence:
7056     return parseFence(Inst, PFS);
7057   case lltok::kw_getelementptr:
7058     return parseGetElementPtr(Inst, PFS);
7059   case lltok::kw_extractvalue:
7060     return parseExtractValue(Inst, PFS);
7061   case lltok::kw_insertvalue:
7062     return parseInsertValue(Inst, PFS);
7063   }
7064 }
7065 
7066 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7067 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7068   if (Opc == Instruction::FCmp) {
7069     switch (Lex.getKind()) {
7070     default:
7071       return tokError("expected fcmp predicate (e.g. 'oeq')");
7072     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7073     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7074     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7075     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7076     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7077     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7078     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7079     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7080     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7081     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7082     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7083     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7084     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7085     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7086     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7087     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7088     }
7089   } else {
7090     switch (Lex.getKind()) {
7091     default:
7092       return tokError("expected icmp predicate (e.g. 'eq')");
7093     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
7094     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
7095     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7096     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7097     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7098     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7099     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7100     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7101     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7102     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7103     }
7104   }
7105   Lex.Lex();
7106   return false;
7107 }
7108 
7109 //===----------------------------------------------------------------------===//
7110 // Terminator Instructions.
7111 //===----------------------------------------------------------------------===//
7112 
7113 /// parseRet - parse a return instruction.
7114 ///   ::= 'ret' void (',' !dbg, !1)*
7115 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
7116 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7117                         PerFunctionState &PFS) {
7118   SMLoc TypeLoc = Lex.getLoc();
7119   Type *Ty = nullptr;
7120   if (parseType(Ty, true /*void allowed*/))
7121     return true;
7122 
7123   Type *ResType = PFS.getFunction().getReturnType();
7124 
7125   if (Ty->isVoidTy()) {
7126     if (!ResType->isVoidTy())
7127       return error(TypeLoc, "value doesn't match function result type '" +
7128                                 getTypeString(ResType) + "'");
7129 
7130     Inst = ReturnInst::Create(Context);
7131     return false;
7132   }
7133 
7134   Value *RV;
7135   if (parseValue(Ty, RV, PFS))
7136     return true;
7137 
7138   if (ResType != RV->getType())
7139     return error(TypeLoc, "value doesn't match function result type '" +
7140                               getTypeString(ResType) + "'");
7141 
7142   Inst = ReturnInst::Create(Context, RV);
7143   return false;
7144 }
7145 
7146 /// parseBr
7147 ///   ::= 'br' TypeAndValue
7148 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7149 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7150   LocTy Loc, Loc2;
7151   Value *Op0;
7152   BasicBlock *Op1, *Op2;
7153   if (parseTypeAndValue(Op0, Loc, PFS))
7154     return true;
7155 
7156   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7157     Inst = BranchInst::Create(BB);
7158     return false;
7159   }
7160 
7161   if (Op0->getType() != Type::getInt1Ty(Context))
7162     return error(Loc, "branch condition must have 'i1' type");
7163 
7164   if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7165       parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7166       parseToken(lltok::comma, "expected ',' after true destination") ||
7167       parseTypeAndBasicBlock(Op2, Loc2, PFS))
7168     return true;
7169 
7170   Inst = BranchInst::Create(Op1, Op2, Op0);
7171   return false;
7172 }
7173 
7174 /// parseSwitch
7175 ///  Instruction
7176 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7177 ///  JumpTable
7178 ///    ::= (TypeAndValue ',' TypeAndValue)*
7179 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7180   LocTy CondLoc, BBLoc;
7181   Value *Cond;
7182   BasicBlock *DefaultBB;
7183   if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7184       parseToken(lltok::comma, "expected ',' after switch condition") ||
7185       parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7186       parseToken(lltok::lsquare, "expected '[' with switch table"))
7187     return true;
7188 
7189   if (!Cond->getType()->isIntegerTy())
7190     return error(CondLoc, "switch condition must have integer type");
7191 
7192   // parse the jump table pairs.
7193   SmallPtrSet<Value*, 32> SeenCases;
7194   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
7195   while (Lex.getKind() != lltok::rsquare) {
7196     Value *Constant;
7197     BasicBlock *DestBB;
7198 
7199     if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7200         parseToken(lltok::comma, "expected ',' after case value") ||
7201         parseTypeAndBasicBlock(DestBB, PFS))
7202       return true;
7203 
7204     if (!SeenCases.insert(Constant).second)
7205       return error(CondLoc, "duplicate case value in switch");
7206     if (!isa<ConstantInt>(Constant))
7207       return error(CondLoc, "case value is not a constant integer");
7208 
7209     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7210   }
7211 
7212   Lex.Lex();  // Eat the ']'.
7213 
7214   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7215   for (unsigned i = 0, e = Table.size(); i != e; ++i)
7216     SI->addCase(Table[i].first, Table[i].second);
7217   Inst = SI;
7218   return false;
7219 }
7220 
7221 /// parseIndirectBr
7222 ///  Instruction
7223 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7224 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7225   LocTy AddrLoc;
7226   Value *Address;
7227   if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7228       parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7229       parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7230     return true;
7231 
7232   if (!Address->getType()->isPointerTy())
7233     return error(AddrLoc, "indirectbr address must have pointer type");
7234 
7235   // parse the destination list.
7236   SmallVector<BasicBlock*, 16> DestList;
7237 
7238   if (Lex.getKind() != lltok::rsquare) {
7239     BasicBlock *DestBB;
7240     if (parseTypeAndBasicBlock(DestBB, PFS))
7241       return true;
7242     DestList.push_back(DestBB);
7243 
7244     while (EatIfPresent(lltok::comma)) {
7245       if (parseTypeAndBasicBlock(DestBB, PFS))
7246         return true;
7247       DestList.push_back(DestBB);
7248     }
7249   }
7250 
7251   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7252     return true;
7253 
7254   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7255   for (BasicBlock *Dest : DestList)
7256     IBI->addDestination(Dest);
7257   Inst = IBI;
7258   return false;
7259 }
7260 
7261 // If RetType is a non-function pointer type, then this is the short syntax
7262 // for the call, which means that RetType is just the return type.  Infer the
7263 // rest of the function argument types from the arguments that are present.
7264 bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7265                                    FunctionType *&FuncTy) {
7266   FuncTy = dyn_cast<FunctionType>(RetType);
7267   if (!FuncTy) {
7268     // Pull out the types of all of the arguments...
7269     SmallVector<Type *, 8> ParamTypes;
7270     ParamTypes.reserve(ArgList.size());
7271     for (const ParamInfo &Arg : ArgList)
7272       ParamTypes.push_back(Arg.V->getType());
7273 
7274     if (!FunctionType::isValidReturnType(RetType))
7275       return true;
7276 
7277     FuncTy = FunctionType::get(RetType, ParamTypes, false);
7278   }
7279   return false;
7280 }
7281 
7282 /// parseInvoke
7283 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7284 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7285 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7286   LocTy CallLoc = Lex.getLoc();
7287   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7288   std::vector<unsigned> FwdRefAttrGrps;
7289   LocTy NoBuiltinLoc;
7290   unsigned CC;
7291   unsigned InvokeAddrSpace;
7292   Type *RetType = nullptr;
7293   LocTy RetTypeLoc;
7294   ValID CalleeID;
7295   SmallVector<ParamInfo, 16> ArgList;
7296   SmallVector<OperandBundleDef, 2> BundleList;
7297 
7298   BasicBlock *NormalBB, *UnwindBB;
7299   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7300       parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7301       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7302       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7303       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7304                                  NoBuiltinLoc) ||
7305       parseOptionalOperandBundles(BundleList, PFS) ||
7306       parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7307       parseTypeAndBasicBlock(NormalBB, PFS) ||
7308       parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7309       parseTypeAndBasicBlock(UnwindBB, PFS))
7310     return true;
7311 
7312   // If RetType is a non-function pointer type, then this is the short syntax
7313   // for the call, which means that RetType is just the return type.  Infer the
7314   // rest of the function argument types from the arguments that are present.
7315   FunctionType *Ty;
7316   if (resolveFunctionType(RetType, ArgList, Ty))
7317     return error(RetTypeLoc, "Invalid result type for LLVM function");
7318 
7319   CalleeID.FTy = Ty;
7320 
7321   // Look up the callee.
7322   Value *Callee;
7323   if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
7324                           Callee, &PFS))
7325     return true;
7326 
7327   // Set up the Attribute for the function.
7328   SmallVector<Value *, 8> Args;
7329   SmallVector<AttributeSet, 8> ArgAttrs;
7330 
7331   // Loop through FunctionType's arguments and ensure they are specified
7332   // correctly.  Also, gather any parameter attributes.
7333   FunctionType::param_iterator I = Ty->param_begin();
7334   FunctionType::param_iterator E = Ty->param_end();
7335   for (const ParamInfo &Arg : ArgList) {
7336     Type *ExpectedTy = nullptr;
7337     if (I != E) {
7338       ExpectedTy = *I++;
7339     } else if (!Ty->isVarArg()) {
7340       return error(Arg.Loc, "too many arguments specified");
7341     }
7342 
7343     if (ExpectedTy && ExpectedTy != Arg.V->getType())
7344       return error(Arg.Loc, "argument is not of expected type '" +
7345                                 getTypeString(ExpectedTy) + "'");
7346     Args.push_back(Arg.V);
7347     ArgAttrs.push_back(Arg.Attrs);
7348   }
7349 
7350   if (I != E)
7351     return error(CallLoc, "not enough parameters specified for call");
7352 
7353   // Finish off the Attribute and check them
7354   AttributeList PAL =
7355       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7356                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
7357 
7358   InvokeInst *II =
7359       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7360   II->setCallingConv(CC);
7361   II->setAttributes(PAL);
7362   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7363   Inst = II;
7364   return false;
7365 }
7366 
7367 /// parseResume
7368 ///   ::= 'resume' TypeAndValue
7369 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7370   Value *Exn; LocTy ExnLoc;
7371   if (parseTypeAndValue(Exn, ExnLoc, PFS))
7372     return true;
7373 
7374   ResumeInst *RI = ResumeInst::Create(Exn);
7375   Inst = RI;
7376   return false;
7377 }
7378 
7379 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7380                                   PerFunctionState &PFS) {
7381   if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7382     return true;
7383 
7384   while (Lex.getKind() != lltok::rsquare) {
7385     // If this isn't the first argument, we need a comma.
7386     if (!Args.empty() &&
7387         parseToken(lltok::comma, "expected ',' in argument list"))
7388       return true;
7389 
7390     // parse the argument.
7391     LocTy ArgLoc;
7392     Type *ArgTy = nullptr;
7393     if (parseType(ArgTy, ArgLoc))
7394       return true;
7395 
7396     Value *V;
7397     if (ArgTy->isMetadataTy()) {
7398       if (parseMetadataAsValue(V, PFS))
7399         return true;
7400     } else {
7401       if (parseValue(ArgTy, V, PFS))
7402         return true;
7403     }
7404     Args.push_back(V);
7405   }
7406 
7407   Lex.Lex();  // Lex the ']'.
7408   return false;
7409 }
7410 
7411 /// parseCleanupRet
7412 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7413 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7414   Value *CleanupPad = nullptr;
7415 
7416   if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7417     return true;
7418 
7419   if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7420     return true;
7421 
7422   if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7423     return true;
7424 
7425   BasicBlock *UnwindBB = nullptr;
7426   if (Lex.getKind() == lltok::kw_to) {
7427     Lex.Lex();
7428     if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7429       return true;
7430   } else {
7431     if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7432       return true;
7433     }
7434   }
7435 
7436   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7437   return false;
7438 }
7439 
7440 /// parseCatchRet
7441 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
7442 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7443   Value *CatchPad = nullptr;
7444 
7445   if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7446     return true;
7447 
7448   if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7449     return true;
7450 
7451   BasicBlock *BB;
7452   if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7453       parseTypeAndBasicBlock(BB, PFS))
7454     return true;
7455 
7456   Inst = CatchReturnInst::Create(CatchPad, BB);
7457   return false;
7458 }
7459 
7460 /// parseCatchSwitch
7461 ///   ::= 'catchswitch' within Parent
7462 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7463   Value *ParentPad;
7464 
7465   if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7466     return true;
7467 
7468   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7469       Lex.getKind() != lltok::LocalVarID)
7470     return tokError("expected scope value for catchswitch");
7471 
7472   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7473     return true;
7474 
7475   if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7476     return true;
7477 
7478   SmallVector<BasicBlock *, 32> Table;
7479   do {
7480     BasicBlock *DestBB;
7481     if (parseTypeAndBasicBlock(DestBB, PFS))
7482       return true;
7483     Table.push_back(DestBB);
7484   } while (EatIfPresent(lltok::comma));
7485 
7486   if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7487     return true;
7488 
7489   if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7490     return true;
7491 
7492   BasicBlock *UnwindBB = nullptr;
7493   if (EatIfPresent(lltok::kw_to)) {
7494     if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7495       return true;
7496   } else {
7497     if (parseTypeAndBasicBlock(UnwindBB, PFS))
7498       return true;
7499   }
7500 
7501   auto *CatchSwitch =
7502       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7503   for (BasicBlock *DestBB : Table)
7504     CatchSwitch->addHandler(DestBB);
7505   Inst = CatchSwitch;
7506   return false;
7507 }
7508 
7509 /// parseCatchPad
7510 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7511 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7512   Value *CatchSwitch = nullptr;
7513 
7514   if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7515     return true;
7516 
7517   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7518     return tokError("expected scope value for catchpad");
7519 
7520   if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7521     return true;
7522 
7523   SmallVector<Value *, 8> Args;
7524   if (parseExceptionArgs(Args, PFS))
7525     return true;
7526 
7527   Inst = CatchPadInst::Create(CatchSwitch, Args);
7528   return false;
7529 }
7530 
7531 /// parseCleanupPad
7532 ///   ::= 'cleanuppad' within Parent ParamList
7533 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7534   Value *ParentPad = nullptr;
7535 
7536   if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7537     return true;
7538 
7539   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7540       Lex.getKind() != lltok::LocalVarID)
7541     return tokError("expected scope value for cleanuppad");
7542 
7543   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7544     return true;
7545 
7546   SmallVector<Value *, 8> Args;
7547   if (parseExceptionArgs(Args, PFS))
7548     return true;
7549 
7550   Inst = CleanupPadInst::Create(ParentPad, Args);
7551   return false;
7552 }
7553 
7554 //===----------------------------------------------------------------------===//
7555 // Unary Operators.
7556 //===----------------------------------------------------------------------===//
7557 
7558 /// parseUnaryOp
7559 ///  ::= UnaryOp TypeAndValue ',' Value
7560 ///
7561 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7562 /// operand is allowed.
7563 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7564                             unsigned Opc, bool IsFP) {
7565   LocTy Loc; Value *LHS;
7566   if (parseTypeAndValue(LHS, Loc, PFS))
7567     return true;
7568 
7569   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7570                     : LHS->getType()->isIntOrIntVectorTy();
7571 
7572   if (!Valid)
7573     return error(Loc, "invalid operand type for instruction");
7574 
7575   Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
7576   return false;
7577 }
7578 
7579 /// parseCallBr
7580 ///   ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7581 ///       OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7582 ///       '[' LabelList ']'
7583 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7584   LocTy CallLoc = Lex.getLoc();
7585   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7586   std::vector<unsigned> FwdRefAttrGrps;
7587   LocTy NoBuiltinLoc;
7588   unsigned CC;
7589   Type *RetType = nullptr;
7590   LocTy RetTypeLoc;
7591   ValID CalleeID;
7592   SmallVector<ParamInfo, 16> ArgList;
7593   SmallVector<OperandBundleDef, 2> BundleList;
7594 
7595   BasicBlock *DefaultDest;
7596   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7597       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7598       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7599       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7600                                  NoBuiltinLoc) ||
7601       parseOptionalOperandBundles(BundleList, PFS) ||
7602       parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7603       parseTypeAndBasicBlock(DefaultDest, PFS) ||
7604       parseToken(lltok::lsquare, "expected '[' in callbr"))
7605     return true;
7606 
7607   // parse the destination list.
7608   SmallVector<BasicBlock *, 16> IndirectDests;
7609 
7610   if (Lex.getKind() != lltok::rsquare) {
7611     BasicBlock *DestBB;
7612     if (parseTypeAndBasicBlock(DestBB, PFS))
7613       return true;
7614     IndirectDests.push_back(DestBB);
7615 
7616     while (EatIfPresent(lltok::comma)) {
7617       if (parseTypeAndBasicBlock(DestBB, PFS))
7618         return true;
7619       IndirectDests.push_back(DestBB);
7620     }
7621   }
7622 
7623   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7624     return true;
7625 
7626   // If RetType is a non-function pointer type, then this is the short syntax
7627   // for the call, which means that RetType is just the return type.  Infer the
7628   // rest of the function argument types from the arguments that are present.
7629   FunctionType *Ty;
7630   if (resolveFunctionType(RetType, ArgList, Ty))
7631     return error(RetTypeLoc, "Invalid result type for LLVM function");
7632 
7633   CalleeID.FTy = Ty;
7634 
7635   // Look up the callee.
7636   Value *Callee;
7637   if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
7638     return true;
7639 
7640   // Set up the Attribute for the function.
7641   SmallVector<Value *, 8> Args;
7642   SmallVector<AttributeSet, 8> ArgAttrs;
7643 
7644   // Loop through FunctionType's arguments and ensure they are specified
7645   // correctly.  Also, gather any parameter attributes.
7646   FunctionType::param_iterator I = Ty->param_begin();
7647   FunctionType::param_iterator E = Ty->param_end();
7648   for (const ParamInfo &Arg : ArgList) {
7649     Type *ExpectedTy = nullptr;
7650     if (I != E) {
7651       ExpectedTy = *I++;
7652     } else if (!Ty->isVarArg()) {
7653       return error(Arg.Loc, "too many arguments specified");
7654     }
7655 
7656     if (ExpectedTy && ExpectedTy != Arg.V->getType())
7657       return error(Arg.Loc, "argument is not of expected type '" +
7658                                 getTypeString(ExpectedTy) + "'");
7659     Args.push_back(Arg.V);
7660     ArgAttrs.push_back(Arg.Attrs);
7661   }
7662 
7663   if (I != E)
7664     return error(CallLoc, "not enough parameters specified for call");
7665 
7666   // Finish off the Attribute and check them
7667   AttributeList PAL =
7668       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7669                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
7670 
7671   CallBrInst *CBI =
7672       CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
7673                          BundleList);
7674   CBI->setCallingConv(CC);
7675   CBI->setAttributes(PAL);
7676   ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7677   Inst = CBI;
7678   return false;
7679 }
7680 
7681 //===----------------------------------------------------------------------===//
7682 // Binary Operators.
7683 //===----------------------------------------------------------------------===//
7684 
7685 /// parseArithmetic
7686 ///  ::= ArithmeticOps TypeAndValue ',' Value
7687 ///
7688 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7689 /// operand is allowed.
7690 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
7691                                unsigned Opc, bool IsFP) {
7692   LocTy Loc; Value *LHS, *RHS;
7693   if (parseTypeAndValue(LHS, Loc, PFS) ||
7694       parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
7695       parseValue(LHS->getType(), RHS, PFS))
7696     return true;
7697 
7698   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7699                     : LHS->getType()->isIntOrIntVectorTy();
7700 
7701   if (!Valid)
7702     return error(Loc, "invalid operand type for instruction");
7703 
7704   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7705   return false;
7706 }
7707 
7708 /// parseLogical
7709 ///  ::= ArithmeticOps TypeAndValue ',' Value {
7710 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
7711                             unsigned Opc) {
7712   LocTy Loc; Value *LHS, *RHS;
7713   if (parseTypeAndValue(LHS, Loc, PFS) ||
7714       parseToken(lltok::comma, "expected ',' in logical operation") ||
7715       parseValue(LHS->getType(), RHS, PFS))
7716     return true;
7717 
7718   if (!LHS->getType()->isIntOrIntVectorTy())
7719     return error(Loc,
7720                  "instruction requires integer or integer vector operands");
7721 
7722   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7723   return false;
7724 }
7725 
7726 /// parseCompare
7727 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
7728 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
7729 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7730                             unsigned Opc) {
7731   // parse the integer/fp comparison predicate.
7732   LocTy Loc;
7733   unsigned Pred;
7734   Value *LHS, *RHS;
7735   if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7736       parseToken(lltok::comma, "expected ',' after compare value") ||
7737       parseValue(LHS->getType(), RHS, PFS))
7738     return true;
7739 
7740   if (Opc == Instruction::FCmp) {
7741     if (!LHS->getType()->isFPOrFPVectorTy())
7742       return error(Loc, "fcmp requires floating point operands");
7743     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7744   } else {
7745     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7746     if (!LHS->getType()->isIntOrIntVectorTy() &&
7747         !LHS->getType()->isPtrOrPtrVectorTy())
7748       return error(Loc, "icmp requires integer operands");
7749     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7750   }
7751   return false;
7752 }
7753 
7754 //===----------------------------------------------------------------------===//
7755 // Other Instructions.
7756 //===----------------------------------------------------------------------===//
7757 
7758 /// parseCast
7759 ///   ::= CastOpc TypeAndValue 'to' Type
7760 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7761                          unsigned Opc) {
7762   LocTy Loc;
7763   Value *Op;
7764   Type *DestTy = nullptr;
7765   if (parseTypeAndValue(Op, Loc, PFS) ||
7766       parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7767       parseType(DestTy))
7768     return true;
7769 
7770   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
7771     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
7772     return error(Loc, "invalid cast opcode for cast from '" +
7773                           getTypeString(Op->getType()) + "' to '" +
7774                           getTypeString(DestTy) + "'");
7775   }
7776   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7777   return false;
7778 }
7779 
7780 /// parseSelect
7781 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7782 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7783   LocTy Loc;
7784   Value *Op0, *Op1, *Op2;
7785   if (parseTypeAndValue(Op0, Loc, PFS) ||
7786       parseToken(lltok::comma, "expected ',' after select condition") ||
7787       parseTypeAndValue(Op1, PFS) ||
7788       parseToken(lltok::comma, "expected ',' after select value") ||
7789       parseTypeAndValue(Op2, PFS))
7790     return true;
7791 
7792   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7793     return error(Loc, Reason);
7794 
7795   Inst = SelectInst::Create(Op0, Op1, Op2);
7796   return false;
7797 }
7798 
7799 /// parseVAArg
7800 ///   ::= 'va_arg' TypeAndValue ',' Type
7801 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7802   Value *Op;
7803   Type *EltTy = nullptr;
7804   LocTy TypeLoc;
7805   if (parseTypeAndValue(Op, PFS) ||
7806       parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7807       parseType(EltTy, TypeLoc))
7808     return true;
7809 
7810   if (!EltTy->isFirstClassType())
7811     return error(TypeLoc, "va_arg requires operand with first class type");
7812 
7813   Inst = new VAArgInst(Op, EltTy);
7814   return false;
7815 }
7816 
7817 /// parseExtractElement
7818 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
7819 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7820   LocTy Loc;
7821   Value *Op0, *Op1;
7822   if (parseTypeAndValue(Op0, Loc, PFS) ||
7823       parseToken(lltok::comma, "expected ',' after extract value") ||
7824       parseTypeAndValue(Op1, PFS))
7825     return true;
7826 
7827   if (!ExtractElementInst::isValidOperands(Op0, Op1))
7828     return error(Loc, "invalid extractelement operands");
7829 
7830   Inst = ExtractElementInst::Create(Op0, Op1);
7831   return false;
7832 }
7833 
7834 /// parseInsertElement
7835 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7836 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7837   LocTy Loc;
7838   Value *Op0, *Op1, *Op2;
7839   if (parseTypeAndValue(Op0, Loc, PFS) ||
7840       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7841       parseTypeAndValue(Op1, PFS) ||
7842       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7843       parseTypeAndValue(Op2, PFS))
7844     return true;
7845 
7846   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7847     return error(Loc, "invalid insertelement operands");
7848 
7849   Inst = InsertElementInst::Create(Op0, Op1, Op2);
7850   return false;
7851 }
7852 
7853 /// parseShuffleVector
7854 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7855 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7856   LocTy Loc;
7857   Value *Op0, *Op1, *Op2;
7858   if (parseTypeAndValue(Op0, Loc, PFS) ||
7859       parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7860       parseTypeAndValue(Op1, PFS) ||
7861       parseToken(lltok::comma, "expected ',' after shuffle value") ||
7862       parseTypeAndValue(Op2, PFS))
7863     return true;
7864 
7865   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7866     return error(Loc, "invalid shufflevector operands");
7867 
7868   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7869   return false;
7870 }
7871 
7872 /// parsePHI
7873 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7874 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7875   Type *Ty = nullptr;  LocTy TypeLoc;
7876   Value *Op0, *Op1;
7877 
7878   if (parseType(Ty, TypeLoc))
7879     return true;
7880 
7881   if (!Ty->isFirstClassType())
7882     return error(TypeLoc, "phi node must have first class type");
7883 
7884   bool First = true;
7885   bool AteExtraComma = false;
7886   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
7887 
7888   while (true) {
7889     if (First) {
7890       if (Lex.getKind() != lltok::lsquare)
7891         break;
7892       First = false;
7893     } else if (!EatIfPresent(lltok::comma))
7894       break;
7895 
7896     if (Lex.getKind() == lltok::MetadataVar) {
7897       AteExtraComma = true;
7898       break;
7899     }
7900 
7901     if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7902         parseValue(Ty, Op0, PFS) ||
7903         parseToken(lltok::comma, "expected ',' after insertelement value") ||
7904         parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7905         parseToken(lltok::rsquare, "expected ']' in phi value list"))
7906       return true;
7907 
7908     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7909   }
7910 
7911   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7912   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7913     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7914   Inst = PN;
7915   return AteExtraComma ? InstExtraComma : InstNormal;
7916 }
7917 
7918 /// parseLandingPad
7919 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7920 /// Clause
7921 ///   ::= 'catch' TypeAndValue
7922 ///   ::= 'filter'
7923 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7924 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7925   Type *Ty = nullptr; LocTy TyLoc;
7926 
7927   if (parseType(Ty, TyLoc))
7928     return true;
7929 
7930   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7931   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7932 
7933   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7934     LandingPadInst::ClauseType CT;
7935     if (EatIfPresent(lltok::kw_catch))
7936       CT = LandingPadInst::Catch;
7937     else if (EatIfPresent(lltok::kw_filter))
7938       CT = LandingPadInst::Filter;
7939     else
7940       return tokError("expected 'catch' or 'filter' clause type");
7941 
7942     Value *V;
7943     LocTy VLoc;
7944     if (parseTypeAndValue(V, VLoc, PFS))
7945       return true;
7946 
7947     // A 'catch' type expects a non-array constant. A filter clause expects an
7948     // array constant.
7949     if (CT == LandingPadInst::Catch) {
7950       if (isa<ArrayType>(V->getType()))
7951         return error(VLoc, "'catch' clause has an invalid type");
7952     } else {
7953       if (!isa<ArrayType>(V->getType()))
7954         return error(VLoc, "'filter' clause has an invalid type");
7955     }
7956 
7957     Constant *CV = dyn_cast<Constant>(V);
7958     if (!CV)
7959       return error(VLoc, "clause argument must be a constant");
7960     LP->addClause(CV);
7961   }
7962 
7963   Inst = LP.release();
7964   return false;
7965 }
7966 
7967 /// parseFreeze
7968 ///   ::= 'freeze' Type Value
7969 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7970   LocTy Loc;
7971   Value *Op;
7972   if (parseTypeAndValue(Op, Loc, PFS))
7973     return true;
7974 
7975   Inst = new FreezeInst(Op);
7976   return false;
7977 }
7978 
7979 /// parseCall
7980 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
7981 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7982 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7983 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7984 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7985 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7986 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
7987 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7988 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7989                          CallInst::TailCallKind TCK) {
7990   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7991   std::vector<unsigned> FwdRefAttrGrps;
7992   LocTy BuiltinLoc;
7993   unsigned CallAddrSpace;
7994   unsigned CC;
7995   Type *RetType = nullptr;
7996   LocTy RetTypeLoc;
7997   ValID CalleeID;
7998   SmallVector<ParamInfo, 16> ArgList;
7999   SmallVector<OperandBundleDef, 2> BundleList;
8000   LocTy CallLoc = Lex.getLoc();
8001 
8002   if (TCK != CallInst::TCK_None &&
8003       parseToken(lltok::kw_call,
8004                  "expected 'tail call', 'musttail call', or 'notail call'"))
8005     return true;
8006 
8007   FastMathFlags FMF = EatFastMathFlagsIfPresent();
8008 
8009   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8010       parseOptionalProgramAddrSpace(CallAddrSpace) ||
8011       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8012       parseValID(CalleeID, &PFS) ||
8013       parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8014                          PFS.getFunction().isVarArg()) ||
8015       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8016       parseOptionalOperandBundles(BundleList, PFS))
8017     return true;
8018 
8019   // If RetType is a non-function pointer type, then this is the short syntax
8020   // for the call, which means that RetType is just the return type.  Infer the
8021   // rest of the function argument types from the arguments that are present.
8022   FunctionType *Ty;
8023   if (resolveFunctionType(RetType, ArgList, Ty))
8024     return error(RetTypeLoc, "Invalid result type for LLVM function");
8025 
8026   CalleeID.FTy = Ty;
8027 
8028   // Look up the callee.
8029   Value *Callee;
8030   if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
8031                           &PFS))
8032     return true;
8033 
8034   // Set up the Attribute for the function.
8035   SmallVector<AttributeSet, 8> Attrs;
8036 
8037   SmallVector<Value*, 8> Args;
8038 
8039   // Loop through FunctionType's arguments and ensure they are specified
8040   // correctly.  Also, gather any parameter attributes.
8041   FunctionType::param_iterator I = Ty->param_begin();
8042   FunctionType::param_iterator E = Ty->param_end();
8043   for (const ParamInfo &Arg : ArgList) {
8044     Type *ExpectedTy = nullptr;
8045     if (I != E) {
8046       ExpectedTy = *I++;
8047     } else if (!Ty->isVarArg()) {
8048       return error(Arg.Loc, "too many arguments specified");
8049     }
8050 
8051     if (ExpectedTy && ExpectedTy != Arg.V->getType())
8052       return error(Arg.Loc, "argument is not of expected type '" +
8053                                 getTypeString(ExpectedTy) + "'");
8054     Args.push_back(Arg.V);
8055     Attrs.push_back(Arg.Attrs);
8056   }
8057 
8058   if (I != E)
8059     return error(CallLoc, "not enough parameters specified for call");
8060 
8061   // Finish off the Attribute and check them
8062   AttributeList PAL =
8063       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8064                          AttributeSet::get(Context, RetAttrs), Attrs);
8065 
8066   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8067   CI->setTailCallKind(TCK);
8068   CI->setCallingConv(CC);
8069   if (FMF.any()) {
8070     if (!isa<FPMathOperator>(CI)) {
8071       CI->deleteValue();
8072       return error(CallLoc, "fast-math-flags specified for call without "
8073                             "floating-point scalar or vector return type");
8074     }
8075     CI->setFastMathFlags(FMF);
8076   }
8077 
8078   if (CalleeID.Kind == ValID::t_GlobalName &&
8079       isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8080     if (SeenNewDbgInfoFormat) {
8081       CI->deleteValue();
8082       return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8083                             "using non-intrinsic debug info");
8084     }
8085     if (!SeenOldDbgInfoFormat)
8086       M->setNewDbgInfoFormatFlag(false);
8087     SeenOldDbgInfoFormat = true;
8088   }
8089   CI->setAttributes(PAL);
8090   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8091   Inst = CI;
8092   return false;
8093 }
8094 
8095 //===----------------------------------------------------------------------===//
8096 // Memory Instructions.
8097 //===----------------------------------------------------------------------===//
8098 
8099 /// parseAlloc
8100 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8101 ///       (',' 'align' i32)? (',', 'addrspace(n))?
8102 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8103   Value *Size = nullptr;
8104   LocTy SizeLoc, TyLoc, ASLoc;
8105   MaybeAlign Alignment;
8106   unsigned AddrSpace = 0;
8107   Type *Ty = nullptr;
8108 
8109   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8110   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8111 
8112   if (parseType(Ty, TyLoc))
8113     return true;
8114 
8115   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
8116     return error(TyLoc, "invalid type for alloca");
8117 
8118   bool AteExtraComma = false;
8119   if (EatIfPresent(lltok::comma)) {
8120     if (Lex.getKind() == lltok::kw_align) {
8121       if (parseOptionalAlignment(Alignment))
8122         return true;
8123       if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8124         return true;
8125     } else if (Lex.getKind() == lltok::kw_addrspace) {
8126       ASLoc = Lex.getLoc();
8127       if (parseOptionalAddrSpace(AddrSpace))
8128         return true;
8129     } else if (Lex.getKind() == lltok::MetadataVar) {
8130       AteExtraComma = true;
8131     } else {
8132       if (parseTypeAndValue(Size, SizeLoc, PFS))
8133         return true;
8134       if (EatIfPresent(lltok::comma)) {
8135         if (Lex.getKind() == lltok::kw_align) {
8136           if (parseOptionalAlignment(Alignment))
8137             return true;
8138           if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8139             return true;
8140         } else if (Lex.getKind() == lltok::kw_addrspace) {
8141           ASLoc = Lex.getLoc();
8142           if (parseOptionalAddrSpace(AddrSpace))
8143             return true;
8144         } else if (Lex.getKind() == lltok::MetadataVar) {
8145           AteExtraComma = true;
8146         }
8147       }
8148     }
8149   }
8150 
8151   if (Size && !Size->getType()->isIntegerTy())
8152     return error(SizeLoc, "element count must have integer type");
8153 
8154   SmallPtrSet<Type *, 4> Visited;
8155   if (!Alignment && !Ty->isSized(&Visited))
8156     return error(TyLoc, "Cannot allocate unsized type");
8157   if (!Alignment)
8158     Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8159   AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8160   AI->setUsedWithInAlloca(IsInAlloca);
8161   AI->setSwiftError(IsSwiftError);
8162   Inst = AI;
8163   return AteExtraComma ? InstExtraComma : InstNormal;
8164 }
8165 
8166 /// parseLoad
8167 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8168 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
8169 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
8170 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8171   Value *Val; LocTy Loc;
8172   MaybeAlign Alignment;
8173   bool AteExtraComma = false;
8174   bool isAtomic = false;
8175   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
8176   SyncScope::ID SSID = SyncScope::System;
8177 
8178   if (Lex.getKind() == lltok::kw_atomic) {
8179     isAtomic = true;
8180     Lex.Lex();
8181   }
8182 
8183   bool isVolatile = false;
8184   if (Lex.getKind() == lltok::kw_volatile) {
8185     isVolatile = true;
8186     Lex.Lex();
8187   }
8188 
8189   Type *Ty;
8190   LocTy ExplicitTypeLoc = Lex.getLoc();
8191   if (parseType(Ty) ||
8192       parseToken(lltok::comma, "expected comma after load's type") ||
8193       parseTypeAndValue(Val, Loc, PFS) ||
8194       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8195       parseOptionalCommaAlign(Alignment, AteExtraComma))
8196     return true;
8197 
8198   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8199     return error(Loc, "load operand must be a pointer to a first class type");
8200   if (isAtomic && !Alignment)
8201     return error(Loc, "atomic load must have explicit non-zero alignment");
8202   if (Ordering == AtomicOrdering::Release ||
8203       Ordering == AtomicOrdering::AcquireRelease)
8204     return error(Loc, "atomic load cannot use Release ordering");
8205 
8206   SmallPtrSet<Type *, 4> Visited;
8207   if (!Alignment && !Ty->isSized(&Visited))
8208     return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8209   if (!Alignment)
8210     Alignment = M->getDataLayout().getABITypeAlign(Ty);
8211   Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8212   return AteExtraComma ? InstExtraComma : InstNormal;
8213 }
8214 
8215 /// parseStore
8216 
8217 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8218 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8219 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
8220 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8221   Value *Val, *Ptr; LocTy Loc, PtrLoc;
8222   MaybeAlign Alignment;
8223   bool AteExtraComma = false;
8224   bool isAtomic = false;
8225   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
8226   SyncScope::ID SSID = SyncScope::System;
8227 
8228   if (Lex.getKind() == lltok::kw_atomic) {
8229     isAtomic = true;
8230     Lex.Lex();
8231   }
8232 
8233   bool isVolatile = false;
8234   if (Lex.getKind() == lltok::kw_volatile) {
8235     isVolatile = true;
8236     Lex.Lex();
8237   }
8238 
8239   if (parseTypeAndValue(Val, Loc, PFS) ||
8240       parseToken(lltok::comma, "expected ',' after store operand") ||
8241       parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8242       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8243       parseOptionalCommaAlign(Alignment, AteExtraComma))
8244     return true;
8245 
8246   if (!Ptr->getType()->isPointerTy())
8247     return error(PtrLoc, "store operand must be a pointer");
8248   if (!Val->getType()->isFirstClassType())
8249     return error(Loc, "store operand must be a first class value");
8250   if (isAtomic && !Alignment)
8251     return error(Loc, "atomic store must have explicit non-zero alignment");
8252   if (Ordering == AtomicOrdering::Acquire ||
8253       Ordering == AtomicOrdering::AcquireRelease)
8254     return error(Loc, "atomic store cannot use Acquire ordering");
8255   SmallPtrSet<Type *, 4> Visited;
8256   if (!Alignment && !Val->getType()->isSized(&Visited))
8257     return error(Loc, "storing unsized types is not allowed");
8258   if (!Alignment)
8259     Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8260 
8261   Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8262   return AteExtraComma ? InstExtraComma : InstNormal;
8263 }
8264 
8265 /// parseCmpXchg
8266 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8267 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8268 ///       'Align'?
8269 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8270   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8271   bool AteExtraComma = false;
8272   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8273   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8274   SyncScope::ID SSID = SyncScope::System;
8275   bool isVolatile = false;
8276   bool isWeak = false;
8277   MaybeAlign Alignment;
8278 
8279   if (EatIfPresent(lltok::kw_weak))
8280     isWeak = true;
8281 
8282   if (EatIfPresent(lltok::kw_volatile))
8283     isVolatile = true;
8284 
8285   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8286       parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8287       parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8288       parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8289       parseTypeAndValue(New, NewLoc, PFS) ||
8290       parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8291       parseOrdering(FailureOrdering) ||
8292       parseOptionalCommaAlign(Alignment, AteExtraComma))
8293     return true;
8294 
8295   if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8296     return tokError("invalid cmpxchg success ordering");
8297   if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8298     return tokError("invalid cmpxchg failure ordering");
8299   if (!Ptr->getType()->isPointerTy())
8300     return error(PtrLoc, "cmpxchg operand must be a pointer");
8301   if (Cmp->getType() != New->getType())
8302     return error(NewLoc, "compare value and new value type do not match");
8303   if (!New->getType()->isFirstClassType())
8304     return error(NewLoc, "cmpxchg operand must be a first class value");
8305 
8306   const Align DefaultAlignment(
8307       PFS.getFunction().getDataLayout().getTypeStoreSize(
8308           Cmp->getType()));
8309 
8310   AtomicCmpXchgInst *CXI =
8311       new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8312                             SuccessOrdering, FailureOrdering, SSID);
8313   CXI->setVolatile(isVolatile);
8314   CXI->setWeak(isWeak);
8315 
8316   Inst = CXI;
8317   return AteExtraComma ? InstExtraComma : InstNormal;
8318 }
8319 
8320 /// parseAtomicRMW
8321 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8322 ///       'singlethread'? AtomicOrdering
8323 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8324   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8325   bool AteExtraComma = false;
8326   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
8327   SyncScope::ID SSID = SyncScope::System;
8328   bool isVolatile = false;
8329   bool IsFP = false;
8330   AtomicRMWInst::BinOp Operation;
8331   MaybeAlign Alignment;
8332 
8333   if (EatIfPresent(lltok::kw_volatile))
8334     isVolatile = true;
8335 
8336   switch (Lex.getKind()) {
8337   default:
8338     return tokError("expected binary operation in atomicrmw");
8339   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
8340   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
8341   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
8342   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
8343   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
8344   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
8345   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
8346   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
8347   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
8348   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
8349   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
8350   case lltok::kw_uinc_wrap:
8351     Operation = AtomicRMWInst::UIncWrap;
8352     break;
8353   case lltok::kw_udec_wrap:
8354     Operation = AtomicRMWInst::UDecWrap;
8355     break;
8356   case lltok::kw_usub_cond:
8357     Operation = AtomicRMWInst::USubCond;
8358     break;
8359   case lltok::kw_usub_sat:
8360     Operation = AtomicRMWInst::USubSat;
8361     break;
8362   case lltok::kw_fadd:
8363     Operation = AtomicRMWInst::FAdd;
8364     IsFP = true;
8365     break;
8366   case lltok::kw_fsub:
8367     Operation = AtomicRMWInst::FSub;
8368     IsFP = true;
8369     break;
8370   case lltok::kw_fmax:
8371     Operation = AtomicRMWInst::FMax;
8372     IsFP = true;
8373     break;
8374   case lltok::kw_fmin:
8375     Operation = AtomicRMWInst::FMin;
8376     IsFP = true;
8377     break;
8378   }
8379   Lex.Lex();  // Eat the operation.
8380 
8381   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8382       parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8383       parseTypeAndValue(Val, ValLoc, PFS) ||
8384       parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8385       parseOptionalCommaAlign(Alignment, AteExtraComma))
8386     return true;
8387 
8388   if (Ordering == AtomicOrdering::Unordered)
8389     return tokError("atomicrmw cannot be unordered");
8390   if (!Ptr->getType()->isPointerTy())
8391     return error(PtrLoc, "atomicrmw operand must be a pointer");
8392   if (Val->getType()->isScalableTy())
8393     return error(ValLoc, "atomicrmw operand may not be scalable");
8394 
8395   if (Operation == AtomicRMWInst::Xchg) {
8396     if (!Val->getType()->isIntegerTy() &&
8397         !Val->getType()->isFloatingPointTy() &&
8398         !Val->getType()->isPointerTy()) {
8399       return error(
8400           ValLoc,
8401           "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
8402               " operand must be an integer, floating point, or pointer type");
8403     }
8404   } else if (IsFP) {
8405     if (!Val->getType()->isFPOrFPVectorTy()) {
8406       return error(ValLoc, "atomicrmw " +
8407                                AtomicRMWInst::getOperationName(Operation) +
8408                                " operand must be a floating point type");
8409     }
8410   } else {
8411     if (!Val->getType()->isIntegerTy()) {
8412       return error(ValLoc, "atomicrmw " +
8413                                AtomicRMWInst::getOperationName(Operation) +
8414                                " operand must be an integer");
8415     }
8416   }
8417 
8418   unsigned Size =
8419       PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8420           Val->getType());
8421   if (Size < 8 || (Size & (Size - 1)))
8422     return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8423                          " integer");
8424   const Align DefaultAlignment(
8425       PFS.getFunction().getDataLayout().getTypeStoreSize(
8426           Val->getType()));
8427   AtomicRMWInst *RMWI =
8428       new AtomicRMWInst(Operation, Ptr, Val,
8429                         Alignment.value_or(DefaultAlignment), Ordering, SSID);
8430   RMWI->setVolatile(isVolatile);
8431   Inst = RMWI;
8432   return AteExtraComma ? InstExtraComma : InstNormal;
8433 }
8434 
8435 /// parseFence
8436 ///   ::= 'fence' 'singlethread'? AtomicOrdering
8437 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8438   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
8439   SyncScope::ID SSID = SyncScope::System;
8440   if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8441     return true;
8442 
8443   if (Ordering == AtomicOrdering::Unordered)
8444     return tokError("fence cannot be unordered");
8445   if (Ordering == AtomicOrdering::Monotonic)
8446     return tokError("fence cannot be monotonic");
8447 
8448   Inst = new FenceInst(Context, Ordering, SSID);
8449   return InstNormal;
8450 }
8451 
8452 /// parseGetElementPtr
8453 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8454 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8455   Value *Ptr = nullptr;
8456   Value *Val = nullptr;
8457   LocTy Loc, EltLoc;
8458   GEPNoWrapFlags NW;
8459 
8460   while (true) {
8461     if (EatIfPresent(lltok::kw_inbounds))
8462       NW |= GEPNoWrapFlags::inBounds();
8463     else if (EatIfPresent(lltok::kw_nusw))
8464       NW |= GEPNoWrapFlags::noUnsignedSignedWrap();
8465     else if (EatIfPresent(lltok::kw_nuw))
8466       NW |= GEPNoWrapFlags::noUnsignedWrap();
8467     else
8468       break;
8469   }
8470 
8471   Type *Ty = nullptr;
8472   if (parseType(Ty) ||
8473       parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8474       parseTypeAndValue(Ptr, Loc, PFS))
8475     return true;
8476 
8477   Type *BaseType = Ptr->getType();
8478   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8479   if (!BasePointerType)
8480     return error(Loc, "base of getelementptr must be a pointer");
8481 
8482   SmallVector<Value*, 16> Indices;
8483   bool AteExtraComma = false;
8484   // GEP returns a vector of pointers if at least one of parameters is a vector.
8485   // All vector parameters should have the same vector width.
8486   ElementCount GEPWidth = BaseType->isVectorTy()
8487                               ? cast<VectorType>(BaseType)->getElementCount()
8488                               : ElementCount::getFixed(0);
8489 
8490   while (EatIfPresent(lltok::comma)) {
8491     if (Lex.getKind() == lltok::MetadataVar) {
8492       AteExtraComma = true;
8493       break;
8494     }
8495     if (parseTypeAndValue(Val, EltLoc, PFS))
8496       return true;
8497     if (!Val->getType()->isIntOrIntVectorTy())
8498       return error(EltLoc, "getelementptr index must be an integer");
8499 
8500     if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8501       ElementCount ValNumEl = ValVTy->getElementCount();
8502       if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8503         return error(
8504             EltLoc,
8505             "getelementptr vector index has a wrong number of elements");
8506       GEPWidth = ValNumEl;
8507     }
8508     Indices.push_back(Val);
8509   }
8510 
8511   SmallPtrSet<Type*, 4> Visited;
8512   if (!Indices.empty() && !Ty->isSized(&Visited))
8513     return error(Loc, "base element of getelementptr must be sized");
8514 
8515   auto *STy = dyn_cast<StructType>(Ty);
8516   if (STy && STy->containsScalableVectorType())
8517     return error(Loc, "getelementptr cannot target structure that contains "
8518                       "scalable vector type");
8519 
8520   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8521     return error(Loc, "invalid getelementptr indices");
8522   GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8523   Inst = GEP;
8524   GEP->setNoWrapFlags(NW);
8525   return AteExtraComma ? InstExtraComma : InstNormal;
8526 }
8527 
8528 /// parseExtractValue
8529 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
8530 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8531   Value *Val; LocTy Loc;
8532   SmallVector<unsigned, 4> Indices;
8533   bool AteExtraComma;
8534   if (parseTypeAndValue(Val, Loc, PFS) ||
8535       parseIndexList(Indices, AteExtraComma))
8536     return true;
8537 
8538   if (!Val->getType()->isAggregateType())
8539     return error(Loc, "extractvalue operand must be aggregate type");
8540 
8541   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8542     return error(Loc, "invalid indices for extractvalue");
8543   Inst = ExtractValueInst::Create(Val, Indices);
8544   return AteExtraComma ? InstExtraComma : InstNormal;
8545 }
8546 
8547 /// parseInsertValue
8548 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8549 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8550   Value *Val0, *Val1; LocTy Loc0, Loc1;
8551   SmallVector<unsigned, 4> Indices;
8552   bool AteExtraComma;
8553   if (parseTypeAndValue(Val0, Loc0, PFS) ||
8554       parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8555       parseTypeAndValue(Val1, Loc1, PFS) ||
8556       parseIndexList(Indices, AteExtraComma))
8557     return true;
8558 
8559   if (!Val0->getType()->isAggregateType())
8560     return error(Loc0, "insertvalue operand must be aggregate type");
8561 
8562   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8563   if (!IndexedType)
8564     return error(Loc0, "invalid indices for insertvalue");
8565   if (IndexedType != Val1->getType())
8566     return error(Loc1, "insertvalue operand and field disagree in type: '" +
8567                            getTypeString(Val1->getType()) + "' instead of '" +
8568                            getTypeString(IndexedType) + "'");
8569   Inst = InsertValueInst::Create(Val0, Val1, Indices);
8570   return AteExtraComma ? InstExtraComma : InstNormal;
8571 }
8572 
8573 //===----------------------------------------------------------------------===//
8574 // Embedded metadata.
8575 //===----------------------------------------------------------------------===//
8576 
8577 /// parseMDNodeVector
8578 ///   ::= { Element (',' Element)* }
8579 /// Element
8580 ///   ::= 'null' | Metadata
8581 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8582   if (parseToken(lltok::lbrace, "expected '{' here"))
8583     return true;
8584 
8585   // Check for an empty list.
8586   if (EatIfPresent(lltok::rbrace))
8587     return false;
8588 
8589   do {
8590     if (EatIfPresent(lltok::kw_null)) {
8591       Elts.push_back(nullptr);
8592       continue;
8593     }
8594 
8595     Metadata *MD;
8596     if (parseMetadata(MD, nullptr))
8597       return true;
8598     Elts.push_back(MD);
8599   } while (EatIfPresent(lltok::comma));
8600 
8601   return parseToken(lltok::rbrace, "expected end of metadata node");
8602 }
8603 
8604 //===----------------------------------------------------------------------===//
8605 // Use-list order directives.
8606 //===----------------------------------------------------------------------===//
8607 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
8608                                 SMLoc Loc) {
8609   if (V->use_empty())
8610     return error(Loc, "value has no uses");
8611 
8612   unsigned NumUses = 0;
8613   SmallDenseMap<const Use *, unsigned, 16> Order;
8614   for (const Use &U : V->uses()) {
8615     if (++NumUses > Indexes.size())
8616       break;
8617     Order[&U] = Indexes[NumUses - 1];
8618   }
8619   if (NumUses < 2)
8620     return error(Loc, "value only has one use");
8621   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
8622     return error(Loc,
8623                  "wrong number of indexes, expected " + Twine(V->getNumUses()));
8624 
8625   V->sortUseList([&](const Use &L, const Use &R) {
8626     return Order.lookup(&L) < Order.lookup(&R);
8627   });
8628   return false;
8629 }
8630 
8631 /// parseUseListOrderIndexes
8632 ///   ::= '{' uint32 (',' uint32)+ '}'
8633 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8634   SMLoc Loc = Lex.getLoc();
8635   if (parseToken(lltok::lbrace, "expected '{' here"))
8636     return true;
8637   if (Lex.getKind() == lltok::rbrace)
8638     return tokError("expected non-empty list of uselistorder indexes");
8639 
8640   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
8641   // indexes should be distinct numbers in the range [0, size-1], and should
8642   // not be in order.
8643   unsigned Offset = 0;
8644   unsigned Max = 0;
8645   bool IsOrdered = true;
8646   assert(Indexes.empty() && "Expected empty order vector");
8647   do {
8648     unsigned Index;
8649     if (parseUInt32(Index))
8650       return true;
8651 
8652     // Update consistency checks.
8653     Offset += Index - Indexes.size();
8654     Max = std::max(Max, Index);
8655     IsOrdered &= Index == Indexes.size();
8656 
8657     Indexes.push_back(Index);
8658   } while (EatIfPresent(lltok::comma));
8659 
8660   if (parseToken(lltok::rbrace, "expected '}' here"))
8661     return true;
8662 
8663   if (Indexes.size() < 2)
8664     return error(Loc, "expected >= 2 uselistorder indexes");
8665   if (Offset != 0 || Max >= Indexes.size())
8666     return error(Loc,
8667                  "expected distinct uselistorder indexes in range [0, size)");
8668   if (IsOrdered)
8669     return error(Loc, "expected uselistorder indexes to change the order");
8670 
8671   return false;
8672 }
8673 
8674 /// parseUseListOrder
8675 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8676 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8677   SMLoc Loc = Lex.getLoc();
8678   if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
8679     return true;
8680 
8681   Value *V;
8682   SmallVector<unsigned, 16> Indexes;
8683   if (parseTypeAndValue(V, PFS) ||
8684       parseToken(lltok::comma, "expected comma in uselistorder directive") ||
8685       parseUseListOrderIndexes(Indexes))
8686     return true;
8687 
8688   return sortUseListOrder(V, Indexes, Loc);
8689 }
8690 
8691 /// parseUseListOrderBB
8692 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8693 bool LLParser::parseUseListOrderBB() {
8694   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
8695   SMLoc Loc = Lex.getLoc();
8696   Lex.Lex();
8697 
8698   ValID Fn, Label;
8699   SmallVector<unsigned, 16> Indexes;
8700   if (parseValID(Fn, /*PFS=*/nullptr) ||
8701       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8702       parseValID(Label, /*PFS=*/nullptr) ||
8703       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8704       parseUseListOrderIndexes(Indexes))
8705     return true;
8706 
8707   // Check the function.
8708   GlobalValue *GV;
8709   if (Fn.Kind == ValID::t_GlobalName)
8710     GV = M->getNamedValue(Fn.StrVal);
8711   else if (Fn.Kind == ValID::t_GlobalID)
8712     GV = NumberedVals.get(Fn.UIntVal);
8713   else
8714     return error(Fn.Loc, "expected function name in uselistorder_bb");
8715   if (!GV)
8716     return error(Fn.Loc,
8717                  "invalid function forward reference in uselistorder_bb");
8718   auto *F = dyn_cast<Function>(GV);
8719   if (!F)
8720     return error(Fn.Loc, "expected function name in uselistorder_bb");
8721   if (F->isDeclaration())
8722     return error(Fn.Loc, "invalid declaration in uselistorder_bb");
8723 
8724   // Check the basic block.
8725   if (Label.Kind == ValID::t_LocalID)
8726     return error(Label.Loc, "invalid numeric label in uselistorder_bb");
8727   if (Label.Kind != ValID::t_LocalName)
8728     return error(Label.Loc, "expected basic block name in uselistorder_bb");
8729   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
8730   if (!V)
8731     return error(Label.Loc, "invalid basic block in uselistorder_bb");
8732   if (!isa<BasicBlock>(V))
8733     return error(Label.Loc, "expected basic block in uselistorder_bb");
8734 
8735   return sortUseListOrder(V, Indexes, Loc);
8736 }
8737 
8738 /// ModuleEntry
8739 ///   ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8740 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8741 bool LLParser::parseModuleEntry(unsigned ID) {
8742   assert(Lex.getKind() == lltok::kw_module);
8743   Lex.Lex();
8744 
8745   std::string Path;
8746   if (parseToken(lltok::colon, "expected ':' here") ||
8747       parseToken(lltok::lparen, "expected '(' here") ||
8748       parseToken(lltok::kw_path, "expected 'path' here") ||
8749       parseToken(lltok::colon, "expected ':' here") ||
8750       parseStringConstant(Path) ||
8751       parseToken(lltok::comma, "expected ',' here") ||
8752       parseToken(lltok::kw_hash, "expected 'hash' here") ||
8753       parseToken(lltok::colon, "expected ':' here") ||
8754       parseToken(lltok::lparen, "expected '(' here"))
8755     return true;
8756 
8757   ModuleHash Hash;
8758   if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8759       parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8760       parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8761       parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8762       parseUInt32(Hash[4]))
8763     return true;
8764 
8765   if (parseToken(lltok::rparen, "expected ')' here") ||
8766       parseToken(lltok::rparen, "expected ')' here"))
8767     return true;
8768 
8769   auto ModuleEntry = Index->addModule(Path, Hash);
8770   ModuleIdMap[ID] = ModuleEntry->first();
8771 
8772   return false;
8773 }
8774 
8775 /// TypeIdEntry
8776 ///   ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8777 bool LLParser::parseTypeIdEntry(unsigned ID) {
8778   assert(Lex.getKind() == lltok::kw_typeid);
8779   Lex.Lex();
8780 
8781   std::string Name;
8782   if (parseToken(lltok::colon, "expected ':' here") ||
8783       parseToken(lltok::lparen, "expected '(' here") ||
8784       parseToken(lltok::kw_name, "expected 'name' here") ||
8785       parseToken(lltok::colon, "expected ':' here") ||
8786       parseStringConstant(Name))
8787     return true;
8788 
8789   TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8790   if (parseToken(lltok::comma, "expected ',' here") ||
8791       parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8792     return true;
8793 
8794   // Check if this ID was forward referenced, and if so, update the
8795   // corresponding GUIDs.
8796   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8797   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8798     for (auto TIDRef : FwdRefTIDs->second) {
8799       assert(!*TIDRef.first &&
8800              "Forward referenced type id GUID expected to be 0");
8801       *TIDRef.first = GlobalValue::getGUID(Name);
8802     }
8803     ForwardRefTypeIds.erase(FwdRefTIDs);
8804   }
8805 
8806   return false;
8807 }
8808 
8809 /// TypeIdSummary
8810 ///   ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8811 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8812   if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8813       parseToken(lltok::colon, "expected ':' here") ||
8814       parseToken(lltok::lparen, "expected '(' here") ||
8815       parseTypeTestResolution(TIS.TTRes))
8816     return true;
8817 
8818   if (EatIfPresent(lltok::comma)) {
8819     // Expect optional wpdResolutions field
8820     if (parseOptionalWpdResolutions(TIS.WPDRes))
8821       return true;
8822   }
8823 
8824   if (parseToken(lltok::rparen, "expected ')' here"))
8825     return true;
8826 
8827   return false;
8828 }
8829 
8830 static ValueInfo EmptyVI =
8831     ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8832 
8833 /// TypeIdCompatibleVtableEntry
8834 ///   ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8835 ///   TypeIdCompatibleVtableInfo
8836 ///   ')'
8837 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8838   assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
8839   Lex.Lex();
8840 
8841   std::string Name;
8842   if (parseToken(lltok::colon, "expected ':' here") ||
8843       parseToken(lltok::lparen, "expected '(' here") ||
8844       parseToken(lltok::kw_name, "expected 'name' here") ||
8845       parseToken(lltok::colon, "expected ':' here") ||
8846       parseStringConstant(Name))
8847     return true;
8848 
8849   TypeIdCompatibleVtableInfo &TI =
8850       Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8851   if (parseToken(lltok::comma, "expected ',' here") ||
8852       parseToken(lltok::kw_summary, "expected 'summary' here") ||
8853       parseToken(lltok::colon, "expected ':' here") ||
8854       parseToken(lltok::lparen, "expected '(' here"))
8855     return true;
8856 
8857   IdToIndexMapType IdToIndexMap;
8858   // parse each call edge
8859   do {
8860     uint64_t Offset;
8861     if (parseToken(lltok::lparen, "expected '(' here") ||
8862         parseToken(lltok::kw_offset, "expected 'offset' here") ||
8863         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8864         parseToken(lltok::comma, "expected ',' here"))
8865       return true;
8866 
8867     LocTy Loc = Lex.getLoc();
8868     unsigned GVId;
8869     ValueInfo VI;
8870     if (parseGVReference(VI, GVId))
8871       return true;
8872 
8873     // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8874     // forward reference. We will save the location of the ValueInfo needing an
8875     // update, but can only do so once the std::vector is finalized.
8876     if (VI == EmptyVI)
8877       IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8878     TI.push_back({Offset, VI});
8879 
8880     if (parseToken(lltok::rparen, "expected ')' in call"))
8881       return true;
8882   } while (EatIfPresent(lltok::comma));
8883 
8884   // Now that the TI vector is finalized, it is safe to save the locations
8885   // of any forward GV references that need updating later.
8886   for (auto I : IdToIndexMap) {
8887     auto &Infos = ForwardRefValueInfos[I.first];
8888     for (auto P : I.second) {
8889       assert(TI[P.first].VTableVI == EmptyVI &&
8890              "Forward referenced ValueInfo expected to be empty");
8891       Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8892     }
8893   }
8894 
8895   if (parseToken(lltok::rparen, "expected ')' here") ||
8896       parseToken(lltok::rparen, "expected ')' here"))
8897     return true;
8898 
8899   // Check if this ID was forward referenced, and if so, update the
8900   // corresponding GUIDs.
8901   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8902   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8903     for (auto TIDRef : FwdRefTIDs->second) {
8904       assert(!*TIDRef.first &&
8905              "Forward referenced type id GUID expected to be 0");
8906       *TIDRef.first = GlobalValue::getGUID(Name);
8907     }
8908     ForwardRefTypeIds.erase(FwdRefTIDs);
8909   }
8910 
8911   return false;
8912 }
8913 
8914 /// TypeTestResolution
8915 ///   ::= 'typeTestRes' ':' '(' 'kind' ':'
8916 ///         ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8917 ///         'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8918 ///         [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8919 ///         [',' 'inlinesBits' ':' UInt64]? ')'
8920 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8921   if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8922       parseToken(lltok::colon, "expected ':' here") ||
8923       parseToken(lltok::lparen, "expected '(' here") ||
8924       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8925       parseToken(lltok::colon, "expected ':' here"))
8926     return true;
8927 
8928   switch (Lex.getKind()) {
8929   case lltok::kw_unknown:
8930     TTRes.TheKind = TypeTestResolution::Unknown;
8931     break;
8932   case lltok::kw_unsat:
8933     TTRes.TheKind = TypeTestResolution::Unsat;
8934     break;
8935   case lltok::kw_byteArray:
8936     TTRes.TheKind = TypeTestResolution::ByteArray;
8937     break;
8938   case lltok::kw_inline:
8939     TTRes.TheKind = TypeTestResolution::Inline;
8940     break;
8941   case lltok::kw_single:
8942     TTRes.TheKind = TypeTestResolution::Single;
8943     break;
8944   case lltok::kw_allOnes:
8945     TTRes.TheKind = TypeTestResolution::AllOnes;
8946     break;
8947   default:
8948     return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8949   }
8950   Lex.Lex();
8951 
8952   if (parseToken(lltok::comma, "expected ',' here") ||
8953       parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8954       parseToken(lltok::colon, "expected ':' here") ||
8955       parseUInt32(TTRes.SizeM1BitWidth))
8956     return true;
8957 
8958   // parse optional fields
8959   while (EatIfPresent(lltok::comma)) {
8960     switch (Lex.getKind()) {
8961     case lltok::kw_alignLog2:
8962       Lex.Lex();
8963       if (parseToken(lltok::colon, "expected ':'") ||
8964           parseUInt64(TTRes.AlignLog2))
8965         return true;
8966       break;
8967     case lltok::kw_sizeM1:
8968       Lex.Lex();
8969       if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8970         return true;
8971       break;
8972     case lltok::kw_bitMask: {
8973       unsigned Val;
8974       Lex.Lex();
8975       if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8976         return true;
8977       assert(Val <= 0xff);
8978       TTRes.BitMask = (uint8_t)Val;
8979       break;
8980     }
8981     case lltok::kw_inlineBits:
8982       Lex.Lex();
8983       if (parseToken(lltok::colon, "expected ':'") ||
8984           parseUInt64(TTRes.InlineBits))
8985         return true;
8986       break;
8987     default:
8988       return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8989     }
8990   }
8991 
8992   if (parseToken(lltok::rparen, "expected ')' here"))
8993     return true;
8994 
8995   return false;
8996 }
8997 
8998 /// OptionalWpdResolutions
8999 ///   ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9000 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9001 bool LLParser::parseOptionalWpdResolutions(
9002     std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9003   if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9004       parseToken(lltok::colon, "expected ':' here") ||
9005       parseToken(lltok::lparen, "expected '(' here"))
9006     return true;
9007 
9008   do {
9009     uint64_t Offset;
9010     WholeProgramDevirtResolution WPDRes;
9011     if (parseToken(lltok::lparen, "expected '(' here") ||
9012         parseToken(lltok::kw_offset, "expected 'offset' here") ||
9013         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9014         parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9015         parseToken(lltok::rparen, "expected ')' here"))
9016       return true;
9017     WPDResMap[Offset] = WPDRes;
9018   } while (EatIfPresent(lltok::comma));
9019 
9020   if (parseToken(lltok::rparen, "expected ')' here"))
9021     return true;
9022 
9023   return false;
9024 }
9025 
9026 /// WpdRes
9027 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9028 ///         [',' OptionalResByArg]? ')'
9029 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9030 ///         ',' 'singleImplName' ':' STRINGCONSTANT ','
9031 ///         [',' OptionalResByArg]? ')'
9032 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9033 ///         [',' OptionalResByArg]? ')'
9034 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9035   if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9036       parseToken(lltok::colon, "expected ':' here") ||
9037       parseToken(lltok::lparen, "expected '(' here") ||
9038       parseToken(lltok::kw_kind, "expected 'kind' here") ||
9039       parseToken(lltok::colon, "expected ':' here"))
9040     return true;
9041 
9042   switch (Lex.getKind()) {
9043   case lltok::kw_indir:
9044     WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
9045     break;
9046   case lltok::kw_singleImpl:
9047     WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
9048     break;
9049   case lltok::kw_branchFunnel:
9050     WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
9051     break;
9052   default:
9053     return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9054   }
9055   Lex.Lex();
9056 
9057   // parse optional fields
9058   while (EatIfPresent(lltok::comma)) {
9059     switch (Lex.getKind()) {
9060     case lltok::kw_singleImplName:
9061       Lex.Lex();
9062       if (parseToken(lltok::colon, "expected ':' here") ||
9063           parseStringConstant(WPDRes.SingleImplName))
9064         return true;
9065       break;
9066     case lltok::kw_resByArg:
9067       if (parseOptionalResByArg(WPDRes.ResByArg))
9068         return true;
9069       break;
9070     default:
9071       return error(Lex.getLoc(),
9072                    "expected optional WholeProgramDevirtResolution field");
9073     }
9074   }
9075 
9076   if (parseToken(lltok::rparen, "expected ')' here"))
9077     return true;
9078 
9079   return false;
9080 }
9081 
9082 /// OptionalResByArg
9083 ///   ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9084 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9085 ///                ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9086 ///                  'virtualConstProp' )
9087 ///                [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9088 ///                [',' 'bit' ':' UInt32]? ')'
9089 bool LLParser::parseOptionalResByArg(
9090     std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9091         &ResByArg) {
9092   if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9093       parseToken(lltok::colon, "expected ':' here") ||
9094       parseToken(lltok::lparen, "expected '(' here"))
9095     return true;
9096 
9097   do {
9098     std::vector<uint64_t> Args;
9099     if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9100         parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9101         parseToken(lltok::colon, "expected ':' here") ||
9102         parseToken(lltok::lparen, "expected '(' here") ||
9103         parseToken(lltok::kw_kind, "expected 'kind' here") ||
9104         parseToken(lltok::colon, "expected ':' here"))
9105       return true;
9106 
9107     WholeProgramDevirtResolution::ByArg ByArg;
9108     switch (Lex.getKind()) {
9109     case lltok::kw_indir:
9110       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
9111       break;
9112     case lltok::kw_uniformRetVal:
9113       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
9114       break;
9115     case lltok::kw_uniqueRetVal:
9116       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
9117       break;
9118     case lltok::kw_virtualConstProp:
9119       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
9120       break;
9121     default:
9122       return error(Lex.getLoc(),
9123                    "unexpected WholeProgramDevirtResolution::ByArg kind");
9124     }
9125     Lex.Lex();
9126 
9127     // parse optional fields
9128     while (EatIfPresent(lltok::comma)) {
9129       switch (Lex.getKind()) {
9130       case lltok::kw_info:
9131         Lex.Lex();
9132         if (parseToken(lltok::colon, "expected ':' here") ||
9133             parseUInt64(ByArg.Info))
9134           return true;
9135         break;
9136       case lltok::kw_byte:
9137         Lex.Lex();
9138         if (parseToken(lltok::colon, "expected ':' here") ||
9139             parseUInt32(ByArg.Byte))
9140           return true;
9141         break;
9142       case lltok::kw_bit:
9143         Lex.Lex();
9144         if (parseToken(lltok::colon, "expected ':' here") ||
9145             parseUInt32(ByArg.Bit))
9146           return true;
9147         break;
9148       default:
9149         return error(Lex.getLoc(),
9150                      "expected optional whole program devirt field");
9151       }
9152     }
9153 
9154     if (parseToken(lltok::rparen, "expected ')' here"))
9155       return true;
9156 
9157     ResByArg[Args] = ByArg;
9158   } while (EatIfPresent(lltok::comma));
9159 
9160   if (parseToken(lltok::rparen, "expected ')' here"))
9161     return true;
9162 
9163   return false;
9164 }
9165 
9166 /// OptionalResByArg
9167 ///   ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9168 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9169   if (parseToken(lltok::kw_args, "expected 'args' here") ||
9170       parseToken(lltok::colon, "expected ':' here") ||
9171       parseToken(lltok::lparen, "expected '(' here"))
9172     return true;
9173 
9174   do {
9175     uint64_t Val;
9176     if (parseUInt64(Val))
9177       return true;
9178     Args.push_back(Val);
9179   } while (EatIfPresent(lltok::comma));
9180 
9181   if (parseToken(lltok::rparen, "expected ')' here"))
9182     return true;
9183 
9184   return false;
9185 }
9186 
9187 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9188 
9189 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9190   bool ReadOnly = Fwd->isReadOnly();
9191   bool WriteOnly = Fwd->isWriteOnly();
9192   assert(!(ReadOnly && WriteOnly));
9193   *Fwd = Resolved;
9194   if (ReadOnly)
9195     Fwd->setReadOnly();
9196   if (WriteOnly)
9197     Fwd->setWriteOnly();
9198 }
9199 
9200 /// Stores the given Name/GUID and associated summary into the Index.
9201 /// Also updates any forward references to the associated entry ID.
9202 bool LLParser::addGlobalValueToIndex(
9203     std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9204     unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9205   // First create the ValueInfo utilizing the Name or GUID.
9206   ValueInfo VI;
9207   if (GUID != 0) {
9208     assert(Name.empty());
9209     VI = Index->getOrInsertValueInfo(GUID);
9210   } else {
9211     assert(!Name.empty());
9212     if (M) {
9213       auto *GV = M->getNamedValue(Name);
9214       if (!GV)
9215         return error(Loc, "Reference to undefined global \"" + Name + "\"");
9216 
9217       VI = Index->getOrInsertValueInfo(GV);
9218     } else {
9219       assert(
9220           (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9221           "Need a source_filename to compute GUID for local");
9222       GUID = GlobalValue::getGUID(
9223           GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9224       VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9225     }
9226   }
9227 
9228   // Resolve forward references from calls/refs
9229   auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9230   if (FwdRefVIs != ForwardRefValueInfos.end()) {
9231     for (auto VIRef : FwdRefVIs->second) {
9232       assert(VIRef.first->getRef() == FwdVIRef &&
9233              "Forward referenced ValueInfo expected to be empty");
9234       resolveFwdRef(VIRef.first, VI);
9235     }
9236     ForwardRefValueInfos.erase(FwdRefVIs);
9237   }
9238 
9239   // Resolve forward references from aliases
9240   auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9241   if (FwdRefAliasees != ForwardRefAliasees.end()) {
9242     for (auto AliaseeRef : FwdRefAliasees->second) {
9243       assert(!AliaseeRef.first->hasAliasee() &&
9244              "Forward referencing alias already has aliasee");
9245       assert(Summary && "Aliasee must be a definition");
9246       AliaseeRef.first->setAliasee(VI, Summary.get());
9247     }
9248     ForwardRefAliasees.erase(FwdRefAliasees);
9249   }
9250 
9251   // Add the summary if one was provided.
9252   if (Summary)
9253     Index->addGlobalValueSummary(VI, std::move(Summary));
9254 
9255   // Save the associated ValueInfo for use in later references by ID.
9256   if (ID == NumberedValueInfos.size())
9257     NumberedValueInfos.push_back(VI);
9258   else {
9259     // Handle non-continuous numbers (to make test simplification easier).
9260     if (ID > NumberedValueInfos.size())
9261       NumberedValueInfos.resize(ID + 1);
9262     NumberedValueInfos[ID] = VI;
9263   }
9264 
9265   return false;
9266 }
9267 
9268 /// parseSummaryIndexFlags
9269 ///   ::= 'flags' ':' UInt64
9270 bool LLParser::parseSummaryIndexFlags() {
9271   assert(Lex.getKind() == lltok::kw_flags);
9272   Lex.Lex();
9273 
9274   if (parseToken(lltok::colon, "expected ':' here"))
9275     return true;
9276   uint64_t Flags;
9277   if (parseUInt64(Flags))
9278     return true;
9279   if (Index)
9280     Index->setFlags(Flags);
9281   return false;
9282 }
9283 
9284 /// parseBlockCount
9285 ///   ::= 'blockcount' ':' UInt64
9286 bool LLParser::parseBlockCount() {
9287   assert(Lex.getKind() == lltok::kw_blockcount);
9288   Lex.Lex();
9289 
9290   if (parseToken(lltok::colon, "expected ':' here"))
9291     return true;
9292   uint64_t BlockCount;
9293   if (parseUInt64(BlockCount))
9294     return true;
9295   if (Index)
9296     Index->setBlockCount(BlockCount);
9297   return false;
9298 }
9299 
9300 /// parseGVEntry
9301 ///   ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9302 ///         [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9303 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9304 bool LLParser::parseGVEntry(unsigned ID) {
9305   assert(Lex.getKind() == lltok::kw_gv);
9306   Lex.Lex();
9307 
9308   if (parseToken(lltok::colon, "expected ':' here") ||
9309       parseToken(lltok::lparen, "expected '(' here"))
9310     return true;
9311 
9312   LocTy Loc = Lex.getLoc();
9313   std::string Name;
9314   GlobalValue::GUID GUID = 0;
9315   switch (Lex.getKind()) {
9316   case lltok::kw_name:
9317     Lex.Lex();
9318     if (parseToken(lltok::colon, "expected ':' here") ||
9319         parseStringConstant(Name))
9320       return true;
9321     // Can't create GUID/ValueInfo until we have the linkage.
9322     break;
9323   case lltok::kw_guid:
9324     Lex.Lex();
9325     if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9326       return true;
9327     break;
9328   default:
9329     return error(Lex.getLoc(), "expected name or guid tag");
9330   }
9331 
9332   if (!EatIfPresent(lltok::comma)) {
9333     // No summaries. Wrap up.
9334     if (parseToken(lltok::rparen, "expected ')' here"))
9335       return true;
9336     // This was created for a call to an external or indirect target.
9337     // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9338     // created for indirect calls with VP. A Name with no GUID came from
9339     // an external definition. We pass ExternalLinkage since that is only
9340     // used when the GUID must be computed from Name, and in that case
9341     // the symbol must have external linkage.
9342     return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9343                                  nullptr, Loc);
9344   }
9345 
9346   // Have a list of summaries
9347   if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9348       parseToken(lltok::colon, "expected ':' here") ||
9349       parseToken(lltok::lparen, "expected '(' here"))
9350     return true;
9351   do {
9352     switch (Lex.getKind()) {
9353     case lltok::kw_function:
9354       if (parseFunctionSummary(Name, GUID, ID))
9355         return true;
9356       break;
9357     case lltok::kw_variable:
9358       if (parseVariableSummary(Name, GUID, ID))
9359         return true;
9360       break;
9361     case lltok::kw_alias:
9362       if (parseAliasSummary(Name, GUID, ID))
9363         return true;
9364       break;
9365     default:
9366       return error(Lex.getLoc(), "expected summary type");
9367     }
9368   } while (EatIfPresent(lltok::comma));
9369 
9370   if (parseToken(lltok::rparen, "expected ')' here") ||
9371       parseToken(lltok::rparen, "expected ')' here"))
9372     return true;
9373 
9374   return false;
9375 }
9376 
9377 /// FunctionSummary
9378 ///   ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9379 ///         ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9380 ///         [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9381 ///         [',' OptionalRefs]? ')'
9382 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9383                                     unsigned ID) {
9384   LocTy Loc = Lex.getLoc();
9385   assert(Lex.getKind() == lltok::kw_function);
9386   Lex.Lex();
9387 
9388   StringRef ModulePath;
9389   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9390       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
9391       /*NotEligibleToImport=*/false,
9392       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9393       GlobalValueSummary::Definition);
9394   unsigned InstCount;
9395   SmallVector<FunctionSummary::EdgeTy, 0> Calls;
9396   FunctionSummary::TypeIdInfo TypeIdInfo;
9397   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9398   SmallVector<ValueInfo, 0> Refs;
9399   std::vector<CallsiteInfo> Callsites;
9400   std::vector<AllocInfo> Allocs;
9401   // Default is all-zeros (conservative values).
9402   FunctionSummary::FFlags FFlags = {};
9403   if (parseToken(lltok::colon, "expected ':' here") ||
9404       parseToken(lltok::lparen, "expected '(' here") ||
9405       parseModuleReference(ModulePath) ||
9406       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9407       parseToken(lltok::comma, "expected ',' here") ||
9408       parseToken(lltok::kw_insts, "expected 'insts' here") ||
9409       parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9410     return true;
9411 
9412   // parse optional fields
9413   while (EatIfPresent(lltok::comma)) {
9414     switch (Lex.getKind()) {
9415     case lltok::kw_funcFlags:
9416       if (parseOptionalFFlags(FFlags))
9417         return true;
9418       break;
9419     case lltok::kw_calls:
9420       if (parseOptionalCalls(Calls))
9421         return true;
9422       break;
9423     case lltok::kw_typeIdInfo:
9424       if (parseOptionalTypeIdInfo(TypeIdInfo))
9425         return true;
9426       break;
9427     case lltok::kw_refs:
9428       if (parseOptionalRefs(Refs))
9429         return true;
9430       break;
9431     case lltok::kw_params:
9432       if (parseOptionalParamAccesses(ParamAccesses))
9433         return true;
9434       break;
9435     case lltok::kw_allocs:
9436       if (parseOptionalAllocs(Allocs))
9437         return true;
9438       break;
9439     case lltok::kw_callsites:
9440       if (parseOptionalCallsites(Callsites))
9441         return true;
9442       break;
9443     default:
9444       return error(Lex.getLoc(), "expected optional function summary field");
9445     }
9446   }
9447 
9448   if (parseToken(lltok::rparen, "expected ')' here"))
9449     return true;
9450 
9451   auto FS = std::make_unique<FunctionSummary>(
9452       GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9453       std::move(TypeIdInfo.TypeTests),
9454       std::move(TypeIdInfo.TypeTestAssumeVCalls),
9455       std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9456       std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9457       std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9458       std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9459 
9460   FS->setModulePath(ModulePath);
9461 
9462   return addGlobalValueToIndex(Name, GUID,
9463                                (GlobalValue::LinkageTypes)GVFlags.Linkage, ID,
9464                                std::move(FS), Loc);
9465 }
9466 
9467 /// VariableSummary
9468 ///   ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9469 ///         [',' OptionalRefs]? ')'
9470 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9471                                     unsigned ID) {
9472   LocTy Loc = Lex.getLoc();
9473   assert(Lex.getKind() == lltok::kw_variable);
9474   Lex.Lex();
9475 
9476   StringRef ModulePath;
9477   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9478       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
9479       /*NotEligibleToImport=*/false,
9480       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9481       GlobalValueSummary::Definition);
9482   GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9483                                         /* WriteOnly */ false,
9484                                         /* Constant */ false,
9485                                         GlobalObject::VCallVisibilityPublic);
9486   SmallVector<ValueInfo, 0> Refs;
9487   VTableFuncList VTableFuncs;
9488   if (parseToken(lltok::colon, "expected ':' here") ||
9489       parseToken(lltok::lparen, "expected '(' here") ||
9490       parseModuleReference(ModulePath) ||
9491       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9492       parseToken(lltok::comma, "expected ',' here") ||
9493       parseGVarFlags(GVarFlags))
9494     return true;
9495 
9496   // parse optional fields
9497   while (EatIfPresent(lltok::comma)) {
9498     switch (Lex.getKind()) {
9499     case lltok::kw_vTableFuncs:
9500       if (parseOptionalVTableFuncs(VTableFuncs))
9501         return true;
9502       break;
9503     case lltok::kw_refs:
9504       if (parseOptionalRefs(Refs))
9505         return true;
9506       break;
9507     default:
9508       return error(Lex.getLoc(), "expected optional variable summary field");
9509     }
9510   }
9511 
9512   if (parseToken(lltok::rparen, "expected ')' here"))
9513     return true;
9514 
9515   auto GS =
9516       std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9517 
9518   GS->setModulePath(ModulePath);
9519   GS->setVTableFuncs(std::move(VTableFuncs));
9520 
9521   return addGlobalValueToIndex(Name, GUID,
9522                                (GlobalValue::LinkageTypes)GVFlags.Linkage, ID,
9523                                std::move(GS), Loc);
9524 }
9525 
9526 /// AliasSummary
9527 ///   ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9528 ///         'aliasee' ':' GVReference ')'
9529 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9530                                  unsigned ID) {
9531   assert(Lex.getKind() == lltok::kw_alias);
9532   LocTy Loc = Lex.getLoc();
9533   Lex.Lex();
9534 
9535   StringRef ModulePath;
9536   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9537       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
9538       /*NotEligibleToImport=*/false,
9539       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9540       GlobalValueSummary::Definition);
9541   if (parseToken(lltok::colon, "expected ':' here") ||
9542       parseToken(lltok::lparen, "expected '(' here") ||
9543       parseModuleReference(ModulePath) ||
9544       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9545       parseToken(lltok::comma, "expected ',' here") ||
9546       parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9547       parseToken(lltok::colon, "expected ':' here"))
9548     return true;
9549 
9550   ValueInfo AliaseeVI;
9551   unsigned GVId;
9552   if (parseGVReference(AliaseeVI, GVId))
9553     return true;
9554 
9555   if (parseToken(lltok::rparen, "expected ')' here"))
9556     return true;
9557 
9558   auto AS = std::make_unique<AliasSummary>(GVFlags);
9559 
9560   AS->setModulePath(ModulePath);
9561 
9562   // Record forward reference if the aliasee is not parsed yet.
9563   if (AliaseeVI.getRef() == FwdVIRef) {
9564     ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9565   } else {
9566     auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9567     assert(Summary && "Aliasee must be a definition");
9568     AS->setAliasee(AliaseeVI, Summary);
9569   }
9570 
9571   return addGlobalValueToIndex(Name, GUID,
9572                                (GlobalValue::LinkageTypes)GVFlags.Linkage, ID,
9573                                std::move(AS), Loc);
9574 }
9575 
9576 /// Flag
9577 ///   ::= [0|1]
9578 bool LLParser::parseFlag(unsigned &Val) {
9579   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9580     return tokError("expected integer");
9581   Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9582   Lex.Lex();
9583   return false;
9584 }
9585 
9586 /// OptionalFFlags
9587 ///   := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9588 ///        [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9589 ///        [',' 'returnDoesNotAlias' ':' Flag]? ')'
9590 ///        [',' 'noInline' ':' Flag]? ')'
9591 ///        [',' 'alwaysInline' ':' Flag]? ')'
9592 ///        [',' 'noUnwind' ':' Flag]? ')'
9593 ///        [',' 'mayThrow' ':' Flag]? ')'
9594 ///        [',' 'hasUnknownCall' ':' Flag]? ')'
9595 ///        [',' 'mustBeUnreachable' ':' Flag]? ')'
9596 
9597 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9598   assert(Lex.getKind() == lltok::kw_funcFlags);
9599   Lex.Lex();
9600 
9601   if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
9602       parseToken(lltok::lparen, "expected '(' in funcFlags"))
9603     return true;
9604 
9605   do {
9606     unsigned Val = 0;
9607     switch (Lex.getKind()) {
9608     case lltok::kw_readNone:
9609       Lex.Lex();
9610       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9611         return true;
9612       FFlags.ReadNone = Val;
9613       break;
9614     case lltok::kw_readOnly:
9615       Lex.Lex();
9616       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9617         return true;
9618       FFlags.ReadOnly = Val;
9619       break;
9620     case lltok::kw_noRecurse:
9621       Lex.Lex();
9622       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9623         return true;
9624       FFlags.NoRecurse = Val;
9625       break;
9626     case lltok::kw_returnDoesNotAlias:
9627       Lex.Lex();
9628       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9629         return true;
9630       FFlags.ReturnDoesNotAlias = Val;
9631       break;
9632     case lltok::kw_noInline:
9633       Lex.Lex();
9634       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9635         return true;
9636       FFlags.NoInline = Val;
9637       break;
9638     case lltok::kw_alwaysInline:
9639       Lex.Lex();
9640       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9641         return true;
9642       FFlags.AlwaysInline = Val;
9643       break;
9644     case lltok::kw_noUnwind:
9645       Lex.Lex();
9646       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9647         return true;
9648       FFlags.NoUnwind = Val;
9649       break;
9650     case lltok::kw_mayThrow:
9651       Lex.Lex();
9652       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9653         return true;
9654       FFlags.MayThrow = Val;
9655       break;
9656     case lltok::kw_hasUnknownCall:
9657       Lex.Lex();
9658       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9659         return true;
9660       FFlags.HasUnknownCall = Val;
9661       break;
9662     case lltok::kw_mustBeUnreachable:
9663       Lex.Lex();
9664       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9665         return true;
9666       FFlags.MustBeUnreachable = Val;
9667       break;
9668     default:
9669       return error(Lex.getLoc(), "expected function flag type");
9670     }
9671   } while (EatIfPresent(lltok::comma));
9672 
9673   if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
9674     return true;
9675 
9676   return false;
9677 }
9678 
9679 /// OptionalCalls
9680 ///   := 'calls' ':' '(' Call [',' Call]* ')'
9681 /// Call ::= '(' 'callee' ':' GVReference
9682 ///            [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
9683 ///            [ ',' 'tail' ]? ')'
9684 bool LLParser::parseOptionalCalls(
9685     SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
9686   assert(Lex.getKind() == lltok::kw_calls);
9687   Lex.Lex();
9688 
9689   if (parseToken(lltok::colon, "expected ':' in calls") ||
9690       parseToken(lltok::lparen, "expected '(' in calls"))
9691     return true;
9692 
9693   IdToIndexMapType IdToIndexMap;
9694   // parse each call edge
9695   do {
9696     ValueInfo VI;
9697     if (parseToken(lltok::lparen, "expected '(' in call") ||
9698         parseToken(lltok::kw_callee, "expected 'callee' in call") ||
9699         parseToken(lltok::colon, "expected ':'"))
9700       return true;
9701 
9702     LocTy Loc = Lex.getLoc();
9703     unsigned GVId;
9704     if (parseGVReference(VI, GVId))
9705       return true;
9706 
9707     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
9708     unsigned RelBF = 0;
9709     unsigned HasTailCall = false;
9710 
9711     // parse optional fields
9712     while (EatIfPresent(lltok::comma)) {
9713       switch (Lex.getKind()) {
9714       case lltok::kw_hotness:
9715         Lex.Lex();
9716         if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
9717           return true;
9718         break;
9719       case lltok::kw_relbf:
9720         Lex.Lex();
9721         if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
9722           return true;
9723         break;
9724       case lltok::kw_tail:
9725         Lex.Lex();
9726         if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
9727           return true;
9728         break;
9729       default:
9730         return error(Lex.getLoc(), "expected hotness, relbf, or tail");
9731       }
9732     }
9733     if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
9734       return tokError("Expected only one of hotness or relbf");
9735     // Keep track of the Call array index needing a forward reference.
9736     // We will save the location of the ValueInfo needing an update, but
9737     // can only do so once the std::vector is finalized.
9738     if (VI.getRef() == FwdVIRef)
9739       IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9740     Calls.push_back(
9741         FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
9742 
9743     if (parseToken(lltok::rparen, "expected ')' in call"))
9744       return true;
9745   } while (EatIfPresent(lltok::comma));
9746 
9747   // Now that the Calls vector is finalized, it is safe to save the locations
9748   // of any forward GV references that need updating later.
9749   for (auto I : IdToIndexMap) {
9750     auto &Infos = ForwardRefValueInfos[I.first];
9751     for (auto P : I.second) {
9752       assert(Calls[P.first].first.getRef() == FwdVIRef &&
9753              "Forward referenced ValueInfo expected to be empty");
9754       Infos.emplace_back(&Calls[P.first].first, P.second);
9755     }
9756   }
9757 
9758   if (parseToken(lltok::rparen, "expected ')' in calls"))
9759     return true;
9760 
9761   return false;
9762 }
9763 
9764 /// Hotness
9765 ///   := ('unknown'|'cold'|'none'|'hot'|'critical')
9766 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
9767   switch (Lex.getKind()) {
9768   case lltok::kw_unknown:
9769     Hotness = CalleeInfo::HotnessType::Unknown;
9770     break;
9771   case lltok::kw_cold:
9772     Hotness = CalleeInfo::HotnessType::Cold;
9773     break;
9774   case lltok::kw_none:
9775     Hotness = CalleeInfo::HotnessType::None;
9776     break;
9777   case lltok::kw_hot:
9778     Hotness = CalleeInfo::HotnessType::Hot;
9779     break;
9780   case lltok::kw_critical:
9781     Hotness = CalleeInfo::HotnessType::Critical;
9782     break;
9783   default:
9784     return error(Lex.getLoc(), "invalid call edge hotness");
9785   }
9786   Lex.Lex();
9787   return false;
9788 }
9789 
9790 /// OptionalVTableFuncs
9791 ///   := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9792 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9793 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
9794   assert(Lex.getKind() == lltok::kw_vTableFuncs);
9795   Lex.Lex();
9796 
9797   if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
9798       parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9799     return true;
9800 
9801   IdToIndexMapType IdToIndexMap;
9802   // parse each virtual function pair
9803   do {
9804     ValueInfo VI;
9805     if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9806         parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9807         parseToken(lltok::colon, "expected ':'"))
9808       return true;
9809 
9810     LocTy Loc = Lex.getLoc();
9811     unsigned GVId;
9812     if (parseGVReference(VI, GVId))
9813       return true;
9814 
9815     uint64_t Offset;
9816     if (parseToken(lltok::comma, "expected comma") ||
9817         parseToken(lltok::kw_offset, "expected offset") ||
9818         parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9819       return true;
9820 
9821     // Keep track of the VTableFuncs array index needing a forward reference.
9822     // We will save the location of the ValueInfo needing an update, but
9823     // can only do so once the std::vector is finalized.
9824     if (VI == EmptyVI)
9825       IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9826     VTableFuncs.push_back({VI, Offset});
9827 
9828     if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9829       return true;
9830   } while (EatIfPresent(lltok::comma));
9831 
9832   // Now that the VTableFuncs vector is finalized, it is safe to save the
9833   // locations of any forward GV references that need updating later.
9834   for (auto I : IdToIndexMap) {
9835     auto &Infos = ForwardRefValueInfos[I.first];
9836     for (auto P : I.second) {
9837       assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9838              "Forward referenced ValueInfo expected to be empty");
9839       Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9840     }
9841   }
9842 
9843   if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9844     return true;
9845 
9846   return false;
9847 }
9848 
9849 /// ParamNo := 'param' ':' UInt64
9850 bool LLParser::parseParamNo(uint64_t &ParamNo) {
9851   if (parseToken(lltok::kw_param, "expected 'param' here") ||
9852       parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9853     return true;
9854   return false;
9855 }
9856 
9857 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9858 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9859   APSInt Lower;
9860   APSInt Upper;
9861   auto ParseAPSInt = [&](APSInt &Val) {
9862     if (Lex.getKind() != lltok::APSInt)
9863       return tokError("expected integer");
9864     Val = Lex.getAPSIntVal();
9865     Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9866     Val.setIsSigned(true);
9867     Lex.Lex();
9868     return false;
9869   };
9870   if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9871       parseToken(lltok::colon, "expected ':' here") ||
9872       parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9873       parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9874       parseToken(lltok::rsquare, "expected ']' here"))
9875     return true;
9876 
9877   ++Upper;
9878   Range =
9879       (Lower == Upper && !Lower.isMaxValue())
9880           ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9881           : ConstantRange(Lower, Upper);
9882 
9883   return false;
9884 }
9885 
9886 /// ParamAccessCall
9887 ///   := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9888 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9889                                     IdLocListType &IdLocList) {
9890   if (parseToken(lltok::lparen, "expected '(' here") ||
9891       parseToken(lltok::kw_callee, "expected 'callee' here") ||
9892       parseToken(lltok::colon, "expected ':' here"))
9893     return true;
9894 
9895   unsigned GVId;
9896   ValueInfo VI;
9897   LocTy Loc = Lex.getLoc();
9898   if (parseGVReference(VI, GVId))
9899     return true;
9900 
9901   Call.Callee = VI;
9902   IdLocList.emplace_back(GVId, Loc);
9903 
9904   if (parseToken(lltok::comma, "expected ',' here") ||
9905       parseParamNo(Call.ParamNo) ||
9906       parseToken(lltok::comma, "expected ',' here") ||
9907       parseParamAccessOffset(Call.Offsets))
9908     return true;
9909 
9910   if (parseToken(lltok::rparen, "expected ')' here"))
9911     return true;
9912 
9913   return false;
9914 }
9915 
9916 /// ParamAccess
9917 ///   := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9918 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9919 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
9920                                 IdLocListType &IdLocList) {
9921   if (parseToken(lltok::lparen, "expected '(' here") ||
9922       parseParamNo(Param.ParamNo) ||
9923       parseToken(lltok::comma, "expected ',' here") ||
9924       parseParamAccessOffset(Param.Use))
9925     return true;
9926 
9927   if (EatIfPresent(lltok::comma)) {
9928     if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
9929         parseToken(lltok::colon, "expected ':' here") ||
9930         parseToken(lltok::lparen, "expected '(' here"))
9931       return true;
9932     do {
9933       FunctionSummary::ParamAccess::Call Call;
9934       if (parseParamAccessCall(Call, IdLocList))
9935         return true;
9936       Param.Calls.push_back(Call);
9937     } while (EatIfPresent(lltok::comma));
9938 
9939     if (parseToken(lltok::rparen, "expected ')' here"))
9940       return true;
9941   }
9942 
9943   if (parseToken(lltok::rparen, "expected ')' here"))
9944     return true;
9945 
9946   return false;
9947 }
9948 
9949 /// OptionalParamAccesses
9950 ///   := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9951 bool LLParser::parseOptionalParamAccesses(
9952     std::vector<FunctionSummary::ParamAccess> &Params) {
9953   assert(Lex.getKind() == lltok::kw_params);
9954   Lex.Lex();
9955 
9956   if (parseToken(lltok::colon, "expected ':' here") ||
9957       parseToken(lltok::lparen, "expected '(' here"))
9958     return true;
9959 
9960   IdLocListType VContexts;
9961   size_t CallsNum = 0;
9962   do {
9963     FunctionSummary::ParamAccess ParamAccess;
9964     if (parseParamAccess(ParamAccess, VContexts))
9965       return true;
9966     CallsNum += ParamAccess.Calls.size();
9967     assert(VContexts.size() == CallsNum);
9968     (void)CallsNum;
9969     Params.emplace_back(std::move(ParamAccess));
9970   } while (EatIfPresent(lltok::comma));
9971 
9972   if (parseToken(lltok::rparen, "expected ')' here"))
9973     return true;
9974 
9975   // Now that the Params is finalized, it is safe to save the locations
9976   // of any forward GV references that need updating later.
9977   IdLocListType::const_iterator ItContext = VContexts.begin();
9978   for (auto &PA : Params) {
9979     for (auto &C : PA.Calls) {
9980       if (C.Callee.getRef() == FwdVIRef)
9981         ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9982                                                             ItContext->second);
9983       ++ItContext;
9984     }
9985   }
9986   assert(ItContext == VContexts.end());
9987 
9988   return false;
9989 }
9990 
9991 /// OptionalRefs
9992 ///   := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9993 bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
9994   assert(Lex.getKind() == lltok::kw_refs);
9995   Lex.Lex();
9996 
9997   if (parseToken(lltok::colon, "expected ':' in refs") ||
9998       parseToken(lltok::lparen, "expected '(' in refs"))
9999     return true;
10000 
10001   struct ValueContext {
10002     ValueInfo VI;
10003     unsigned GVId;
10004     LocTy Loc;
10005   };
10006   std::vector<ValueContext> VContexts;
10007   // parse each ref edge
10008   do {
10009     ValueContext VC;
10010     VC.Loc = Lex.getLoc();
10011     if (parseGVReference(VC.VI, VC.GVId))
10012       return true;
10013     VContexts.push_back(VC);
10014   } while (EatIfPresent(lltok::comma));
10015 
10016   // Sort value contexts so that ones with writeonly
10017   // and readonly ValueInfo  are at the end of VContexts vector.
10018   // See FunctionSummary::specialRefCounts()
10019   llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10020     return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10021   });
10022 
10023   IdToIndexMapType IdToIndexMap;
10024   for (auto &VC : VContexts) {
10025     // Keep track of the Refs array index needing a forward reference.
10026     // We will save the location of the ValueInfo needing an update, but
10027     // can only do so once the std::vector is finalized.
10028     if (VC.VI.getRef() == FwdVIRef)
10029       IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10030     Refs.push_back(VC.VI);
10031   }
10032 
10033   // Now that the Refs vector is finalized, it is safe to save the locations
10034   // of any forward GV references that need updating later.
10035   for (auto I : IdToIndexMap) {
10036     auto &Infos = ForwardRefValueInfos[I.first];
10037     for (auto P : I.second) {
10038       assert(Refs[P.first].getRef() == FwdVIRef &&
10039              "Forward referenced ValueInfo expected to be empty");
10040       Infos.emplace_back(&Refs[P.first], P.second);
10041     }
10042   }
10043 
10044   if (parseToken(lltok::rparen, "expected ')' in refs"))
10045     return true;
10046 
10047   return false;
10048 }
10049 
10050 /// OptionalTypeIdInfo
10051 ///   := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10052 ///         [',' TypeCheckedLoadVCalls]?  [',' TypeTestAssumeConstVCalls]?
10053 ///         [',' TypeCheckedLoadConstVCalls]? ')'
10054 bool LLParser::parseOptionalTypeIdInfo(
10055     FunctionSummary::TypeIdInfo &TypeIdInfo) {
10056   assert(Lex.getKind() == lltok::kw_typeIdInfo);
10057   Lex.Lex();
10058 
10059   if (parseToken(lltok::colon, "expected ':' here") ||
10060       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10061     return true;
10062 
10063   do {
10064     switch (Lex.getKind()) {
10065     case lltok::kw_typeTests:
10066       if (parseTypeTests(TypeIdInfo.TypeTests))
10067         return true;
10068       break;
10069     case lltok::kw_typeTestAssumeVCalls:
10070       if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10071                            TypeIdInfo.TypeTestAssumeVCalls))
10072         return true;
10073       break;
10074     case lltok::kw_typeCheckedLoadVCalls:
10075       if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10076                            TypeIdInfo.TypeCheckedLoadVCalls))
10077         return true;
10078       break;
10079     case lltok::kw_typeTestAssumeConstVCalls:
10080       if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10081                               TypeIdInfo.TypeTestAssumeConstVCalls))
10082         return true;
10083       break;
10084     case lltok::kw_typeCheckedLoadConstVCalls:
10085       if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10086                               TypeIdInfo.TypeCheckedLoadConstVCalls))
10087         return true;
10088       break;
10089     default:
10090       return error(Lex.getLoc(), "invalid typeIdInfo list type");
10091     }
10092   } while (EatIfPresent(lltok::comma));
10093 
10094   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10095     return true;
10096 
10097   return false;
10098 }
10099 
10100 /// TypeTests
10101 ///   ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10102 ///         [',' (SummaryID | UInt64)]* ')'
10103 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10104   assert(Lex.getKind() == lltok::kw_typeTests);
10105   Lex.Lex();
10106 
10107   if (parseToken(lltok::colon, "expected ':' here") ||
10108       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10109     return true;
10110 
10111   IdToIndexMapType IdToIndexMap;
10112   do {
10113     GlobalValue::GUID GUID = 0;
10114     if (Lex.getKind() == lltok::SummaryID) {
10115       unsigned ID = Lex.getUIntVal();
10116       LocTy Loc = Lex.getLoc();
10117       // Keep track of the TypeTests array index needing a forward reference.
10118       // We will save the location of the GUID needing an update, but
10119       // can only do so once the std::vector is finalized.
10120       IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10121       Lex.Lex();
10122     } else if (parseUInt64(GUID))
10123       return true;
10124     TypeTests.push_back(GUID);
10125   } while (EatIfPresent(lltok::comma));
10126 
10127   // Now that the TypeTests vector is finalized, it is safe to save the
10128   // locations of any forward GV references that need updating later.
10129   for (auto I : IdToIndexMap) {
10130     auto &Ids = ForwardRefTypeIds[I.first];
10131     for (auto P : I.second) {
10132       assert(TypeTests[P.first] == 0 &&
10133              "Forward referenced type id GUID expected to be 0");
10134       Ids.emplace_back(&TypeTests[P.first], P.second);
10135     }
10136   }
10137 
10138   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10139     return true;
10140 
10141   return false;
10142 }
10143 
10144 /// VFuncIdList
10145 ///   ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10146 bool LLParser::parseVFuncIdList(
10147     lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10148   assert(Lex.getKind() == Kind);
10149   Lex.Lex();
10150 
10151   if (parseToken(lltok::colon, "expected ':' here") ||
10152       parseToken(lltok::lparen, "expected '(' here"))
10153     return true;
10154 
10155   IdToIndexMapType IdToIndexMap;
10156   do {
10157     FunctionSummary::VFuncId VFuncId;
10158     if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10159       return true;
10160     VFuncIdList.push_back(VFuncId);
10161   } while (EatIfPresent(lltok::comma));
10162 
10163   if (parseToken(lltok::rparen, "expected ')' here"))
10164     return true;
10165 
10166   // Now that the VFuncIdList vector is finalized, it is safe to save the
10167   // locations of any forward GV references that need updating later.
10168   for (auto I : IdToIndexMap) {
10169     auto &Ids = ForwardRefTypeIds[I.first];
10170     for (auto P : I.second) {
10171       assert(VFuncIdList[P.first].GUID == 0 &&
10172              "Forward referenced type id GUID expected to be 0");
10173       Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10174     }
10175   }
10176 
10177   return false;
10178 }
10179 
10180 /// ConstVCallList
10181 ///   ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10182 bool LLParser::parseConstVCallList(
10183     lltok::Kind Kind,
10184     std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10185   assert(Lex.getKind() == Kind);
10186   Lex.Lex();
10187 
10188   if (parseToken(lltok::colon, "expected ':' here") ||
10189       parseToken(lltok::lparen, "expected '(' here"))
10190     return true;
10191 
10192   IdToIndexMapType IdToIndexMap;
10193   do {
10194     FunctionSummary::ConstVCall ConstVCall;
10195     if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10196       return true;
10197     ConstVCallList.push_back(ConstVCall);
10198   } while (EatIfPresent(lltok::comma));
10199 
10200   if (parseToken(lltok::rparen, "expected ')' here"))
10201     return true;
10202 
10203   // Now that the ConstVCallList vector is finalized, it is safe to save the
10204   // locations of any forward GV references that need updating later.
10205   for (auto I : IdToIndexMap) {
10206     auto &Ids = ForwardRefTypeIds[I.first];
10207     for (auto P : I.second) {
10208       assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10209              "Forward referenced type id GUID expected to be 0");
10210       Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10211     }
10212   }
10213 
10214   return false;
10215 }
10216 
10217 /// ConstVCall
10218 ///   ::= '(' VFuncId ',' Args ')'
10219 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10220                                IdToIndexMapType &IdToIndexMap, unsigned Index) {
10221   if (parseToken(lltok::lparen, "expected '(' here") ||
10222       parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10223     return true;
10224 
10225   if (EatIfPresent(lltok::comma))
10226     if (parseArgs(ConstVCall.Args))
10227       return true;
10228 
10229   if (parseToken(lltok::rparen, "expected ')' here"))
10230     return true;
10231 
10232   return false;
10233 }
10234 
10235 /// VFuncId
10236 ///   ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10237 ///         'offset' ':' UInt64 ')'
10238 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10239                             IdToIndexMapType &IdToIndexMap, unsigned Index) {
10240   assert(Lex.getKind() == lltok::kw_vFuncId);
10241   Lex.Lex();
10242 
10243   if (parseToken(lltok::colon, "expected ':' here") ||
10244       parseToken(lltok::lparen, "expected '(' here"))
10245     return true;
10246 
10247   if (Lex.getKind() == lltok::SummaryID) {
10248     VFuncId.GUID = 0;
10249     unsigned ID = Lex.getUIntVal();
10250     LocTy Loc = Lex.getLoc();
10251     // Keep track of the array index needing a forward reference.
10252     // We will save the location of the GUID needing an update, but
10253     // can only do so once the caller's std::vector is finalized.
10254     IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10255     Lex.Lex();
10256   } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10257              parseToken(lltok::colon, "expected ':' here") ||
10258              parseUInt64(VFuncId.GUID))
10259     return true;
10260 
10261   if (parseToken(lltok::comma, "expected ',' here") ||
10262       parseToken(lltok::kw_offset, "expected 'offset' here") ||
10263       parseToken(lltok::colon, "expected ':' here") ||
10264       parseUInt64(VFuncId.Offset) ||
10265       parseToken(lltok::rparen, "expected ')' here"))
10266     return true;
10267 
10268   return false;
10269 }
10270 
10271 /// GVFlags
10272 ///   ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10273 ///         'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10274 ///         'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10275 ///         'canAutoHide' ':' Flag ',' ')'
10276 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10277   assert(Lex.getKind() == lltok::kw_flags);
10278   Lex.Lex();
10279 
10280   if (parseToken(lltok::colon, "expected ':' here") ||
10281       parseToken(lltok::lparen, "expected '(' here"))
10282     return true;
10283 
10284   do {
10285     unsigned Flag = 0;
10286     switch (Lex.getKind()) {
10287     case lltok::kw_linkage:
10288       Lex.Lex();
10289       if (parseToken(lltok::colon, "expected ':'"))
10290         return true;
10291       bool HasLinkage;
10292       GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10293       assert(HasLinkage && "Linkage not optional in summary entry");
10294       Lex.Lex();
10295       break;
10296     case lltok::kw_visibility:
10297       Lex.Lex();
10298       if (parseToken(lltok::colon, "expected ':'"))
10299         return true;
10300       parseOptionalVisibility(Flag);
10301       GVFlags.Visibility = Flag;
10302       break;
10303     case lltok::kw_notEligibleToImport:
10304       Lex.Lex();
10305       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10306         return true;
10307       GVFlags.NotEligibleToImport = Flag;
10308       break;
10309     case lltok::kw_live:
10310       Lex.Lex();
10311       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10312         return true;
10313       GVFlags.Live = Flag;
10314       break;
10315     case lltok::kw_dsoLocal:
10316       Lex.Lex();
10317       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10318         return true;
10319       GVFlags.DSOLocal = Flag;
10320       break;
10321     case lltok::kw_canAutoHide:
10322       Lex.Lex();
10323       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10324         return true;
10325       GVFlags.CanAutoHide = Flag;
10326       break;
10327     case lltok::kw_importType:
10328       Lex.Lex();
10329       if (parseToken(lltok::colon, "expected ':'"))
10330         return true;
10331       GlobalValueSummary::ImportKind IK;
10332       if (parseOptionalImportType(Lex.getKind(), IK))
10333         return true;
10334       GVFlags.ImportType = static_cast<unsigned>(IK);
10335       Lex.Lex();
10336       break;
10337     default:
10338       return error(Lex.getLoc(), "expected gv flag type");
10339     }
10340   } while (EatIfPresent(lltok::comma));
10341 
10342   if (parseToken(lltok::rparen, "expected ')' here"))
10343     return true;
10344 
10345   return false;
10346 }
10347 
10348 /// GVarFlags
10349 ///   ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10350 ///                      ',' 'writeonly' ':' Flag
10351 ///                      ',' 'constant' ':' Flag ')'
10352 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10353   assert(Lex.getKind() == lltok::kw_varFlags);
10354   Lex.Lex();
10355 
10356   if (parseToken(lltok::colon, "expected ':' here") ||
10357       parseToken(lltok::lparen, "expected '(' here"))
10358     return true;
10359 
10360   auto ParseRest = [this](unsigned int &Val) {
10361     Lex.Lex();
10362     if (parseToken(lltok::colon, "expected ':'"))
10363       return true;
10364     return parseFlag(Val);
10365   };
10366 
10367   do {
10368     unsigned Flag = 0;
10369     switch (Lex.getKind()) {
10370     case lltok::kw_readonly:
10371       if (ParseRest(Flag))
10372         return true;
10373       GVarFlags.MaybeReadOnly = Flag;
10374       break;
10375     case lltok::kw_writeonly:
10376       if (ParseRest(Flag))
10377         return true;
10378       GVarFlags.MaybeWriteOnly = Flag;
10379       break;
10380     case lltok::kw_constant:
10381       if (ParseRest(Flag))
10382         return true;
10383       GVarFlags.Constant = Flag;
10384       break;
10385     case lltok::kw_vcall_visibility:
10386       if (ParseRest(Flag))
10387         return true;
10388       GVarFlags.VCallVisibility = Flag;
10389       break;
10390     default:
10391       return error(Lex.getLoc(), "expected gvar flag type");
10392     }
10393   } while (EatIfPresent(lltok::comma));
10394   return parseToken(lltok::rparen, "expected ')' here");
10395 }
10396 
10397 /// ModuleReference
10398 ///   ::= 'module' ':' UInt
10399 bool LLParser::parseModuleReference(StringRef &ModulePath) {
10400   // parse module id.
10401   if (parseToken(lltok::kw_module, "expected 'module' here") ||
10402       parseToken(lltok::colon, "expected ':' here") ||
10403       parseToken(lltok::SummaryID, "expected module ID"))
10404     return true;
10405 
10406   unsigned ModuleID = Lex.getUIntVal();
10407   auto I = ModuleIdMap.find(ModuleID);
10408   // We should have already parsed all module IDs
10409   assert(I != ModuleIdMap.end());
10410   ModulePath = I->second;
10411   return false;
10412 }
10413 
10414 /// GVReference
10415 ///   ::= SummaryID
10416 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10417   bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10418   if (!ReadOnly)
10419     WriteOnly = EatIfPresent(lltok::kw_writeonly);
10420   if (parseToken(lltok::SummaryID, "expected GV ID"))
10421     return true;
10422 
10423   GVId = Lex.getUIntVal();
10424   // Check if we already have a VI for this GV
10425   if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10426     assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10427     VI = NumberedValueInfos[GVId];
10428   } else
10429     // We will create a forward reference to the stored location.
10430     VI = ValueInfo(false, FwdVIRef);
10431 
10432   if (ReadOnly)
10433     VI.setReadOnly();
10434   if (WriteOnly)
10435     VI.setWriteOnly();
10436   return false;
10437 }
10438 
10439 /// OptionalAllocs
10440 ///   := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10441 /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10442 ///              ',' MemProfs ')'
10443 /// Version ::= UInt32
10444 bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10445   assert(Lex.getKind() == lltok::kw_allocs);
10446   Lex.Lex();
10447 
10448   if (parseToken(lltok::colon, "expected ':' in allocs") ||
10449       parseToken(lltok::lparen, "expected '(' in allocs"))
10450     return true;
10451 
10452   // parse each alloc
10453   do {
10454     if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10455         parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10456         parseToken(lltok::colon, "expected ':'") ||
10457         parseToken(lltok::lparen, "expected '(' in versions"))
10458       return true;
10459 
10460     SmallVector<uint8_t> Versions;
10461     do {
10462       uint8_t V = 0;
10463       if (parseAllocType(V))
10464         return true;
10465       Versions.push_back(V);
10466     } while (EatIfPresent(lltok::comma));
10467 
10468     if (parseToken(lltok::rparen, "expected ')' in versions") ||
10469         parseToken(lltok::comma, "expected ',' in alloc"))
10470       return true;
10471 
10472     std::vector<MIBInfo> MIBs;
10473     if (parseMemProfs(MIBs))
10474       return true;
10475 
10476     Allocs.push_back({Versions, MIBs});
10477 
10478     if (parseToken(lltok::rparen, "expected ')' in alloc"))
10479       return true;
10480   } while (EatIfPresent(lltok::comma));
10481 
10482   if (parseToken(lltok::rparen, "expected ')' in allocs"))
10483     return true;
10484 
10485   return false;
10486 }
10487 
10488 /// MemProfs
10489 ///   := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10490 /// MemProf ::= '(' 'type' ':' AllocType
10491 ///              ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10492 /// StackId ::= UInt64
10493 bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10494   assert(Lex.getKind() == lltok::kw_memProf);
10495   Lex.Lex();
10496 
10497   if (parseToken(lltok::colon, "expected ':' in memprof") ||
10498       parseToken(lltok::lparen, "expected '(' in memprof"))
10499     return true;
10500 
10501   // parse each MIB
10502   do {
10503     if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10504         parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10505         parseToken(lltok::colon, "expected ':'"))
10506       return true;
10507 
10508     uint8_t AllocType;
10509     if (parseAllocType(AllocType))
10510       return true;
10511 
10512     if (parseToken(lltok::comma, "expected ',' in memprof") ||
10513         parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10514         parseToken(lltok::colon, "expected ':'") ||
10515         parseToken(lltok::lparen, "expected '(' in stackIds"))
10516       return true;
10517 
10518     SmallVector<unsigned> StackIdIndices;
10519     do {
10520       uint64_t StackId = 0;
10521       if (parseUInt64(StackId))
10522         return true;
10523       StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10524     } while (EatIfPresent(lltok::comma));
10525 
10526     if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10527       return true;
10528 
10529     MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10530 
10531     if (parseToken(lltok::rparen, "expected ')' in memprof"))
10532       return true;
10533   } while (EatIfPresent(lltok::comma));
10534 
10535   if (parseToken(lltok::rparen, "expected ')' in memprof"))
10536     return true;
10537 
10538   return false;
10539 }
10540 
10541 /// AllocType
10542 ///   := ('none'|'notcold'|'cold'|'hot')
10543 bool LLParser::parseAllocType(uint8_t &AllocType) {
10544   switch (Lex.getKind()) {
10545   case lltok::kw_none:
10546     AllocType = (uint8_t)AllocationType::None;
10547     break;
10548   case lltok::kw_notcold:
10549     AllocType = (uint8_t)AllocationType::NotCold;
10550     break;
10551   case lltok::kw_cold:
10552     AllocType = (uint8_t)AllocationType::Cold;
10553     break;
10554   case lltok::kw_hot:
10555     AllocType = (uint8_t)AllocationType::Hot;
10556     break;
10557   default:
10558     return error(Lex.getLoc(), "invalid alloc type");
10559   }
10560   Lex.Lex();
10561   return false;
10562 }
10563 
10564 /// OptionalCallsites
10565 ///   := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10566 /// Callsite ::= '(' 'callee' ':' GVReference
10567 ///              ',' 'clones' ':' '(' Version [',' Version]* ')'
10568 ///              ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10569 /// Version ::= UInt32
10570 /// StackId ::= UInt64
10571 bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10572   assert(Lex.getKind() == lltok::kw_callsites);
10573   Lex.Lex();
10574 
10575   if (parseToken(lltok::colon, "expected ':' in callsites") ||
10576       parseToken(lltok::lparen, "expected '(' in callsites"))
10577     return true;
10578 
10579   IdToIndexMapType IdToIndexMap;
10580   // parse each callsite
10581   do {
10582     if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10583         parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10584         parseToken(lltok::colon, "expected ':'"))
10585       return true;
10586 
10587     ValueInfo VI;
10588     unsigned GVId = 0;
10589     LocTy Loc = Lex.getLoc();
10590     if (!EatIfPresent(lltok::kw_null)) {
10591       if (parseGVReference(VI, GVId))
10592         return true;
10593     }
10594 
10595     if (parseToken(lltok::comma, "expected ',' in callsite") ||
10596         parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10597         parseToken(lltok::colon, "expected ':'") ||
10598         parseToken(lltok::lparen, "expected '(' in clones"))
10599       return true;
10600 
10601     SmallVector<unsigned> Clones;
10602     do {
10603       unsigned V = 0;
10604       if (parseUInt32(V))
10605         return true;
10606       Clones.push_back(V);
10607     } while (EatIfPresent(lltok::comma));
10608 
10609     if (parseToken(lltok::rparen, "expected ')' in clones") ||
10610         parseToken(lltok::comma, "expected ',' in callsite") ||
10611         parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
10612         parseToken(lltok::colon, "expected ':'") ||
10613         parseToken(lltok::lparen, "expected '(' in stackIds"))
10614       return true;
10615 
10616     SmallVector<unsigned> StackIdIndices;
10617     do {
10618       uint64_t StackId = 0;
10619       if (parseUInt64(StackId))
10620         return true;
10621       StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10622     } while (EatIfPresent(lltok::comma));
10623 
10624     if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10625       return true;
10626 
10627     // Keep track of the Callsites array index needing a forward reference.
10628     // We will save the location of the ValueInfo needing an update, but
10629     // can only do so once the SmallVector is finalized.
10630     if (VI.getRef() == FwdVIRef)
10631       IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10632     Callsites.push_back({VI, Clones, StackIdIndices});
10633 
10634     if (parseToken(lltok::rparen, "expected ')' in callsite"))
10635       return true;
10636   } while (EatIfPresent(lltok::comma));
10637 
10638   // Now that the Callsites vector is finalized, it is safe to save the
10639   // locations of any forward GV references that need updating later.
10640   for (auto I : IdToIndexMap) {
10641     auto &Infos = ForwardRefValueInfos[I.first];
10642     for (auto P : I.second) {
10643       assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
10644              "Forward referenced ValueInfo expected to be empty");
10645       Infos.emplace_back(&Callsites[P.first].Callee, P.second);
10646     }
10647   }
10648 
10649   if (parseToken(lltok::rparen, "expected ')' in callsites"))
10650     return true;
10651 
10652   return false;
10653 }
10654