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