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