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