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