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