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