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