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