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