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