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