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