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