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