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