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