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