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