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