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_udiv:
3480     return error(ID.Loc, "udiv constexprs are no longer supported");
3481   case lltok::kw_sdiv:
3482     return error(ID.Loc, "sdiv constexprs are no longer supported");
3483   case lltok::kw_urem:
3484     return error(ID.Loc, "urem constexprs are no longer supported");
3485   case lltok::kw_srem:
3486     return error(ID.Loc, "srem constexprs are no longer supported");
3487   case lltok::kw_fadd:
3488     return error(ID.Loc, "fadd constexprs are no longer supported");
3489   case lltok::kw_fsub:
3490     return error(ID.Loc, "fsub constexprs are no longer supported");
3491   case lltok::kw_fmul:
3492     return error(ID.Loc, "fmul constexprs are no longer supported");
3493   case lltok::kw_fdiv:
3494     return error(ID.Loc, "fdiv constexprs are no longer supported");
3495   case lltok::kw_frem:
3496     return error(ID.Loc, "frem constexprs are no longer supported");
3497   case lltok::kw_icmp:
3498   case lltok::kw_fcmp: {
3499     unsigned PredVal, Opc = Lex.getUIntVal();
3500     Constant *Val0, *Val1;
3501     Lex.Lex();
3502     if (parseCmpPredicate(PredVal, Opc) ||
3503         parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3504         parseGlobalTypeAndValue(Val0) ||
3505         parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3506         parseGlobalTypeAndValue(Val1) ||
3507         parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3508       return true;
3509 
3510     if (Val0->getType() != Val1->getType())
3511       return error(ID.Loc, "compare operands must have the same type");
3512 
3513     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3514 
3515     if (Opc == Instruction::FCmp) {
3516       if (!Val0->getType()->isFPOrFPVectorTy())
3517         return error(ID.Loc, "fcmp requires floating point operands");
3518       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3519     } else {
3520       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3521       if (!Val0->getType()->isIntOrIntVectorTy() &&
3522           !Val0->getType()->isPtrOrPtrVectorTy())
3523         return error(ID.Loc, "icmp requires pointer or integer operands");
3524       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3525     }
3526     ID.Kind = ValID::t_Constant;
3527     return false;
3528   }
3529 
3530   // Unary Operators.
3531   case lltok::kw_fneg: {
3532     unsigned Opc = Lex.getUIntVal();
3533     Constant *Val;
3534     Lex.Lex();
3535     if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3536         parseGlobalTypeAndValue(Val) ||
3537         parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3538       return true;
3539 
3540     // Check that the type is valid for the operator.
3541     switch (Opc) {
3542     case Instruction::FNeg:
3543       if (!Val->getType()->isFPOrFPVectorTy())
3544         return error(ID.Loc, "constexpr requires fp operands");
3545       break;
3546     default: llvm_unreachable("Unknown unary operator!");
3547     }
3548     unsigned Flags = 0;
3549     Constant *C = ConstantExpr::get(Opc, Val, Flags);
3550     ID.ConstantVal = C;
3551     ID.Kind = ValID::t_Constant;
3552     return false;
3553   }
3554   // Binary Operators.
3555   case lltok::kw_add:
3556   case lltok::kw_sub:
3557   case lltok::kw_mul:
3558   case lltok::kw_shl:
3559   case lltok::kw_lshr:
3560   case lltok::kw_ashr: {
3561     bool NUW = false;
3562     bool NSW = false;
3563     bool Exact = false;
3564     unsigned Opc = Lex.getUIntVal();
3565     Constant *Val0, *Val1;
3566     Lex.Lex();
3567     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3568         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3569       if (EatIfPresent(lltok::kw_nuw))
3570         NUW = true;
3571       if (EatIfPresent(lltok::kw_nsw)) {
3572         NSW = true;
3573         if (EatIfPresent(lltok::kw_nuw))
3574           NUW = true;
3575       }
3576     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3577                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3578       if (EatIfPresent(lltok::kw_exact))
3579         Exact = true;
3580     }
3581     if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3582         parseGlobalTypeAndValue(Val0) ||
3583         parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3584         parseGlobalTypeAndValue(Val1) ||
3585         parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3586       return true;
3587     if (Val0->getType() != Val1->getType())
3588       return error(ID.Loc, "operands of constexpr must have same type");
3589     // Check that the type is valid for the operator.
3590     switch (Opc) {
3591     case Instruction::Add:
3592     case Instruction::Sub:
3593     case Instruction::Mul:
3594     case Instruction::UDiv:
3595     case Instruction::SDiv:
3596     case Instruction::URem:
3597     case Instruction::SRem:
3598     case Instruction::Shl:
3599     case Instruction::AShr:
3600     case Instruction::LShr:
3601       if (!Val0->getType()->isIntOrIntVectorTy())
3602         return error(ID.Loc, "constexpr requires integer operands");
3603       break;
3604     case Instruction::FAdd:
3605     case Instruction::FSub:
3606     case Instruction::FMul:
3607     case Instruction::FDiv:
3608     case Instruction::FRem:
3609       if (!Val0->getType()->isFPOrFPVectorTy())
3610         return error(ID.Loc, "constexpr requires fp operands");
3611       break;
3612     default: llvm_unreachable("Unknown binary operator!");
3613     }
3614     unsigned Flags = 0;
3615     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3616     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3617     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3618     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3619     ID.ConstantVal = C;
3620     ID.Kind = ValID::t_Constant;
3621     return false;
3622   }
3623 
3624   // Logical Operations
3625   case lltok::kw_and:
3626   case lltok::kw_or:
3627   case lltok::kw_xor: {
3628     unsigned Opc = Lex.getUIntVal();
3629     Constant *Val0, *Val1;
3630     Lex.Lex();
3631     if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3632         parseGlobalTypeAndValue(Val0) ||
3633         parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3634         parseGlobalTypeAndValue(Val1) ||
3635         parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3636       return true;
3637     if (Val0->getType() != Val1->getType())
3638       return error(ID.Loc, "operands of constexpr must have same type");
3639     if (!Val0->getType()->isIntOrIntVectorTy())
3640       return error(ID.Loc,
3641                    "constexpr requires integer or integer vector operands");
3642     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3643     ID.Kind = ValID::t_Constant;
3644     return false;
3645   }
3646 
3647   case lltok::kw_getelementptr:
3648   case lltok::kw_shufflevector:
3649   case lltok::kw_insertelement:
3650   case lltok::kw_extractelement:
3651   case lltok::kw_select: {
3652     unsigned Opc = Lex.getUIntVal();
3653     SmallVector<Constant*, 16> Elts;
3654     bool InBounds = false;
3655     Type *Ty;
3656     Lex.Lex();
3657 
3658     if (Opc == Instruction::GetElementPtr)
3659       InBounds = EatIfPresent(lltok::kw_inbounds);
3660 
3661     if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3662       return true;
3663 
3664     LocTy ExplicitTypeLoc = Lex.getLoc();
3665     if (Opc == Instruction::GetElementPtr) {
3666       if (parseType(Ty) ||
3667           parseToken(lltok::comma, "expected comma after getelementptr's type"))
3668         return true;
3669     }
3670 
3671     Optional<unsigned> InRangeOp;
3672     if (parseGlobalValueVector(
3673             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3674         parseToken(lltok::rparen, "expected ')' in constantexpr"))
3675       return true;
3676 
3677     if (Opc == Instruction::GetElementPtr) {
3678       if (Elts.size() == 0 ||
3679           !Elts[0]->getType()->isPtrOrPtrVectorTy())
3680         return error(ID.Loc, "base of getelementptr must be a pointer");
3681 
3682       Type *BaseType = Elts[0]->getType();
3683       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3684       if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
3685         return error(
3686             ExplicitTypeLoc,
3687             typeComparisonErrorMessage(
3688                 "explicit pointee type doesn't match operand's pointee type",
3689                 Ty, BasePointerType->getNonOpaquePointerElementType()));
3690       }
3691 
3692       unsigned GEPWidth =
3693           BaseType->isVectorTy()
3694               ? cast<FixedVectorType>(BaseType)->getNumElements()
3695               : 0;
3696 
3697       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3698       for (Constant *Val : Indices) {
3699         Type *ValTy = Val->getType();
3700         if (!ValTy->isIntOrIntVectorTy())
3701           return error(ID.Loc, "getelementptr index must be an integer");
3702         if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3703           unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3704           if (GEPWidth && (ValNumEl != GEPWidth))
3705             return error(
3706                 ID.Loc,
3707                 "getelementptr vector index has a wrong number of elements");
3708           // GEPWidth may have been unknown because the base is a scalar,
3709           // but it is known now.
3710           GEPWidth = ValNumEl;
3711         }
3712       }
3713 
3714       SmallPtrSet<Type*, 4> Visited;
3715       if (!Indices.empty() && !Ty->isSized(&Visited))
3716         return error(ID.Loc, "base element of getelementptr must be sized");
3717 
3718       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3719         return error(ID.Loc, "invalid getelementptr indices");
3720 
3721       if (InRangeOp) {
3722         if (*InRangeOp == 0)
3723           return error(ID.Loc,
3724                        "inrange keyword may not appear on pointer operand");
3725         --*InRangeOp;
3726       }
3727 
3728       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3729                                                       InBounds, InRangeOp);
3730     } else if (Opc == Instruction::Select) {
3731       if (Elts.size() != 3)
3732         return error(ID.Loc, "expected three operands to select");
3733       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3734                                                               Elts[2]))
3735         return error(ID.Loc, Reason);
3736       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3737     } else if (Opc == Instruction::ShuffleVector) {
3738       if (Elts.size() != 3)
3739         return error(ID.Loc, "expected three operands to shufflevector");
3740       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3741         return error(ID.Loc, "invalid operands to shufflevector");
3742       SmallVector<int, 16> Mask;
3743       ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3744       ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3745     } else if (Opc == Instruction::ExtractElement) {
3746       if (Elts.size() != 2)
3747         return error(ID.Loc, "expected two operands to extractelement");
3748       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3749         return error(ID.Loc, "invalid extractelement operands");
3750       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3751     } else {
3752       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3753       if (Elts.size() != 3)
3754         return error(ID.Loc, "expected three operands to insertelement");
3755       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3756         return error(ID.Loc, "invalid insertelement operands");
3757       ID.ConstantVal =
3758                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3759     }
3760 
3761     ID.Kind = ValID::t_Constant;
3762     return false;
3763   }
3764   }
3765 
3766   Lex.Lex();
3767   return false;
3768 }
3769 
3770 /// parseGlobalValue - parse a global value with the specified type.
3771 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3772   C = nullptr;
3773   ValID ID;
3774   Value *V = nullptr;
3775   bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
3776                 convertValIDToValue(Ty, ID, V, nullptr);
3777   if (V && !(C = dyn_cast<Constant>(V)))
3778     return error(ID.Loc, "global values must be constants");
3779   return Parsed;
3780 }
3781 
3782 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3783   Type *Ty = nullptr;
3784   return parseType(Ty) || parseGlobalValue(Ty, V);
3785 }
3786 
3787 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3788   C = nullptr;
3789 
3790   LocTy KwLoc = Lex.getLoc();
3791   if (!EatIfPresent(lltok::kw_comdat))
3792     return false;
3793 
3794   if (EatIfPresent(lltok::lparen)) {
3795     if (Lex.getKind() != lltok::ComdatVar)
3796       return tokError("expected comdat variable");
3797     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3798     Lex.Lex();
3799     if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3800       return true;
3801   } else {
3802     if (GlobalName.empty())
3803       return tokError("comdat cannot be unnamed");
3804     C = getComdat(std::string(GlobalName), KwLoc);
3805   }
3806 
3807   return false;
3808 }
3809 
3810 /// parseGlobalValueVector
3811 ///   ::= /*empty*/
3812 ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3813 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3814                                       Optional<unsigned> *InRangeOp) {
3815   // Empty list.
3816   if (Lex.getKind() == lltok::rbrace ||
3817       Lex.getKind() == lltok::rsquare ||
3818       Lex.getKind() == lltok::greater ||
3819       Lex.getKind() == lltok::rparen)
3820     return false;
3821 
3822   do {
3823     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3824       *InRangeOp = Elts.size();
3825 
3826     Constant *C;
3827     if (parseGlobalTypeAndValue(C))
3828       return true;
3829     Elts.push_back(C);
3830   } while (EatIfPresent(lltok::comma));
3831 
3832   return false;
3833 }
3834 
3835 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3836   SmallVector<Metadata *, 16> Elts;
3837   if (parseMDNodeVector(Elts))
3838     return true;
3839 
3840   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3841   return false;
3842 }
3843 
3844 /// MDNode:
3845 ///  ::= !{ ... }
3846 ///  ::= !7
3847 ///  ::= !DILocation(...)
3848 bool LLParser::parseMDNode(MDNode *&N) {
3849   if (Lex.getKind() == lltok::MetadataVar)
3850     return parseSpecializedMDNode(N);
3851 
3852   return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3853 }
3854 
3855 bool LLParser::parseMDNodeTail(MDNode *&N) {
3856   // !{ ... }
3857   if (Lex.getKind() == lltok::lbrace)
3858     return parseMDTuple(N);
3859 
3860   // !42
3861   return parseMDNodeID(N);
3862 }
3863 
3864 namespace {
3865 
3866 /// Structure to represent an optional metadata field.
3867 template <class FieldTy> struct MDFieldImpl {
3868   typedef MDFieldImpl ImplTy;
3869   FieldTy Val;
3870   bool Seen;
3871 
3872   void assign(FieldTy Val) {
3873     Seen = true;
3874     this->Val = std::move(Val);
3875   }
3876 
3877   explicit MDFieldImpl(FieldTy Default)
3878       : Val(std::move(Default)), Seen(false) {}
3879 };
3880 
3881 /// Structure to represent an optional metadata field that
3882 /// can be of either type (A or B) and encapsulates the
3883 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3884 /// to reimplement the specifics for representing each Field.
3885 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3886   typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3887   FieldTypeA A;
3888   FieldTypeB B;
3889   bool Seen;
3890 
3891   enum {
3892     IsInvalid = 0,
3893     IsTypeA = 1,
3894     IsTypeB = 2
3895   } WhatIs;
3896 
3897   void assign(FieldTypeA A) {
3898     Seen = true;
3899     this->A = std::move(A);
3900     WhatIs = IsTypeA;
3901   }
3902 
3903   void assign(FieldTypeB B) {
3904     Seen = true;
3905     this->B = std::move(B);
3906     WhatIs = IsTypeB;
3907   }
3908 
3909   explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3910       : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3911         WhatIs(IsInvalid) {}
3912 };
3913 
3914 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3915   uint64_t Max;
3916 
3917   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3918       : ImplTy(Default), Max(Max) {}
3919 };
3920 
3921 struct LineField : public MDUnsignedField {
3922   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3923 };
3924 
3925 struct ColumnField : public MDUnsignedField {
3926   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3927 };
3928 
3929 struct DwarfTagField : public MDUnsignedField {
3930   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3931   DwarfTagField(dwarf::Tag DefaultTag)
3932       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3933 };
3934 
3935 struct DwarfMacinfoTypeField : public MDUnsignedField {
3936   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3937   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3938     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3939 };
3940 
3941 struct DwarfAttEncodingField : public MDUnsignedField {
3942   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3943 };
3944 
3945 struct DwarfVirtualityField : public MDUnsignedField {
3946   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3947 };
3948 
3949 struct DwarfLangField : public MDUnsignedField {
3950   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3951 };
3952 
3953 struct DwarfCCField : public MDUnsignedField {
3954   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3955 };
3956 
3957 struct EmissionKindField : public MDUnsignedField {
3958   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3959 };
3960 
3961 struct NameTableKindField : public MDUnsignedField {
3962   NameTableKindField()
3963       : MDUnsignedField(
3964             0, (unsigned)
3965                    DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3966 };
3967 
3968 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3969   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3970 };
3971 
3972 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3973   DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3974 };
3975 
3976 struct MDAPSIntField : public MDFieldImpl<APSInt> {
3977   MDAPSIntField() : ImplTy(APSInt()) {}
3978 };
3979 
3980 struct MDSignedField : public MDFieldImpl<int64_t> {
3981   int64_t Min = INT64_MIN;
3982   int64_t Max = INT64_MAX;
3983 
3984   MDSignedField(int64_t Default = 0)
3985       : ImplTy(Default) {}
3986   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3987       : ImplTy(Default), Min(Min), Max(Max) {}
3988 };
3989 
3990 struct MDBoolField : public MDFieldImpl<bool> {
3991   MDBoolField(bool Default = false) : ImplTy(Default) {}
3992 };
3993 
3994 struct MDField : public MDFieldImpl<Metadata *> {
3995   bool AllowNull;
3996 
3997   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3998 };
3999 
4000 struct MDStringField : public MDFieldImpl<MDString *> {
4001   bool AllowEmpty;
4002   MDStringField(bool AllowEmpty = true)
4003       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4004 };
4005 
4006 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4007   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4008 };
4009 
4010 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4011   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4012 };
4013 
4014 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4015   MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4016       : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4017 
4018   MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4019                     bool AllowNull = true)
4020       : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4021 
4022   bool isMDSignedField() const { return WhatIs == IsTypeA; }
4023   bool isMDField() const { return WhatIs == IsTypeB; }
4024   int64_t getMDSignedValue() const {
4025     assert(isMDSignedField() && "Wrong field type");
4026     return A.Val;
4027   }
4028   Metadata *getMDFieldValue() const {
4029     assert(isMDField() && "Wrong field type");
4030     return B.Val;
4031   }
4032 };
4033 
4034 } // end anonymous namespace
4035 
4036 namespace llvm {
4037 
4038 template <>
4039 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4040   if (Lex.getKind() != lltok::APSInt)
4041     return tokError("expected integer");
4042 
4043   Result.assign(Lex.getAPSIntVal());
4044   Lex.Lex();
4045   return false;
4046 }
4047 
4048 template <>
4049 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4050                             MDUnsignedField &Result) {
4051   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4052     return tokError("expected unsigned integer");
4053 
4054   auto &U = Lex.getAPSIntVal();
4055   if (U.ugt(Result.Max))
4056     return tokError("value for '" + Name + "' too large, limit is " +
4057                     Twine(Result.Max));
4058   Result.assign(U.getZExtValue());
4059   assert(Result.Val <= Result.Max && "Expected value in range");
4060   Lex.Lex();
4061   return false;
4062 }
4063 
4064 template <>
4065 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4066   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4067 }
4068 template <>
4069 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4070   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4071 }
4072 
4073 template <>
4074 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4075   if (Lex.getKind() == lltok::APSInt)
4076     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4077 
4078   if (Lex.getKind() != lltok::DwarfTag)
4079     return tokError("expected DWARF tag");
4080 
4081   unsigned Tag = dwarf::getTag(Lex.getStrVal());
4082   if (Tag == dwarf::DW_TAG_invalid)
4083     return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4084   assert(Tag <= Result.Max && "Expected valid DWARF tag");
4085 
4086   Result.assign(Tag);
4087   Lex.Lex();
4088   return false;
4089 }
4090 
4091 template <>
4092 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4093                             DwarfMacinfoTypeField &Result) {
4094   if (Lex.getKind() == lltok::APSInt)
4095     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4096 
4097   if (Lex.getKind() != lltok::DwarfMacinfo)
4098     return tokError("expected DWARF macinfo type");
4099 
4100   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4101   if (Macinfo == dwarf::DW_MACINFO_invalid)
4102     return tokError("invalid DWARF macinfo type" + Twine(" '") +
4103                     Lex.getStrVal() + "'");
4104   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4105 
4106   Result.assign(Macinfo);
4107   Lex.Lex();
4108   return false;
4109 }
4110 
4111 template <>
4112 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4113                             DwarfVirtualityField &Result) {
4114   if (Lex.getKind() == lltok::APSInt)
4115     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4116 
4117   if (Lex.getKind() != lltok::DwarfVirtuality)
4118     return tokError("expected DWARF virtuality code");
4119 
4120   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4121   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4122     return tokError("invalid DWARF virtuality code" + Twine(" '") +
4123                     Lex.getStrVal() + "'");
4124   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4125   Result.assign(Virtuality);
4126   Lex.Lex();
4127   return false;
4128 }
4129 
4130 template <>
4131 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4132   if (Lex.getKind() == lltok::APSInt)
4133     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4134 
4135   if (Lex.getKind() != lltok::DwarfLang)
4136     return tokError("expected DWARF language");
4137 
4138   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4139   if (!Lang)
4140     return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4141                     "'");
4142   assert(Lang <= Result.Max && "Expected valid DWARF language");
4143   Result.assign(Lang);
4144   Lex.Lex();
4145   return false;
4146 }
4147 
4148 template <>
4149 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4150   if (Lex.getKind() == lltok::APSInt)
4151     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4152 
4153   if (Lex.getKind() != lltok::DwarfCC)
4154     return tokError("expected DWARF calling convention");
4155 
4156   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4157   if (!CC)
4158     return tokError("invalid DWARF calling convention" + Twine(" '") +
4159                     Lex.getStrVal() + "'");
4160   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4161   Result.assign(CC);
4162   Lex.Lex();
4163   return false;
4164 }
4165 
4166 template <>
4167 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4168                             EmissionKindField &Result) {
4169   if (Lex.getKind() == lltok::APSInt)
4170     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4171 
4172   if (Lex.getKind() != lltok::EmissionKind)
4173     return tokError("expected emission kind");
4174 
4175   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4176   if (!Kind)
4177     return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4178                     "'");
4179   assert(*Kind <= Result.Max && "Expected valid emission kind");
4180   Result.assign(*Kind);
4181   Lex.Lex();
4182   return false;
4183 }
4184 
4185 template <>
4186 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4187                             NameTableKindField &Result) {
4188   if (Lex.getKind() == lltok::APSInt)
4189     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4190 
4191   if (Lex.getKind() != lltok::NameTableKind)
4192     return tokError("expected nameTable kind");
4193 
4194   auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4195   if (!Kind)
4196     return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4197                     "'");
4198   assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4199   Result.assign((unsigned)*Kind);
4200   Lex.Lex();
4201   return false;
4202 }
4203 
4204 template <>
4205 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4206                             DwarfAttEncodingField &Result) {
4207   if (Lex.getKind() == lltok::APSInt)
4208     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4209 
4210   if (Lex.getKind() != lltok::DwarfAttEncoding)
4211     return tokError("expected DWARF type attribute encoding");
4212 
4213   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4214   if (!Encoding)
4215     return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4216                     Lex.getStrVal() + "'");
4217   assert(Encoding <= Result.Max && "Expected valid DWARF language");
4218   Result.assign(Encoding);
4219   Lex.Lex();
4220   return false;
4221 }
4222 
4223 /// DIFlagField
4224 ///  ::= uint32
4225 ///  ::= DIFlagVector
4226 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4227 template <>
4228 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4229 
4230   // parser for a single flag.
4231   auto parseFlag = [&](DINode::DIFlags &Val) {
4232     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4233       uint32_t TempVal = static_cast<uint32_t>(Val);
4234       bool Res = parseUInt32(TempVal);
4235       Val = static_cast<DINode::DIFlags>(TempVal);
4236       return Res;
4237     }
4238 
4239     if (Lex.getKind() != lltok::DIFlag)
4240       return tokError("expected debug info flag");
4241 
4242     Val = DINode::getFlag(Lex.getStrVal());
4243     if (!Val)
4244       return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4245                       "'");
4246     Lex.Lex();
4247     return false;
4248   };
4249 
4250   // parse the flags and combine them together.
4251   DINode::DIFlags Combined = DINode::FlagZero;
4252   do {
4253     DINode::DIFlags Val;
4254     if (parseFlag(Val))
4255       return true;
4256     Combined |= Val;
4257   } while (EatIfPresent(lltok::bar));
4258 
4259   Result.assign(Combined);
4260   return false;
4261 }
4262 
4263 /// DISPFlagField
4264 ///  ::= uint32
4265 ///  ::= DISPFlagVector
4266 ///  ::= DISPFlagVector '|' DISPFlag* '|' uint32
4267 template <>
4268 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4269 
4270   // parser for a single flag.
4271   auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4272     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4273       uint32_t TempVal = static_cast<uint32_t>(Val);
4274       bool Res = parseUInt32(TempVal);
4275       Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4276       return Res;
4277     }
4278 
4279     if (Lex.getKind() != lltok::DISPFlag)
4280       return tokError("expected debug info flag");
4281 
4282     Val = DISubprogram::getFlag(Lex.getStrVal());
4283     if (!Val)
4284       return tokError(Twine("invalid subprogram debug info flag '") +
4285                       Lex.getStrVal() + "'");
4286     Lex.Lex();
4287     return false;
4288   };
4289 
4290   // parse the flags and combine them together.
4291   DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4292   do {
4293     DISubprogram::DISPFlags Val;
4294     if (parseFlag(Val))
4295       return true;
4296     Combined |= Val;
4297   } while (EatIfPresent(lltok::bar));
4298 
4299   Result.assign(Combined);
4300   return false;
4301 }
4302 
4303 template <>
4304 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4305   if (Lex.getKind() != lltok::APSInt)
4306     return tokError("expected signed integer");
4307 
4308   auto &S = Lex.getAPSIntVal();
4309   if (S < Result.Min)
4310     return tokError("value for '" + Name + "' too small, limit is " +
4311                     Twine(Result.Min));
4312   if (S > Result.Max)
4313     return tokError("value for '" + Name + "' too large, limit is " +
4314                     Twine(Result.Max));
4315   Result.assign(S.getExtValue());
4316   assert(Result.Val >= Result.Min && "Expected value in range");
4317   assert(Result.Val <= Result.Max && "Expected value in range");
4318   Lex.Lex();
4319   return false;
4320 }
4321 
4322 template <>
4323 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4324   switch (Lex.getKind()) {
4325   default:
4326     return tokError("expected 'true' or 'false'");
4327   case lltok::kw_true:
4328     Result.assign(true);
4329     break;
4330   case lltok::kw_false:
4331     Result.assign(false);
4332     break;
4333   }
4334   Lex.Lex();
4335   return false;
4336 }
4337 
4338 template <>
4339 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4340   if (Lex.getKind() == lltok::kw_null) {
4341     if (!Result.AllowNull)
4342       return tokError("'" + Name + "' cannot be null");
4343     Lex.Lex();
4344     Result.assign(nullptr);
4345     return false;
4346   }
4347 
4348   Metadata *MD;
4349   if (parseMetadata(MD, nullptr))
4350     return true;
4351 
4352   Result.assign(MD);
4353   return false;
4354 }
4355 
4356 template <>
4357 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4358                             MDSignedOrMDField &Result) {
4359   // Try to parse a signed int.
4360   if (Lex.getKind() == lltok::APSInt) {
4361     MDSignedField Res = Result.A;
4362     if (!parseMDField(Loc, Name, Res)) {
4363       Result.assign(Res);
4364       return false;
4365     }
4366     return true;
4367   }
4368 
4369   // Otherwise, try to parse as an MDField.
4370   MDField Res = Result.B;
4371   if (!parseMDField(Loc, Name, Res)) {
4372     Result.assign(Res);
4373     return false;
4374   }
4375 
4376   return true;
4377 }
4378 
4379 template <>
4380 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4381   LocTy ValueLoc = Lex.getLoc();
4382   std::string S;
4383   if (parseStringConstant(S))
4384     return true;
4385 
4386   if (!Result.AllowEmpty && S.empty())
4387     return error(ValueLoc, "'" + Name + "' cannot be empty");
4388 
4389   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4390   return false;
4391 }
4392 
4393 template <>
4394 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4395   SmallVector<Metadata *, 4> MDs;
4396   if (parseMDNodeVector(MDs))
4397     return true;
4398 
4399   Result.assign(std::move(MDs));
4400   return false;
4401 }
4402 
4403 template <>
4404 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4405                             ChecksumKindField &Result) {
4406   Optional<DIFile::ChecksumKind> CSKind =
4407       DIFile::getChecksumKind(Lex.getStrVal());
4408 
4409   if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4410     return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4411                     "'");
4412 
4413   Result.assign(*CSKind);
4414   Lex.Lex();
4415   return false;
4416 }
4417 
4418 } // end namespace llvm
4419 
4420 template <class ParserTy>
4421 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4422   do {
4423     if (Lex.getKind() != lltok::LabelStr)
4424       return tokError("expected field label here");
4425 
4426     if (ParseField())
4427       return true;
4428   } while (EatIfPresent(lltok::comma));
4429 
4430   return false;
4431 }
4432 
4433 template <class ParserTy>
4434 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4435   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4436   Lex.Lex();
4437 
4438   if (parseToken(lltok::lparen, "expected '(' here"))
4439     return true;
4440   if (Lex.getKind() != lltok::rparen)
4441     if (parseMDFieldsImplBody(ParseField))
4442       return true;
4443 
4444   ClosingLoc = Lex.getLoc();
4445   return parseToken(lltok::rparen, "expected ')' here");
4446 }
4447 
4448 template <class FieldTy>
4449 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4450   if (Result.Seen)
4451     return tokError("field '" + Name + "' cannot be specified more than once");
4452 
4453   LocTy Loc = Lex.getLoc();
4454   Lex.Lex();
4455   return parseMDField(Loc, Name, Result);
4456 }
4457 
4458 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4459   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4460 
4461 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
4462   if (Lex.getStrVal() == #CLASS)                                               \
4463     return parse##CLASS(N, IsDistinct);
4464 #include "llvm/IR/Metadata.def"
4465 
4466   return tokError("expected metadata type");
4467 }
4468 
4469 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4470 #define NOP_FIELD(NAME, TYPE, INIT)
4471 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
4472   if (!NAME.Seen)                                                              \
4473     return error(ClosingLoc, "missing required field '" #NAME "'");
4474 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
4475   if (Lex.getStrVal() == #NAME)                                                \
4476     return parseMDField(#NAME, NAME);
4477 #define PARSE_MD_FIELDS()                                                      \
4478   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
4479   do {                                                                         \
4480     LocTy ClosingLoc;                                                          \
4481     if (parseMDFieldsImpl(                                                     \
4482             [&]() -> bool {                                                    \
4483               VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                  \
4484               return tokError(Twine("invalid field '") + Lex.getStrVal() +     \
4485                               "'");                                            \
4486             },                                                                 \
4487             ClosingLoc))                                                       \
4488       return true;                                                             \
4489     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
4490   } while (false)
4491 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
4492   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4493 
4494 /// parseDILocationFields:
4495 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4496 ///   isImplicitCode: true)
4497 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4498 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4499   OPTIONAL(line, LineField, );                                                 \
4500   OPTIONAL(column, ColumnField, );                                             \
4501   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4502   OPTIONAL(inlinedAt, MDField, );                                              \
4503   OPTIONAL(isImplicitCode, MDBoolField, (false));
4504   PARSE_MD_FIELDS();
4505 #undef VISIT_MD_FIELDS
4506 
4507   Result =
4508       GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4509                                    inlinedAt.Val, isImplicitCode.Val));
4510   return false;
4511 }
4512 
4513 /// parseGenericDINode:
4514 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4515 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4516 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4517   REQUIRED(tag, DwarfTagField, );                                              \
4518   OPTIONAL(header, MDStringField, );                                           \
4519   OPTIONAL(operands, MDFieldList, );
4520   PARSE_MD_FIELDS();
4521 #undef VISIT_MD_FIELDS
4522 
4523   Result = GET_OR_DISTINCT(GenericDINode,
4524                            (Context, tag.Val, header.Val, operands.Val));
4525   return false;
4526 }
4527 
4528 /// parseDISubrange:
4529 ///   ::= !DISubrange(count: 30, lowerBound: 2)
4530 ///   ::= !DISubrange(count: !node, lowerBound: 2)
4531 ///   ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4532 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4533 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4534   OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false));              \
4535   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4536   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4537   OPTIONAL(stride, MDSignedOrMDField, );
4538   PARSE_MD_FIELDS();
4539 #undef VISIT_MD_FIELDS
4540 
4541   Metadata *Count = nullptr;
4542   Metadata *LowerBound = nullptr;
4543   Metadata *UpperBound = nullptr;
4544   Metadata *Stride = nullptr;
4545 
4546   auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4547     if (Bound.isMDSignedField())
4548       return ConstantAsMetadata::get(ConstantInt::getSigned(
4549           Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4550     if (Bound.isMDField())
4551       return Bound.getMDFieldValue();
4552     return nullptr;
4553   };
4554 
4555   Count = convToMetadata(count);
4556   LowerBound = convToMetadata(lowerBound);
4557   UpperBound = convToMetadata(upperBound);
4558   Stride = convToMetadata(stride);
4559 
4560   Result = GET_OR_DISTINCT(DISubrange,
4561                            (Context, Count, LowerBound, UpperBound, Stride));
4562 
4563   return false;
4564 }
4565 
4566 /// parseDIGenericSubrange:
4567 ///   ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4568 ///   !node3)
4569 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4570 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4571   OPTIONAL(count, MDSignedOrMDField, );                                        \
4572   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4573   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4574   OPTIONAL(stride, MDSignedOrMDField, );
4575   PARSE_MD_FIELDS();
4576 #undef VISIT_MD_FIELDS
4577 
4578   auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4579     if (Bound.isMDSignedField())
4580       return DIExpression::get(
4581           Context, {dwarf::DW_OP_consts,
4582                     static_cast<uint64_t>(Bound.getMDSignedValue())});
4583     if (Bound.isMDField())
4584       return Bound.getMDFieldValue();
4585     return nullptr;
4586   };
4587 
4588   Metadata *Count = ConvToMetadata(count);
4589   Metadata *LowerBound = ConvToMetadata(lowerBound);
4590   Metadata *UpperBound = ConvToMetadata(upperBound);
4591   Metadata *Stride = ConvToMetadata(stride);
4592 
4593   Result = GET_OR_DISTINCT(DIGenericSubrange,
4594                            (Context, Count, LowerBound, UpperBound, Stride));
4595 
4596   return false;
4597 }
4598 
4599 /// parseDIEnumerator:
4600 ///   ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4601 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4602 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4603   REQUIRED(name, MDStringField, );                                             \
4604   REQUIRED(value, MDAPSIntField, );                                            \
4605   OPTIONAL(isUnsigned, MDBoolField, (false));
4606   PARSE_MD_FIELDS();
4607 #undef VISIT_MD_FIELDS
4608 
4609   if (isUnsigned.Val && value.Val.isNegative())
4610     return tokError("unsigned enumerator with negative value");
4611 
4612   APSInt Value(value.Val);
4613   // Add a leading zero so that unsigned values with the msb set are not
4614   // mistaken for negative values when used for signed enumerators.
4615   if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4616     Value = Value.zext(Value.getBitWidth() + 1);
4617 
4618   Result =
4619       GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4620 
4621   return false;
4622 }
4623 
4624 /// parseDIBasicType:
4625 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4626 ///                    encoding: DW_ATE_encoding, flags: 0)
4627 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4628 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4629   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
4630   OPTIONAL(name, MDStringField, );                                             \
4631   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4632   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4633   OPTIONAL(encoding, DwarfAttEncodingField, );                                 \
4634   OPTIONAL(flags, DIFlagField, );
4635   PARSE_MD_FIELDS();
4636 #undef VISIT_MD_FIELDS
4637 
4638   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4639                                          align.Val, encoding.Val, flags.Val));
4640   return false;
4641 }
4642 
4643 /// parseDIStringType:
4644 ///   ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4645 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4646 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4647   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type));                   \
4648   OPTIONAL(name, MDStringField, );                                             \
4649   OPTIONAL(stringLength, MDField, );                                           \
4650   OPTIONAL(stringLengthExpression, MDField, );                                 \
4651   OPTIONAL(stringLocationExpression, MDField, );                               \
4652   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4653   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4654   OPTIONAL(encoding, DwarfAttEncodingField, );
4655   PARSE_MD_FIELDS();
4656 #undef VISIT_MD_FIELDS
4657 
4658   Result = GET_OR_DISTINCT(
4659       DIStringType,
4660       (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
4661        stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
4662   return false;
4663 }
4664 
4665 /// parseDIDerivedType:
4666 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4667 ///                      line: 7, scope: !1, baseType: !2, size: 32,
4668 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
4669 ///                      dwarfAddressSpace: 3)
4670 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4671 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4672   REQUIRED(tag, DwarfTagField, );                                              \
4673   OPTIONAL(name, MDStringField, );                                             \
4674   OPTIONAL(file, MDField, );                                                   \
4675   OPTIONAL(line, LineField, );                                                 \
4676   OPTIONAL(scope, MDField, );                                                  \
4677   REQUIRED(baseType, MDField, );                                               \
4678   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4679   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4680   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4681   OPTIONAL(flags, DIFlagField, );                                              \
4682   OPTIONAL(extraData, MDField, );                                              \
4683   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));      \
4684   OPTIONAL(annotations, MDField, );
4685   PARSE_MD_FIELDS();
4686 #undef VISIT_MD_FIELDS
4687 
4688   Optional<unsigned> DWARFAddressSpace;
4689   if (dwarfAddressSpace.Val != UINT32_MAX)
4690     DWARFAddressSpace = dwarfAddressSpace.Val;
4691 
4692   Result = GET_OR_DISTINCT(DIDerivedType,
4693                            (Context, tag.Val, name.Val, file.Val, line.Val,
4694                             scope.Val, baseType.Val, size.Val, align.Val,
4695                             offset.Val, DWARFAddressSpace, flags.Val,
4696                             extraData.Val, annotations.Val));
4697   return false;
4698 }
4699 
4700 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4701 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4702   REQUIRED(tag, DwarfTagField, );                                              \
4703   OPTIONAL(name, MDStringField, );                                             \
4704   OPTIONAL(file, MDField, );                                                   \
4705   OPTIONAL(line, LineField, );                                                 \
4706   OPTIONAL(scope, MDField, );                                                  \
4707   OPTIONAL(baseType, MDField, );                                               \
4708   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4709   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4710   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4711   OPTIONAL(flags, DIFlagField, );                                              \
4712   OPTIONAL(elements, MDField, );                                               \
4713   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
4714   OPTIONAL(vtableHolder, MDField, );                                           \
4715   OPTIONAL(templateParams, MDField, );                                         \
4716   OPTIONAL(identifier, MDStringField, );                                       \
4717   OPTIONAL(discriminator, MDField, );                                          \
4718   OPTIONAL(dataLocation, MDField, );                                           \
4719   OPTIONAL(associated, MDField, );                                             \
4720   OPTIONAL(allocated, MDField, );                                              \
4721   OPTIONAL(rank, MDSignedOrMDField, );                                         \
4722   OPTIONAL(annotations, MDField, );
4723   PARSE_MD_FIELDS();
4724 #undef VISIT_MD_FIELDS
4725 
4726   Metadata *Rank = nullptr;
4727   if (rank.isMDSignedField())
4728     Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4729         Type::getInt64Ty(Context), rank.getMDSignedValue()));
4730   else if (rank.isMDField())
4731     Rank = rank.getMDFieldValue();
4732 
4733   // If this has an identifier try to build an ODR type.
4734   if (identifier.Val)
4735     if (auto *CT = DICompositeType::buildODRType(
4736             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4737             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4738             elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4739             discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4740             Rank, annotations.Val)) {
4741       Result = CT;
4742       return false;
4743     }
4744 
4745   // Create a new node, and save it in the context if it belongs in the type
4746   // map.
4747   Result = GET_OR_DISTINCT(
4748       DICompositeType,
4749       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4750        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4751        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4752        discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
4753        annotations.Val));
4754   return false;
4755 }
4756 
4757 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4758 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4759   OPTIONAL(flags, DIFlagField, );                                              \
4760   OPTIONAL(cc, DwarfCCField, );                                                \
4761   REQUIRED(types, MDField, );
4762   PARSE_MD_FIELDS();
4763 #undef VISIT_MD_FIELDS
4764 
4765   Result = GET_OR_DISTINCT(DISubroutineType,
4766                            (Context, flags.Val, cc.Val, types.Val));
4767   return false;
4768 }
4769 
4770 /// parseDIFileType:
4771 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4772 ///                   checksumkind: CSK_MD5,
4773 ///                   checksum: "000102030405060708090a0b0c0d0e0f",
4774 ///                   source: "source file contents")
4775 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4776   // The default constructed value for checksumkind is required, but will never
4777   // be used, as the parser checks if the field was actually Seen before using
4778   // the Val.
4779 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4780   REQUIRED(filename, MDStringField, );                                         \
4781   REQUIRED(directory, MDStringField, );                                        \
4782   OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5));                \
4783   OPTIONAL(checksum, MDStringField, );                                         \
4784   OPTIONAL(source, MDStringField, );
4785   PARSE_MD_FIELDS();
4786 #undef VISIT_MD_FIELDS
4787 
4788   Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4789   if (checksumkind.Seen && checksum.Seen)
4790     OptChecksum.emplace(checksumkind.Val, checksum.Val);
4791   else if (checksumkind.Seen || checksum.Seen)
4792     return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4793 
4794   Optional<MDString *> OptSource;
4795   if (source.Seen)
4796     OptSource = source.Val;
4797   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4798                                     OptChecksum, OptSource));
4799   return false;
4800 }
4801 
4802 /// parseDICompileUnit:
4803 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4804 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
4805 ///                      splitDebugFilename: "abc.debug",
4806 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4807 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4808 ///                      sysroot: "/", sdk: "MacOSX.sdk")
4809 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4810   if (!IsDistinct)
4811     return Lex.Error("missing 'distinct', required for !DICompileUnit");
4812 
4813 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4814   REQUIRED(language, DwarfLangField, );                                        \
4815   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
4816   OPTIONAL(producer, MDStringField, );                                         \
4817   OPTIONAL(isOptimized, MDBoolField, );                                        \
4818   OPTIONAL(flags, MDStringField, );                                            \
4819   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
4820   OPTIONAL(splitDebugFilename, MDStringField, );                               \
4821   OPTIONAL(emissionKind, EmissionKindField, );                                 \
4822   OPTIONAL(enums, MDField, );                                                  \
4823   OPTIONAL(retainedTypes, MDField, );                                          \
4824   OPTIONAL(globals, MDField, );                                                \
4825   OPTIONAL(imports, MDField, );                                                \
4826   OPTIONAL(macros, MDField, );                                                 \
4827   OPTIONAL(dwoId, MDUnsignedField, );                                          \
4828   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
4829   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);                       \
4830   OPTIONAL(nameTableKind, NameTableKindField, );                               \
4831   OPTIONAL(rangesBaseAddress, MDBoolField, = false);                           \
4832   OPTIONAL(sysroot, MDStringField, );                                          \
4833   OPTIONAL(sdk, MDStringField, );
4834   PARSE_MD_FIELDS();
4835 #undef VISIT_MD_FIELDS
4836 
4837   Result = DICompileUnit::getDistinct(
4838       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4839       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4840       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4841       splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4842       rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4843   return false;
4844 }
4845 
4846 /// parseDISubprogram:
4847 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4848 ///                     file: !1, line: 7, type: !2, isLocal: false,
4849 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
4850 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
4851 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
4852 ///                     spFlags: 10, isOptimized: false, templateParams: !4,
4853 ///                     declaration: !5, retainedNodes: !6, thrownTypes: !7,
4854 ///                     annotations: !8)
4855 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4856   auto Loc = Lex.getLoc();
4857 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4858   OPTIONAL(scope, MDField, );                                                  \
4859   OPTIONAL(name, MDStringField, );                                             \
4860   OPTIONAL(linkageName, MDStringField, );                                      \
4861   OPTIONAL(file, MDField, );                                                   \
4862   OPTIONAL(line, LineField, );                                                 \
4863   OPTIONAL(type, MDField, );                                                   \
4864   OPTIONAL(isLocal, MDBoolField, );                                            \
4865   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4866   OPTIONAL(scopeLine, LineField, );                                            \
4867   OPTIONAL(containingType, MDField, );                                         \
4868   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
4869   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
4870   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
4871   OPTIONAL(flags, DIFlagField, );                                              \
4872   OPTIONAL(spFlags, DISPFlagField, );                                          \
4873   OPTIONAL(isOptimized, MDBoolField, );                                        \
4874   OPTIONAL(unit, MDField, );                                                   \
4875   OPTIONAL(templateParams, MDField, );                                         \
4876   OPTIONAL(declaration, MDField, );                                            \
4877   OPTIONAL(retainedNodes, MDField, );                                          \
4878   OPTIONAL(thrownTypes, MDField, );                                            \
4879   OPTIONAL(annotations, MDField, );                                            \
4880   OPTIONAL(targetFuncName, MDStringField, );
4881   PARSE_MD_FIELDS();
4882 #undef VISIT_MD_FIELDS
4883 
4884   // An explicit spFlags field takes precedence over individual fields in
4885   // older IR versions.
4886   DISubprogram::DISPFlags SPFlags =
4887       spFlags.Seen ? spFlags.Val
4888                    : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4889                                              isOptimized.Val, virtuality.Val);
4890   if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4891     return Lex.Error(
4892         Loc,
4893         "missing 'distinct', required for !DISubprogram that is a Definition");
4894   Result = GET_OR_DISTINCT(
4895       DISubprogram,
4896       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4897        type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4898        thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4899        declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
4900        targetFuncName.Val));
4901   return false;
4902 }
4903 
4904 /// parseDILexicalBlock:
4905 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4906 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4907 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4908   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4909   OPTIONAL(file, MDField, );                                                   \
4910   OPTIONAL(line, LineField, );                                                 \
4911   OPTIONAL(column, ColumnField, );
4912   PARSE_MD_FIELDS();
4913 #undef VISIT_MD_FIELDS
4914 
4915   Result = GET_OR_DISTINCT(
4916       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4917   return false;
4918 }
4919 
4920 /// parseDILexicalBlockFile:
4921 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4922 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4923 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4924   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4925   OPTIONAL(file, MDField, );                                                   \
4926   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4927   PARSE_MD_FIELDS();
4928 #undef VISIT_MD_FIELDS
4929 
4930   Result = GET_OR_DISTINCT(DILexicalBlockFile,
4931                            (Context, scope.Val, file.Val, discriminator.Val));
4932   return false;
4933 }
4934 
4935 /// parseDICommonBlock:
4936 ///   ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4937 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4938 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4939   REQUIRED(scope, MDField, );                                                  \
4940   OPTIONAL(declaration, MDField, );                                            \
4941   OPTIONAL(name, MDStringField, );                                             \
4942   OPTIONAL(file, MDField, );                                                   \
4943   OPTIONAL(line, LineField, );
4944   PARSE_MD_FIELDS();
4945 #undef VISIT_MD_FIELDS
4946 
4947   Result = GET_OR_DISTINCT(DICommonBlock,
4948                            (Context, scope.Val, declaration.Val, name.Val,
4949                             file.Val, line.Val));
4950   return false;
4951 }
4952 
4953 /// parseDINamespace:
4954 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4955 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
4956 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4957   REQUIRED(scope, MDField, );                                                  \
4958   OPTIONAL(name, MDStringField, );                                             \
4959   OPTIONAL(exportSymbols, MDBoolField, );
4960   PARSE_MD_FIELDS();
4961 #undef VISIT_MD_FIELDS
4962 
4963   Result = GET_OR_DISTINCT(DINamespace,
4964                            (Context, scope.Val, name.Val, exportSymbols.Val));
4965   return false;
4966 }
4967 
4968 /// parseDIMacro:
4969 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
4970 ///   "SomeValue")
4971 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
4972 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4973   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
4974   OPTIONAL(line, LineField, );                                                 \
4975   REQUIRED(name, MDStringField, );                                             \
4976   OPTIONAL(value, MDStringField, );
4977   PARSE_MD_FIELDS();
4978 #undef VISIT_MD_FIELDS
4979 
4980   Result = GET_OR_DISTINCT(DIMacro,
4981                            (Context, type.Val, line.Val, name.Val, value.Val));
4982   return false;
4983 }
4984 
4985 /// parseDIMacroFile:
4986 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4987 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4988 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4989   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
4990   OPTIONAL(line, LineField, );                                                 \
4991   REQUIRED(file, MDField, );                                                   \
4992   OPTIONAL(nodes, MDField, );
4993   PARSE_MD_FIELDS();
4994 #undef VISIT_MD_FIELDS
4995 
4996   Result = GET_OR_DISTINCT(DIMacroFile,
4997                            (Context, type.Val, line.Val, file.Val, nodes.Val));
4998   return false;
4999 }
5000 
5001 /// parseDIModule:
5002 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5003 ///   "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5004 ///   file: !1, line: 4, isDecl: false)
5005 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5006 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5007   REQUIRED(scope, MDField, );                                                  \
5008   REQUIRED(name, MDStringField, );                                             \
5009   OPTIONAL(configMacros, MDStringField, );                                     \
5010   OPTIONAL(includePath, MDStringField, );                                      \
5011   OPTIONAL(apinotes, MDStringField, );                                         \
5012   OPTIONAL(file, MDField, );                                                   \
5013   OPTIONAL(line, LineField, );                                                 \
5014   OPTIONAL(isDecl, MDBoolField, );
5015   PARSE_MD_FIELDS();
5016 #undef VISIT_MD_FIELDS
5017 
5018   Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5019                                       configMacros.Val, includePath.Val,
5020                                       apinotes.Val, line.Val, isDecl.Val));
5021   return false;
5022 }
5023 
5024 /// parseDITemplateTypeParameter:
5025 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5026 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5027 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5028   OPTIONAL(name, MDStringField, );                                             \
5029   REQUIRED(type, MDField, );                                                   \
5030   OPTIONAL(defaulted, MDBoolField, );
5031   PARSE_MD_FIELDS();
5032 #undef VISIT_MD_FIELDS
5033 
5034   Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5035                            (Context, name.Val, type.Val, defaulted.Val));
5036   return false;
5037 }
5038 
5039 /// parseDITemplateValueParameter:
5040 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5041 ///                                 name: "V", type: !1, defaulted: false,
5042 ///                                 value: i32 7)
5043 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5044 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5045   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
5046   OPTIONAL(name, MDStringField, );                                             \
5047   OPTIONAL(type, MDField, );                                                   \
5048   OPTIONAL(defaulted, MDBoolField, );                                          \
5049   REQUIRED(value, MDField, );
5050 
5051   PARSE_MD_FIELDS();
5052 #undef VISIT_MD_FIELDS
5053 
5054   Result = GET_OR_DISTINCT(
5055       DITemplateValueParameter,
5056       (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5057   return false;
5058 }
5059 
5060 /// parseDIGlobalVariable:
5061 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5062 ///                         file: !1, line: 7, type: !2, isLocal: false,
5063 ///                         isDefinition: true, templateParams: !3,
5064 ///                         declaration: !4, align: 8)
5065 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5066 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5067   OPTIONAL(name, MDStringField, (/* AllowEmpty */ false));                     \
5068   OPTIONAL(scope, MDField, );                                                  \
5069   OPTIONAL(linkageName, MDStringField, );                                      \
5070   OPTIONAL(file, MDField, );                                                   \
5071   OPTIONAL(line, LineField, );                                                 \
5072   OPTIONAL(type, MDField, );                                                   \
5073   OPTIONAL(isLocal, MDBoolField, );                                            \
5074   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
5075   OPTIONAL(templateParams, MDField, );                                         \
5076   OPTIONAL(declaration, MDField, );                                            \
5077   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5078   OPTIONAL(annotations, MDField, );
5079   PARSE_MD_FIELDS();
5080 #undef VISIT_MD_FIELDS
5081 
5082   Result =
5083       GET_OR_DISTINCT(DIGlobalVariable,
5084                       (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5085                        line.Val, type.Val, isLocal.Val, isDefinition.Val,
5086                        declaration.Val, templateParams.Val, align.Val,
5087                        annotations.Val));
5088   return false;
5089 }
5090 
5091 /// parseDILocalVariable:
5092 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5093 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5094 ///                        align: 8)
5095 ///   ::= !DILocalVariable(scope: !0, name: "foo",
5096 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5097 ///                        align: 8)
5098 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5099 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5100   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5101   OPTIONAL(name, MDStringField, );                                             \
5102   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
5103   OPTIONAL(file, MDField, );                                                   \
5104   OPTIONAL(line, LineField, );                                                 \
5105   OPTIONAL(type, MDField, );                                                   \
5106   OPTIONAL(flags, DIFlagField, );                                              \
5107   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5108   OPTIONAL(annotations, MDField, );
5109   PARSE_MD_FIELDS();
5110 #undef VISIT_MD_FIELDS
5111 
5112   Result = GET_OR_DISTINCT(DILocalVariable,
5113                            (Context, scope.Val, name.Val, file.Val, line.Val,
5114                             type.Val, arg.Val, flags.Val, align.Val,
5115                             annotations.Val));
5116   return false;
5117 }
5118 
5119 /// parseDILabel:
5120 ///   ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5121 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5122 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5123   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5124   REQUIRED(name, MDStringField, );                                             \
5125   REQUIRED(file, MDField, );                                                   \
5126   REQUIRED(line, LineField, );
5127   PARSE_MD_FIELDS();
5128 #undef VISIT_MD_FIELDS
5129 
5130   Result = GET_OR_DISTINCT(DILabel,
5131                            (Context, scope.Val, name.Val, file.Val, line.Val));
5132   return false;
5133 }
5134 
5135 /// parseDIExpression:
5136 ///   ::= !DIExpression(0, 7, -1)
5137 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5138   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5139   Lex.Lex();
5140 
5141   if (parseToken(lltok::lparen, "expected '(' here"))
5142     return true;
5143 
5144   SmallVector<uint64_t, 8> Elements;
5145   if (Lex.getKind() != lltok::rparen)
5146     do {
5147       if (Lex.getKind() == lltok::DwarfOp) {
5148         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5149           Lex.Lex();
5150           Elements.push_back(Op);
5151           continue;
5152         }
5153         return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5154       }
5155 
5156       if (Lex.getKind() == lltok::DwarfAttEncoding) {
5157         if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5158           Lex.Lex();
5159           Elements.push_back(Op);
5160           continue;
5161         }
5162         return tokError(Twine("invalid DWARF attribute encoding '") +
5163                         Lex.getStrVal() + "'");
5164       }
5165 
5166       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5167         return tokError("expected unsigned integer");
5168 
5169       auto &U = Lex.getAPSIntVal();
5170       if (U.ugt(UINT64_MAX))
5171         return tokError("element too large, limit is " + Twine(UINT64_MAX));
5172       Elements.push_back(U.getZExtValue());
5173       Lex.Lex();
5174     } while (EatIfPresent(lltok::comma));
5175 
5176   if (parseToken(lltok::rparen, "expected ')' here"))
5177     return true;
5178 
5179   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5180   return false;
5181 }
5182 
5183 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5184   return parseDIArgList(Result, IsDistinct, nullptr);
5185 }
5186 /// ParseDIArgList:
5187 ///   ::= !DIArgList(i32 7, i64 %0)
5188 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5189                               PerFunctionState *PFS) {
5190   assert(PFS && "Expected valid function state");
5191   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5192   Lex.Lex();
5193 
5194   if (parseToken(lltok::lparen, "expected '(' here"))
5195     return true;
5196 
5197   SmallVector<ValueAsMetadata *, 4> Args;
5198   if (Lex.getKind() != lltok::rparen)
5199     do {
5200       Metadata *MD;
5201       if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5202         return true;
5203       Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5204     } while (EatIfPresent(lltok::comma));
5205 
5206   if (parseToken(lltok::rparen, "expected ')' here"))
5207     return true;
5208 
5209   Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5210   return false;
5211 }
5212 
5213 /// parseDIGlobalVariableExpression:
5214 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5215 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5216                                                bool IsDistinct) {
5217 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5218   REQUIRED(var, MDField, );                                                    \
5219   REQUIRED(expr, MDField, );
5220   PARSE_MD_FIELDS();
5221 #undef VISIT_MD_FIELDS
5222 
5223   Result =
5224       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5225   return false;
5226 }
5227 
5228 /// parseDIObjCProperty:
5229 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5230 ///                       getter: "getFoo", attributes: 7, type: !2)
5231 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5232 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5233   OPTIONAL(name, MDStringField, );                                             \
5234   OPTIONAL(file, MDField, );                                                   \
5235   OPTIONAL(line, LineField, );                                                 \
5236   OPTIONAL(setter, MDStringField, );                                           \
5237   OPTIONAL(getter, MDStringField, );                                           \
5238   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
5239   OPTIONAL(type, MDField, );
5240   PARSE_MD_FIELDS();
5241 #undef VISIT_MD_FIELDS
5242 
5243   Result = GET_OR_DISTINCT(DIObjCProperty,
5244                            (Context, name.Val, file.Val, line.Val, setter.Val,
5245                             getter.Val, attributes.Val, type.Val));
5246   return false;
5247 }
5248 
5249 /// parseDIImportedEntity:
5250 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5251 ///                         line: 7, name: "foo", elements: !2)
5252 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5253 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5254   REQUIRED(tag, DwarfTagField, );                                              \
5255   REQUIRED(scope, MDField, );                                                  \
5256   OPTIONAL(entity, MDField, );                                                 \
5257   OPTIONAL(file, MDField, );                                                   \
5258   OPTIONAL(line, LineField, );                                                 \
5259   OPTIONAL(name, MDStringField, );                                             \
5260   OPTIONAL(elements, MDField, );
5261   PARSE_MD_FIELDS();
5262 #undef VISIT_MD_FIELDS
5263 
5264   Result = GET_OR_DISTINCT(DIImportedEntity,
5265                            (Context, tag.Val, scope.Val, entity.Val, file.Val,
5266                             line.Val, name.Val, elements.Val));
5267   return false;
5268 }
5269 
5270 #undef PARSE_MD_FIELD
5271 #undef NOP_FIELD
5272 #undef REQUIRE_FIELD
5273 #undef DECLARE_FIELD
5274 
5275 /// parseMetadataAsValue
5276 ///  ::= metadata i32 %local
5277 ///  ::= metadata i32 @global
5278 ///  ::= metadata i32 7
5279 ///  ::= metadata !0
5280 ///  ::= metadata !{...}
5281 ///  ::= metadata !"string"
5282 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5283   // Note: the type 'metadata' has already been parsed.
5284   Metadata *MD;
5285   if (parseMetadata(MD, &PFS))
5286     return true;
5287 
5288   V = MetadataAsValue::get(Context, MD);
5289   return false;
5290 }
5291 
5292 /// parseValueAsMetadata
5293 ///  ::= i32 %local
5294 ///  ::= i32 @global
5295 ///  ::= i32 7
5296 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5297                                     PerFunctionState *PFS) {
5298   Type *Ty;
5299   LocTy Loc;
5300   if (parseType(Ty, TypeMsg, Loc))
5301     return true;
5302   if (Ty->isMetadataTy())
5303     return error(Loc, "invalid metadata-value-metadata roundtrip");
5304 
5305   Value *V;
5306   if (parseValue(Ty, V, PFS))
5307     return true;
5308 
5309   MD = ValueAsMetadata::get(V);
5310   return false;
5311 }
5312 
5313 /// parseMetadata
5314 ///  ::= i32 %local
5315 ///  ::= i32 @global
5316 ///  ::= i32 7
5317 ///  ::= !42
5318 ///  ::= !{...}
5319 ///  ::= !"string"
5320 ///  ::= !DILocation(...)
5321 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5322   if (Lex.getKind() == lltok::MetadataVar) {
5323     MDNode *N;
5324     // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5325     // so parsing this requires a Function State.
5326     if (Lex.getStrVal() == "DIArgList") {
5327       if (parseDIArgList(N, false, PFS))
5328         return true;
5329     } else if (parseSpecializedMDNode(N)) {
5330       return true;
5331     }
5332     MD = N;
5333     return false;
5334   }
5335 
5336   // ValueAsMetadata:
5337   // <type> <value>
5338   if (Lex.getKind() != lltok::exclaim)
5339     return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5340 
5341   // '!'.
5342   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5343   Lex.Lex();
5344 
5345   // MDString:
5346   //   ::= '!' STRINGCONSTANT
5347   if (Lex.getKind() == lltok::StringConstant) {
5348     MDString *S;
5349     if (parseMDString(S))
5350       return true;
5351     MD = S;
5352     return false;
5353   }
5354 
5355   // MDNode:
5356   // !{ ... }
5357   // !7
5358   MDNode *N;
5359   if (parseMDNodeTail(N))
5360     return true;
5361   MD = N;
5362   return false;
5363 }
5364 
5365 //===----------------------------------------------------------------------===//
5366 // Function Parsing.
5367 //===----------------------------------------------------------------------===//
5368 
5369 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5370                                    PerFunctionState *PFS) {
5371   if (Ty->isFunctionTy())
5372     return error(ID.Loc, "functions are not values, refer to them as pointers");
5373 
5374   switch (ID.Kind) {
5375   case ValID::t_LocalID:
5376     if (!PFS)
5377       return error(ID.Loc, "invalid use of function-local name");
5378     V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
5379     return V == nullptr;
5380   case ValID::t_LocalName:
5381     if (!PFS)
5382       return error(ID.Loc, "invalid use of function-local name");
5383     V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
5384     return V == nullptr;
5385   case ValID::t_InlineAsm: {
5386     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5387       return error(ID.Loc, "invalid type for inline asm constraint string");
5388     V = InlineAsm::get(
5389         ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5390         InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5391     return false;
5392   }
5393   case ValID::t_GlobalName:
5394     V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
5395     if (V && ID.NoCFI)
5396       V = NoCFIValue::get(cast<GlobalValue>(V));
5397     return V == nullptr;
5398   case ValID::t_GlobalID:
5399     V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
5400     if (V && ID.NoCFI)
5401       V = NoCFIValue::get(cast<GlobalValue>(V));
5402     return V == nullptr;
5403   case ValID::t_APSInt:
5404     if (!Ty->isIntegerTy())
5405       return error(ID.Loc, "integer constant must have integer type");
5406     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5407     V = ConstantInt::get(Context, ID.APSIntVal);
5408     return false;
5409   case ValID::t_APFloat:
5410     if (!Ty->isFloatingPointTy() ||
5411         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5412       return error(ID.Loc, "floating point constant invalid for type");
5413 
5414     // The lexer has no type info, so builds all half, bfloat, float, and double
5415     // FP constants as double.  Fix this here.  Long double does not need this.
5416     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5417       // Check for signaling before potentially converting and losing that info.
5418       bool IsSNAN = ID.APFloatVal.isSignaling();
5419       bool Ignored;
5420       if (Ty->isHalfTy())
5421         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5422                               &Ignored);
5423       else if (Ty->isBFloatTy())
5424         ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5425                               &Ignored);
5426       else if (Ty->isFloatTy())
5427         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5428                               &Ignored);
5429       if (IsSNAN) {
5430         // The convert call above may quiet an SNaN, so manufacture another
5431         // SNaN. The bitcast works because the payload (significand) parameter
5432         // is truncated to fit.
5433         APInt Payload = ID.APFloatVal.bitcastToAPInt();
5434         ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5435                                          ID.APFloatVal.isNegative(), &Payload);
5436       }
5437     }
5438     V = ConstantFP::get(Context, ID.APFloatVal);
5439 
5440     if (V->getType() != Ty)
5441       return error(ID.Loc, "floating point constant does not have type '" +
5442                                getTypeString(Ty) + "'");
5443 
5444     return false;
5445   case ValID::t_Null:
5446     if (!Ty->isPointerTy())
5447       return error(ID.Loc, "null must be a pointer type");
5448     V = ConstantPointerNull::get(cast<PointerType>(Ty));
5449     return false;
5450   case ValID::t_Undef:
5451     // FIXME: LabelTy should not be a first-class type.
5452     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5453       return error(ID.Loc, "invalid type for undef constant");
5454     V = UndefValue::get(Ty);
5455     return false;
5456   case ValID::t_EmptyArray:
5457     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5458       return error(ID.Loc, "invalid empty array initializer");
5459     V = UndefValue::get(Ty);
5460     return false;
5461   case ValID::t_Zero:
5462     // FIXME: LabelTy should not be a first-class type.
5463     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5464       return error(ID.Loc, "invalid type for null constant");
5465     V = Constant::getNullValue(Ty);
5466     return false;
5467   case ValID::t_None:
5468     if (!Ty->isTokenTy())
5469       return error(ID.Loc, "invalid type for none constant");
5470     V = Constant::getNullValue(Ty);
5471     return false;
5472   case ValID::t_Poison:
5473     // FIXME: LabelTy should not be a first-class type.
5474     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5475       return error(ID.Loc, "invalid type for poison constant");
5476     V = PoisonValue::get(Ty);
5477     return false;
5478   case ValID::t_Constant:
5479     if (ID.ConstantVal->getType() != Ty)
5480       return error(ID.Loc, "constant expression type mismatch: got type '" +
5481                                getTypeString(ID.ConstantVal->getType()) +
5482                                "' but expected '" + getTypeString(Ty) + "'");
5483     V = ID.ConstantVal;
5484     return false;
5485   case ValID::t_ConstantStruct:
5486   case ValID::t_PackedConstantStruct:
5487     if (StructType *ST = dyn_cast<StructType>(Ty)) {
5488       if (ST->getNumElements() != ID.UIntVal)
5489         return error(ID.Loc,
5490                      "initializer with struct type has wrong # elements");
5491       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5492         return error(ID.Loc, "packed'ness of initializer and type don't match");
5493 
5494       // Verify that the elements are compatible with the structtype.
5495       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5496         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5497           return error(
5498               ID.Loc,
5499               "element " + Twine(i) +
5500                   " of struct initializer doesn't match struct element type");
5501 
5502       V = ConstantStruct::get(
5503           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5504     } else
5505       return error(ID.Loc, "constant expression type mismatch");
5506     return false;
5507   }
5508   llvm_unreachable("Invalid ValID");
5509 }
5510 
5511 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5512   C = nullptr;
5513   ValID ID;
5514   auto Loc = Lex.getLoc();
5515   if (parseValID(ID, /*PFS=*/nullptr))
5516     return true;
5517   switch (ID.Kind) {
5518   case ValID::t_APSInt:
5519   case ValID::t_APFloat:
5520   case ValID::t_Undef:
5521   case ValID::t_Constant:
5522   case ValID::t_ConstantStruct:
5523   case ValID::t_PackedConstantStruct: {
5524     Value *V;
5525     if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
5526       return true;
5527     assert(isa<Constant>(V) && "Expected a constant value");
5528     C = cast<Constant>(V);
5529     return false;
5530   }
5531   case ValID::t_Null:
5532     C = Constant::getNullValue(Ty);
5533     return false;
5534   default:
5535     return error(Loc, "expected a constant value");
5536   }
5537 }
5538 
5539 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5540   V = nullptr;
5541   ValID ID;
5542   return parseValID(ID, PFS, Ty) ||
5543          convertValIDToValue(Ty, ID, V, PFS);
5544 }
5545 
5546 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5547   Type *Ty = nullptr;
5548   return parseType(Ty) || parseValue(Ty, V, PFS);
5549 }
5550 
5551 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5552                                       PerFunctionState &PFS) {
5553   Value *V;
5554   Loc = Lex.getLoc();
5555   if (parseTypeAndValue(V, PFS))
5556     return true;
5557   if (!isa<BasicBlock>(V))
5558     return error(Loc, "expected a basic block");
5559   BB = cast<BasicBlock>(V);
5560   return false;
5561 }
5562 
5563 /// FunctionHeader
5564 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5565 ///       OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5566 ///       '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5567 ///       OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5568 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5569   // parse the linkage.
5570   LocTy LinkageLoc = Lex.getLoc();
5571   unsigned Linkage;
5572   unsigned Visibility;
5573   unsigned DLLStorageClass;
5574   bool DSOLocal;
5575   AttrBuilder RetAttrs(M->getContext());
5576   unsigned CC;
5577   bool HasLinkage;
5578   Type *RetType = nullptr;
5579   LocTy RetTypeLoc = Lex.getLoc();
5580   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5581                            DSOLocal) ||
5582       parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5583       parseType(RetType, RetTypeLoc, true /*void allowed*/))
5584     return true;
5585 
5586   // Verify that the linkage is ok.
5587   switch ((GlobalValue::LinkageTypes)Linkage) {
5588   case GlobalValue::ExternalLinkage:
5589     break; // always ok.
5590   case GlobalValue::ExternalWeakLinkage:
5591     if (IsDefine)
5592       return error(LinkageLoc, "invalid linkage for function definition");
5593     break;
5594   case GlobalValue::PrivateLinkage:
5595   case GlobalValue::InternalLinkage:
5596   case GlobalValue::AvailableExternallyLinkage:
5597   case GlobalValue::LinkOnceAnyLinkage:
5598   case GlobalValue::LinkOnceODRLinkage:
5599   case GlobalValue::WeakAnyLinkage:
5600   case GlobalValue::WeakODRLinkage:
5601     if (!IsDefine)
5602       return error(LinkageLoc, "invalid linkage for function declaration");
5603     break;
5604   case GlobalValue::AppendingLinkage:
5605   case GlobalValue::CommonLinkage:
5606     return error(LinkageLoc, "invalid function linkage type");
5607   }
5608 
5609   if (!isValidVisibilityForLinkage(Visibility, Linkage))
5610     return error(LinkageLoc,
5611                  "symbol with local linkage must have default visibility");
5612 
5613   if (!FunctionType::isValidReturnType(RetType))
5614     return error(RetTypeLoc, "invalid function return type");
5615 
5616   LocTy NameLoc = Lex.getLoc();
5617 
5618   std::string FunctionName;
5619   if (Lex.getKind() == lltok::GlobalVar) {
5620     FunctionName = Lex.getStrVal();
5621   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
5622     unsigned NameID = Lex.getUIntVal();
5623 
5624     if (NameID != NumberedVals.size())
5625       return tokError("function expected to be numbered '%" +
5626                       Twine(NumberedVals.size()) + "'");
5627   } else {
5628     return tokError("expected function name");
5629   }
5630 
5631   Lex.Lex();
5632 
5633   if (Lex.getKind() != lltok::lparen)
5634     return tokError("expected '(' in function argument list");
5635 
5636   SmallVector<ArgInfo, 8> ArgList;
5637   bool IsVarArg;
5638   AttrBuilder FuncAttrs(M->getContext());
5639   std::vector<unsigned> FwdRefAttrGrps;
5640   LocTy BuiltinLoc;
5641   std::string Section;
5642   std::string Partition;
5643   MaybeAlign Alignment;
5644   std::string GC;
5645   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5646   unsigned AddrSpace = 0;
5647   Constant *Prefix = nullptr;
5648   Constant *Prologue = nullptr;
5649   Constant *PersonalityFn = nullptr;
5650   Comdat *C;
5651 
5652   if (parseArgumentList(ArgList, IsVarArg) ||
5653       parseOptionalUnnamedAddr(UnnamedAddr) ||
5654       parseOptionalProgramAddrSpace(AddrSpace) ||
5655       parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5656                                  BuiltinLoc) ||
5657       (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5658       (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5659       parseOptionalComdat(FunctionName, C) ||
5660       parseOptionalAlignment(Alignment) ||
5661       (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5662       (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5663       (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5664       (EatIfPresent(lltok::kw_personality) &&
5665        parseGlobalTypeAndValue(PersonalityFn)))
5666     return true;
5667 
5668   if (FuncAttrs.contains(Attribute::Builtin))
5669     return error(BuiltinLoc, "'builtin' attribute not valid on function");
5670 
5671   // If the alignment was parsed as an attribute, move to the alignment field.
5672   if (FuncAttrs.hasAlignmentAttr()) {
5673     Alignment = FuncAttrs.getAlignment();
5674     FuncAttrs.removeAttribute(Attribute::Alignment);
5675   }
5676 
5677   // Okay, if we got here, the function is syntactically valid.  Convert types
5678   // and do semantic checks.
5679   std::vector<Type*> ParamTypeList;
5680   SmallVector<AttributeSet, 8> Attrs;
5681 
5682   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5683     ParamTypeList.push_back(ArgList[i].Ty);
5684     Attrs.push_back(ArgList[i].Attrs);
5685   }
5686 
5687   AttributeList PAL =
5688       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5689                          AttributeSet::get(Context, RetAttrs), Attrs);
5690 
5691   if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
5692     return error(RetTypeLoc, "functions with 'sret' argument must return void");
5693 
5694   FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5695   PointerType *PFT = PointerType::get(FT, AddrSpace);
5696 
5697   Fn = nullptr;
5698   GlobalValue *FwdFn = nullptr;
5699   if (!FunctionName.empty()) {
5700     // If this was a definition of a forward reference, remove the definition
5701     // from the forward reference table and fill in the forward ref.
5702     auto FRVI = ForwardRefVals.find(FunctionName);
5703     if (FRVI != ForwardRefVals.end()) {
5704       FwdFn = FRVI->second.first;
5705       if (!FwdFn->getType()->isOpaque() &&
5706           !FwdFn->getType()->getNonOpaquePointerElementType()->isFunctionTy())
5707         return error(FRVI->second.second, "invalid forward reference to "
5708                                           "function as global value!");
5709       if (FwdFn->getType() != PFT)
5710         return error(FRVI->second.second,
5711                      "invalid forward reference to "
5712                      "function '" +
5713                          FunctionName +
5714                          "' with wrong type: "
5715                          "expected '" +
5716                          getTypeString(PFT) + "' but was '" +
5717                          getTypeString(FwdFn->getType()) + "'");
5718       ForwardRefVals.erase(FRVI);
5719     } else if ((Fn = M->getFunction(FunctionName))) {
5720       // Reject redefinitions.
5721       return error(NameLoc,
5722                    "invalid redefinition of function '" + FunctionName + "'");
5723     } else if (M->getNamedValue(FunctionName)) {
5724       return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5725     }
5726 
5727   } else {
5728     // If this is a definition of a forward referenced function, make sure the
5729     // types agree.
5730     auto I = ForwardRefValIDs.find(NumberedVals.size());
5731     if (I != ForwardRefValIDs.end()) {
5732       FwdFn = I->second.first;
5733       if (FwdFn->getType() != PFT)
5734         return error(NameLoc, "type of definition and forward reference of '@" +
5735                                   Twine(NumberedVals.size()) +
5736                                   "' disagree: "
5737                                   "expected '" +
5738                                   getTypeString(PFT) + "' but was '" +
5739                                   getTypeString(FwdFn->getType()) + "'");
5740       ForwardRefValIDs.erase(I);
5741     }
5742   }
5743 
5744   Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5745                         FunctionName, M);
5746 
5747   assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5748 
5749   if (FunctionName.empty())
5750     NumberedVals.push_back(Fn);
5751 
5752   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5753   maybeSetDSOLocal(DSOLocal, *Fn);
5754   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5755   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5756   Fn->setCallingConv(CC);
5757   Fn->setAttributes(PAL);
5758   Fn->setUnnamedAddr(UnnamedAddr);
5759   Fn->setAlignment(MaybeAlign(Alignment));
5760   Fn->setSection(Section);
5761   Fn->setPartition(Partition);
5762   Fn->setComdat(C);
5763   Fn->setPersonalityFn(PersonalityFn);
5764   if (!GC.empty()) Fn->setGC(GC);
5765   Fn->setPrefixData(Prefix);
5766   Fn->setPrologueData(Prologue);
5767   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5768 
5769   // Add all of the arguments we parsed to the function.
5770   Function::arg_iterator ArgIt = Fn->arg_begin();
5771   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5772     // If the argument has a name, insert it into the argument symbol table.
5773     if (ArgList[i].Name.empty()) continue;
5774 
5775     // Set the name, if it conflicted, it will be auto-renamed.
5776     ArgIt->setName(ArgList[i].Name);
5777 
5778     if (ArgIt->getName() != ArgList[i].Name)
5779       return error(ArgList[i].Loc,
5780                    "redefinition of argument '%" + ArgList[i].Name + "'");
5781   }
5782 
5783   if (FwdFn) {
5784     FwdFn->replaceAllUsesWith(Fn);
5785     FwdFn->eraseFromParent();
5786   }
5787 
5788   if (IsDefine)
5789     return false;
5790 
5791   // Check the declaration has no block address forward references.
5792   ValID ID;
5793   if (FunctionName.empty()) {
5794     ID.Kind = ValID::t_GlobalID;
5795     ID.UIntVal = NumberedVals.size() - 1;
5796   } else {
5797     ID.Kind = ValID::t_GlobalName;
5798     ID.StrVal = FunctionName;
5799   }
5800   auto Blocks = ForwardRefBlockAddresses.find(ID);
5801   if (Blocks != ForwardRefBlockAddresses.end())
5802     return error(Blocks->first.Loc,
5803                  "cannot take blockaddress inside a declaration");
5804   return false;
5805 }
5806 
5807 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5808   ValID ID;
5809   if (FunctionNumber == -1) {
5810     ID.Kind = ValID::t_GlobalName;
5811     ID.StrVal = std::string(F.getName());
5812   } else {
5813     ID.Kind = ValID::t_GlobalID;
5814     ID.UIntVal = FunctionNumber;
5815   }
5816 
5817   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5818   if (Blocks == P.ForwardRefBlockAddresses.end())
5819     return false;
5820 
5821   for (const auto &I : Blocks->second) {
5822     const ValID &BBID = I.first;
5823     GlobalValue *GV = I.second;
5824 
5825     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5826            "Expected local id or name");
5827     BasicBlock *BB;
5828     if (BBID.Kind == ValID::t_LocalName)
5829       BB = getBB(BBID.StrVal, BBID.Loc);
5830     else
5831       BB = getBB(BBID.UIntVal, BBID.Loc);
5832     if (!BB)
5833       return P.error(BBID.Loc, "referenced value is not a basic block");
5834 
5835     Value *ResolvedVal = BlockAddress::get(&F, BB);
5836     ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
5837                                            ResolvedVal);
5838     if (!ResolvedVal)
5839       return true;
5840     GV->replaceAllUsesWith(ResolvedVal);
5841     GV->eraseFromParent();
5842   }
5843 
5844   P.ForwardRefBlockAddresses.erase(Blocks);
5845   return false;
5846 }
5847 
5848 /// parseFunctionBody
5849 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
5850 bool LLParser::parseFunctionBody(Function &Fn) {
5851   if (Lex.getKind() != lltok::lbrace)
5852     return tokError("expected '{' in function body");
5853   Lex.Lex();  // eat the {.
5854 
5855   int FunctionNumber = -1;
5856   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5857 
5858   PerFunctionState PFS(*this, Fn, FunctionNumber);
5859 
5860   // Resolve block addresses and allow basic blocks to be forward-declared
5861   // within this function.
5862   if (PFS.resolveForwardRefBlockAddresses())
5863     return true;
5864   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5865 
5866   // We need at least one basic block.
5867   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5868     return tokError("function body requires at least one basic block");
5869 
5870   while (Lex.getKind() != lltok::rbrace &&
5871          Lex.getKind() != lltok::kw_uselistorder)
5872     if (parseBasicBlock(PFS))
5873       return true;
5874 
5875   while (Lex.getKind() != lltok::rbrace)
5876     if (parseUseListOrder(&PFS))
5877       return true;
5878 
5879   // Eat the }.
5880   Lex.Lex();
5881 
5882   // Verify function is ok.
5883   return PFS.finishFunction();
5884 }
5885 
5886 /// parseBasicBlock
5887 ///   ::= (LabelStr|LabelID)? Instruction*
5888 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
5889   // If this basic block starts out with a name, remember it.
5890   std::string Name;
5891   int NameID = -1;
5892   LocTy NameLoc = Lex.getLoc();
5893   if (Lex.getKind() == lltok::LabelStr) {
5894     Name = Lex.getStrVal();
5895     Lex.Lex();
5896   } else if (Lex.getKind() == lltok::LabelID) {
5897     NameID = Lex.getUIntVal();
5898     Lex.Lex();
5899   }
5900 
5901   BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
5902   if (!BB)
5903     return true;
5904 
5905   std::string NameStr;
5906 
5907   // parse the instructions in this block until we get a terminator.
5908   Instruction *Inst;
5909   do {
5910     // This instruction may have three possibilities for a name: a) none
5911     // specified, b) name specified "%foo =", c) number specified: "%4 =".
5912     LocTy NameLoc = Lex.getLoc();
5913     int NameID = -1;
5914     NameStr = "";
5915 
5916     if (Lex.getKind() == lltok::LocalVarID) {
5917       NameID = Lex.getUIntVal();
5918       Lex.Lex();
5919       if (parseToken(lltok::equal, "expected '=' after instruction id"))
5920         return true;
5921     } else if (Lex.getKind() == lltok::LocalVar) {
5922       NameStr = Lex.getStrVal();
5923       Lex.Lex();
5924       if (parseToken(lltok::equal, "expected '=' after instruction name"))
5925         return true;
5926     }
5927 
5928     switch (parseInstruction(Inst, BB, PFS)) {
5929     default:
5930       llvm_unreachable("Unknown parseInstruction result!");
5931     case InstError: return true;
5932     case InstNormal:
5933       BB->getInstList().push_back(Inst);
5934 
5935       // With a normal result, we check to see if the instruction is followed by
5936       // a comma and metadata.
5937       if (EatIfPresent(lltok::comma))
5938         if (parseInstructionMetadata(*Inst))
5939           return true;
5940       break;
5941     case InstExtraComma:
5942       BB->getInstList().push_back(Inst);
5943 
5944       // If the instruction parser ate an extra comma at the end of it, it
5945       // *must* be followed by metadata.
5946       if (parseInstructionMetadata(*Inst))
5947         return true;
5948       break;
5949     }
5950 
5951     // Set the name on the instruction.
5952     if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
5953       return true;
5954   } while (!Inst->isTerminator());
5955 
5956   return false;
5957 }
5958 
5959 //===----------------------------------------------------------------------===//
5960 // Instruction Parsing.
5961 //===----------------------------------------------------------------------===//
5962 
5963 /// parseInstruction - parse one of the many different instructions.
5964 ///
5965 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
5966                                PerFunctionState &PFS) {
5967   lltok::Kind Token = Lex.getKind();
5968   if (Token == lltok::Eof)
5969     return tokError("found end of file when expecting more instructions");
5970   LocTy Loc = Lex.getLoc();
5971   unsigned KeywordVal = Lex.getUIntVal();
5972   Lex.Lex();  // Eat the keyword.
5973 
5974   switch (Token) {
5975   default:
5976     return error(Loc, "expected instruction opcode");
5977   // Terminator Instructions.
5978   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5979   case lltok::kw_ret:
5980     return parseRet(Inst, BB, PFS);
5981   case lltok::kw_br:
5982     return parseBr(Inst, PFS);
5983   case lltok::kw_switch:
5984     return parseSwitch(Inst, PFS);
5985   case lltok::kw_indirectbr:
5986     return parseIndirectBr(Inst, PFS);
5987   case lltok::kw_invoke:
5988     return parseInvoke(Inst, PFS);
5989   case lltok::kw_resume:
5990     return parseResume(Inst, PFS);
5991   case lltok::kw_cleanupret:
5992     return parseCleanupRet(Inst, PFS);
5993   case lltok::kw_catchret:
5994     return parseCatchRet(Inst, PFS);
5995   case lltok::kw_catchswitch:
5996     return parseCatchSwitch(Inst, PFS);
5997   case lltok::kw_catchpad:
5998     return parseCatchPad(Inst, PFS);
5999   case lltok::kw_cleanuppad:
6000     return parseCleanupPad(Inst, PFS);
6001   case lltok::kw_callbr:
6002     return parseCallBr(Inst, PFS);
6003   // Unary Operators.
6004   case lltok::kw_fneg: {
6005     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6006     int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6007     if (Res != 0)
6008       return Res;
6009     if (FMF.any())
6010       Inst->setFastMathFlags(FMF);
6011     return false;
6012   }
6013   // Binary Operators.
6014   case lltok::kw_add:
6015   case lltok::kw_sub:
6016   case lltok::kw_mul:
6017   case lltok::kw_shl: {
6018     bool NUW = EatIfPresent(lltok::kw_nuw);
6019     bool NSW = EatIfPresent(lltok::kw_nsw);
6020     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6021 
6022     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6023       return true;
6024 
6025     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6026     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6027     return false;
6028   }
6029   case lltok::kw_fadd:
6030   case lltok::kw_fsub:
6031   case lltok::kw_fmul:
6032   case lltok::kw_fdiv:
6033   case lltok::kw_frem: {
6034     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6035     int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6036     if (Res != 0)
6037       return Res;
6038     if (FMF.any())
6039       Inst->setFastMathFlags(FMF);
6040     return 0;
6041   }
6042 
6043   case lltok::kw_sdiv:
6044   case lltok::kw_udiv:
6045   case lltok::kw_lshr:
6046   case lltok::kw_ashr: {
6047     bool Exact = EatIfPresent(lltok::kw_exact);
6048 
6049     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6050       return true;
6051     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6052     return false;
6053   }
6054 
6055   case lltok::kw_urem:
6056   case lltok::kw_srem:
6057     return parseArithmetic(Inst, PFS, KeywordVal,
6058                            /*IsFP*/ false);
6059   case lltok::kw_and:
6060   case lltok::kw_or:
6061   case lltok::kw_xor:
6062     return parseLogical(Inst, PFS, KeywordVal);
6063   case lltok::kw_icmp:
6064     return parseCompare(Inst, PFS, KeywordVal);
6065   case lltok::kw_fcmp: {
6066     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6067     int Res = parseCompare(Inst, PFS, KeywordVal);
6068     if (Res != 0)
6069       return Res;
6070     if (FMF.any())
6071       Inst->setFastMathFlags(FMF);
6072     return 0;
6073   }
6074 
6075   // Casts.
6076   case lltok::kw_trunc:
6077   case lltok::kw_zext:
6078   case lltok::kw_sext:
6079   case lltok::kw_fptrunc:
6080   case lltok::kw_fpext:
6081   case lltok::kw_bitcast:
6082   case lltok::kw_addrspacecast:
6083   case lltok::kw_uitofp:
6084   case lltok::kw_sitofp:
6085   case lltok::kw_fptoui:
6086   case lltok::kw_fptosi:
6087   case lltok::kw_inttoptr:
6088   case lltok::kw_ptrtoint:
6089     return parseCast(Inst, PFS, KeywordVal);
6090   // Other.
6091   case lltok::kw_select: {
6092     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6093     int Res = parseSelect(Inst, PFS);
6094     if (Res != 0)
6095       return Res;
6096     if (FMF.any()) {
6097       if (!isa<FPMathOperator>(Inst))
6098         return error(Loc, "fast-math-flags specified for select without "
6099                           "floating-point scalar or vector return type");
6100       Inst->setFastMathFlags(FMF);
6101     }
6102     return 0;
6103   }
6104   case lltok::kw_va_arg:
6105     return parseVAArg(Inst, PFS);
6106   case lltok::kw_extractelement:
6107     return parseExtractElement(Inst, PFS);
6108   case lltok::kw_insertelement:
6109     return parseInsertElement(Inst, PFS);
6110   case lltok::kw_shufflevector:
6111     return parseShuffleVector(Inst, PFS);
6112   case lltok::kw_phi: {
6113     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6114     int Res = parsePHI(Inst, PFS);
6115     if (Res != 0)
6116       return Res;
6117     if (FMF.any()) {
6118       if (!isa<FPMathOperator>(Inst))
6119         return error(Loc, "fast-math-flags specified for phi without "
6120                           "floating-point scalar or vector return type");
6121       Inst->setFastMathFlags(FMF);
6122     }
6123     return 0;
6124   }
6125   case lltok::kw_landingpad:
6126     return parseLandingPad(Inst, PFS);
6127   case lltok::kw_freeze:
6128     return parseFreeze(Inst, PFS);
6129   // Call.
6130   case lltok::kw_call:
6131     return parseCall(Inst, PFS, CallInst::TCK_None);
6132   case lltok::kw_tail:
6133     return parseCall(Inst, PFS, CallInst::TCK_Tail);
6134   case lltok::kw_musttail:
6135     return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6136   case lltok::kw_notail:
6137     return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6138   // Memory.
6139   case lltok::kw_alloca:
6140     return parseAlloc(Inst, PFS);
6141   case lltok::kw_load:
6142     return parseLoad(Inst, PFS);
6143   case lltok::kw_store:
6144     return parseStore(Inst, PFS);
6145   case lltok::kw_cmpxchg:
6146     return parseCmpXchg(Inst, PFS);
6147   case lltok::kw_atomicrmw:
6148     return parseAtomicRMW(Inst, PFS);
6149   case lltok::kw_fence:
6150     return parseFence(Inst, PFS);
6151   case lltok::kw_getelementptr:
6152     return parseGetElementPtr(Inst, PFS);
6153   case lltok::kw_extractvalue:
6154     return parseExtractValue(Inst, PFS);
6155   case lltok::kw_insertvalue:
6156     return parseInsertValue(Inst, PFS);
6157   }
6158 }
6159 
6160 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6161 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6162   if (Opc == Instruction::FCmp) {
6163     switch (Lex.getKind()) {
6164     default:
6165       return tokError("expected fcmp predicate (e.g. 'oeq')");
6166     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6167     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6168     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6169     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6170     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6171     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6172     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6173     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6174     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6175     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6176     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6177     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6178     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6179     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6180     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6181     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6182     }
6183   } else {
6184     switch (Lex.getKind()) {
6185     default:
6186       return tokError("expected icmp predicate (e.g. 'eq')");
6187     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
6188     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
6189     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6190     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6191     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6192     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6193     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6194     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6195     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6196     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6197     }
6198   }
6199   Lex.Lex();
6200   return false;
6201 }
6202 
6203 //===----------------------------------------------------------------------===//
6204 // Terminator Instructions.
6205 //===----------------------------------------------------------------------===//
6206 
6207 /// parseRet - parse a return instruction.
6208 ///   ::= 'ret' void (',' !dbg, !1)*
6209 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
6210 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6211                         PerFunctionState &PFS) {
6212   SMLoc TypeLoc = Lex.getLoc();
6213   Type *Ty = nullptr;
6214   if (parseType(Ty, true /*void allowed*/))
6215     return true;
6216 
6217   Type *ResType = PFS.getFunction().getReturnType();
6218 
6219   if (Ty->isVoidTy()) {
6220     if (!ResType->isVoidTy())
6221       return error(TypeLoc, "value doesn't match function result type '" +
6222                                 getTypeString(ResType) + "'");
6223 
6224     Inst = ReturnInst::Create(Context);
6225     return false;
6226   }
6227 
6228   Value *RV;
6229   if (parseValue(Ty, RV, PFS))
6230     return true;
6231 
6232   if (ResType != RV->getType())
6233     return error(TypeLoc, "value doesn't match function result type '" +
6234                               getTypeString(ResType) + "'");
6235 
6236   Inst = ReturnInst::Create(Context, RV);
6237   return false;
6238 }
6239 
6240 /// parseBr
6241 ///   ::= 'br' TypeAndValue
6242 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6243 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6244   LocTy Loc, Loc2;
6245   Value *Op0;
6246   BasicBlock *Op1, *Op2;
6247   if (parseTypeAndValue(Op0, Loc, PFS))
6248     return true;
6249 
6250   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6251     Inst = BranchInst::Create(BB);
6252     return false;
6253   }
6254 
6255   if (Op0->getType() != Type::getInt1Ty(Context))
6256     return error(Loc, "branch condition must have 'i1' type");
6257 
6258   if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6259       parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6260       parseToken(lltok::comma, "expected ',' after true destination") ||
6261       parseTypeAndBasicBlock(Op2, Loc2, PFS))
6262     return true;
6263 
6264   Inst = BranchInst::Create(Op1, Op2, Op0);
6265   return false;
6266 }
6267 
6268 /// parseSwitch
6269 ///  Instruction
6270 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6271 ///  JumpTable
6272 ///    ::= (TypeAndValue ',' TypeAndValue)*
6273 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6274   LocTy CondLoc, BBLoc;
6275   Value *Cond;
6276   BasicBlock *DefaultBB;
6277   if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6278       parseToken(lltok::comma, "expected ',' after switch condition") ||
6279       parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6280       parseToken(lltok::lsquare, "expected '[' with switch table"))
6281     return true;
6282 
6283   if (!Cond->getType()->isIntegerTy())
6284     return error(CondLoc, "switch condition must have integer type");
6285 
6286   // parse the jump table pairs.
6287   SmallPtrSet<Value*, 32> SeenCases;
6288   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6289   while (Lex.getKind() != lltok::rsquare) {
6290     Value *Constant;
6291     BasicBlock *DestBB;
6292 
6293     if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6294         parseToken(lltok::comma, "expected ',' after case value") ||
6295         parseTypeAndBasicBlock(DestBB, PFS))
6296       return true;
6297 
6298     if (!SeenCases.insert(Constant).second)
6299       return error(CondLoc, "duplicate case value in switch");
6300     if (!isa<ConstantInt>(Constant))
6301       return error(CondLoc, "case value is not a constant integer");
6302 
6303     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6304   }
6305 
6306   Lex.Lex();  // Eat the ']'.
6307 
6308   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6309   for (unsigned i = 0, e = Table.size(); i != e; ++i)
6310     SI->addCase(Table[i].first, Table[i].second);
6311   Inst = SI;
6312   return false;
6313 }
6314 
6315 /// parseIndirectBr
6316 ///  Instruction
6317 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6318 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6319   LocTy AddrLoc;
6320   Value *Address;
6321   if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6322       parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6323       parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6324     return true;
6325 
6326   if (!Address->getType()->isPointerTy())
6327     return error(AddrLoc, "indirectbr address must have pointer type");
6328 
6329   // parse the destination list.
6330   SmallVector<BasicBlock*, 16> DestList;
6331 
6332   if (Lex.getKind() != lltok::rsquare) {
6333     BasicBlock *DestBB;
6334     if (parseTypeAndBasicBlock(DestBB, PFS))
6335       return true;
6336     DestList.push_back(DestBB);
6337 
6338     while (EatIfPresent(lltok::comma)) {
6339       if (parseTypeAndBasicBlock(DestBB, PFS))
6340         return true;
6341       DestList.push_back(DestBB);
6342     }
6343   }
6344 
6345   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6346     return true;
6347 
6348   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6349   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6350     IBI->addDestination(DestList[i]);
6351   Inst = IBI;
6352   return false;
6353 }
6354 
6355 /// parseInvoke
6356 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6357 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6358 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6359   LocTy CallLoc = Lex.getLoc();
6360   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6361   std::vector<unsigned> FwdRefAttrGrps;
6362   LocTy NoBuiltinLoc;
6363   unsigned CC;
6364   unsigned InvokeAddrSpace;
6365   Type *RetType = nullptr;
6366   LocTy RetTypeLoc;
6367   ValID CalleeID;
6368   SmallVector<ParamInfo, 16> ArgList;
6369   SmallVector<OperandBundleDef, 2> BundleList;
6370 
6371   BasicBlock *NormalBB, *UnwindBB;
6372   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6373       parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6374       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6375       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6376       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6377                                  NoBuiltinLoc) ||
6378       parseOptionalOperandBundles(BundleList, PFS) ||
6379       parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6380       parseTypeAndBasicBlock(NormalBB, PFS) ||
6381       parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6382       parseTypeAndBasicBlock(UnwindBB, PFS))
6383     return true;
6384 
6385   // If RetType is a non-function pointer type, then this is the short syntax
6386   // for the call, which means that RetType is just the return type.  Infer the
6387   // rest of the function argument types from the arguments that are present.
6388   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6389   if (!Ty) {
6390     // Pull out the types of all of the arguments...
6391     std::vector<Type*> ParamTypes;
6392     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6393       ParamTypes.push_back(ArgList[i].V->getType());
6394 
6395     if (!FunctionType::isValidReturnType(RetType))
6396       return error(RetTypeLoc, "Invalid result type for LLVM function");
6397 
6398     Ty = FunctionType::get(RetType, ParamTypes, false);
6399   }
6400 
6401   CalleeID.FTy = Ty;
6402 
6403   // Look up the callee.
6404   Value *Callee;
6405   if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6406                           Callee, &PFS))
6407     return true;
6408 
6409   // Set up the Attribute for the function.
6410   SmallVector<Value *, 8> Args;
6411   SmallVector<AttributeSet, 8> ArgAttrs;
6412 
6413   // Loop through FunctionType's arguments and ensure they are specified
6414   // correctly.  Also, gather any parameter attributes.
6415   FunctionType::param_iterator I = Ty->param_begin();
6416   FunctionType::param_iterator E = Ty->param_end();
6417   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6418     Type *ExpectedTy = nullptr;
6419     if (I != E) {
6420       ExpectedTy = *I++;
6421     } else if (!Ty->isVarArg()) {
6422       return error(ArgList[i].Loc, "too many arguments specified");
6423     }
6424 
6425     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6426       return error(ArgList[i].Loc, "argument is not of expected type '" +
6427                                        getTypeString(ExpectedTy) + "'");
6428     Args.push_back(ArgList[i].V);
6429     ArgAttrs.push_back(ArgList[i].Attrs);
6430   }
6431 
6432   if (I != E)
6433     return error(CallLoc, "not enough parameters specified for call");
6434 
6435   if (FnAttrs.hasAlignmentAttr())
6436     return error(CallLoc, "invoke instructions may not have an alignment");
6437 
6438   // Finish off the Attribute and check them
6439   AttributeList PAL =
6440       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6441                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6442 
6443   InvokeInst *II =
6444       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6445   II->setCallingConv(CC);
6446   II->setAttributes(PAL);
6447   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6448   Inst = II;
6449   return false;
6450 }
6451 
6452 /// parseResume
6453 ///   ::= 'resume' TypeAndValue
6454 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6455   Value *Exn; LocTy ExnLoc;
6456   if (parseTypeAndValue(Exn, ExnLoc, PFS))
6457     return true;
6458 
6459   ResumeInst *RI = ResumeInst::Create(Exn);
6460   Inst = RI;
6461   return false;
6462 }
6463 
6464 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6465                                   PerFunctionState &PFS) {
6466   if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6467     return true;
6468 
6469   while (Lex.getKind() != lltok::rsquare) {
6470     // If this isn't the first argument, we need a comma.
6471     if (!Args.empty() &&
6472         parseToken(lltok::comma, "expected ',' in argument list"))
6473       return true;
6474 
6475     // parse the argument.
6476     LocTy ArgLoc;
6477     Type *ArgTy = nullptr;
6478     if (parseType(ArgTy, ArgLoc))
6479       return true;
6480 
6481     Value *V;
6482     if (ArgTy->isMetadataTy()) {
6483       if (parseMetadataAsValue(V, PFS))
6484         return true;
6485     } else {
6486       if (parseValue(ArgTy, V, PFS))
6487         return true;
6488     }
6489     Args.push_back(V);
6490   }
6491 
6492   Lex.Lex();  // Lex the ']'.
6493   return false;
6494 }
6495 
6496 /// parseCleanupRet
6497 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6498 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6499   Value *CleanupPad = nullptr;
6500 
6501   if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6502     return true;
6503 
6504   if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6505     return true;
6506 
6507   if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6508     return true;
6509 
6510   BasicBlock *UnwindBB = nullptr;
6511   if (Lex.getKind() == lltok::kw_to) {
6512     Lex.Lex();
6513     if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6514       return true;
6515   } else {
6516     if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6517       return true;
6518     }
6519   }
6520 
6521   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6522   return false;
6523 }
6524 
6525 /// parseCatchRet
6526 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
6527 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6528   Value *CatchPad = nullptr;
6529 
6530   if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6531     return true;
6532 
6533   if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6534     return true;
6535 
6536   BasicBlock *BB;
6537   if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6538       parseTypeAndBasicBlock(BB, PFS))
6539     return true;
6540 
6541   Inst = CatchReturnInst::Create(CatchPad, BB);
6542   return false;
6543 }
6544 
6545 /// parseCatchSwitch
6546 ///   ::= 'catchswitch' within Parent
6547 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6548   Value *ParentPad;
6549 
6550   if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6551     return true;
6552 
6553   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6554       Lex.getKind() != lltok::LocalVarID)
6555     return tokError("expected scope value for catchswitch");
6556 
6557   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6558     return true;
6559 
6560   if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6561     return true;
6562 
6563   SmallVector<BasicBlock *, 32> Table;
6564   do {
6565     BasicBlock *DestBB;
6566     if (parseTypeAndBasicBlock(DestBB, PFS))
6567       return true;
6568     Table.push_back(DestBB);
6569   } while (EatIfPresent(lltok::comma));
6570 
6571   if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6572     return true;
6573 
6574   if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6575     return true;
6576 
6577   BasicBlock *UnwindBB = nullptr;
6578   if (EatIfPresent(lltok::kw_to)) {
6579     if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6580       return true;
6581   } else {
6582     if (parseTypeAndBasicBlock(UnwindBB, PFS))
6583       return true;
6584   }
6585 
6586   auto *CatchSwitch =
6587       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6588   for (BasicBlock *DestBB : Table)
6589     CatchSwitch->addHandler(DestBB);
6590   Inst = CatchSwitch;
6591   return false;
6592 }
6593 
6594 /// parseCatchPad
6595 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6596 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6597   Value *CatchSwitch = nullptr;
6598 
6599   if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6600     return true;
6601 
6602   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6603     return tokError("expected scope value for catchpad");
6604 
6605   if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6606     return true;
6607 
6608   SmallVector<Value *, 8> Args;
6609   if (parseExceptionArgs(Args, PFS))
6610     return true;
6611 
6612   Inst = CatchPadInst::Create(CatchSwitch, Args);
6613   return false;
6614 }
6615 
6616 /// parseCleanupPad
6617 ///   ::= 'cleanuppad' within Parent ParamList
6618 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6619   Value *ParentPad = nullptr;
6620 
6621   if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6622     return true;
6623 
6624   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6625       Lex.getKind() != lltok::LocalVarID)
6626     return tokError("expected scope value for cleanuppad");
6627 
6628   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6629     return true;
6630 
6631   SmallVector<Value *, 8> Args;
6632   if (parseExceptionArgs(Args, PFS))
6633     return true;
6634 
6635   Inst = CleanupPadInst::Create(ParentPad, Args);
6636   return false;
6637 }
6638 
6639 //===----------------------------------------------------------------------===//
6640 // Unary Operators.
6641 //===----------------------------------------------------------------------===//
6642 
6643 /// parseUnaryOp
6644 ///  ::= UnaryOp TypeAndValue ',' Value
6645 ///
6646 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6647 /// operand is allowed.
6648 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6649                             unsigned Opc, bool IsFP) {
6650   LocTy Loc; Value *LHS;
6651   if (parseTypeAndValue(LHS, Loc, PFS))
6652     return true;
6653 
6654   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6655                     : LHS->getType()->isIntOrIntVectorTy();
6656 
6657   if (!Valid)
6658     return error(Loc, "invalid operand type for instruction");
6659 
6660   Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6661   return false;
6662 }
6663 
6664 /// parseCallBr
6665 ///   ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6666 ///       OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6667 ///       '[' LabelList ']'
6668 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6669   LocTy CallLoc = Lex.getLoc();
6670   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6671   std::vector<unsigned> FwdRefAttrGrps;
6672   LocTy NoBuiltinLoc;
6673   unsigned CC;
6674   Type *RetType = nullptr;
6675   LocTy RetTypeLoc;
6676   ValID CalleeID;
6677   SmallVector<ParamInfo, 16> ArgList;
6678   SmallVector<OperandBundleDef, 2> BundleList;
6679 
6680   BasicBlock *DefaultDest;
6681   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6682       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6683       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6684       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6685                                  NoBuiltinLoc) ||
6686       parseOptionalOperandBundles(BundleList, PFS) ||
6687       parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6688       parseTypeAndBasicBlock(DefaultDest, PFS) ||
6689       parseToken(lltok::lsquare, "expected '[' in callbr"))
6690     return true;
6691 
6692   // parse the destination list.
6693   SmallVector<BasicBlock *, 16> IndirectDests;
6694 
6695   if (Lex.getKind() != lltok::rsquare) {
6696     BasicBlock *DestBB;
6697     if (parseTypeAndBasicBlock(DestBB, PFS))
6698       return true;
6699     IndirectDests.push_back(DestBB);
6700 
6701     while (EatIfPresent(lltok::comma)) {
6702       if (parseTypeAndBasicBlock(DestBB, PFS))
6703         return true;
6704       IndirectDests.push_back(DestBB);
6705     }
6706   }
6707 
6708   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6709     return true;
6710 
6711   // If RetType is a non-function pointer type, then this is the short syntax
6712   // for the call, which means that RetType is just the return type.  Infer the
6713   // rest of the function argument types from the arguments that are present.
6714   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6715   if (!Ty) {
6716     // Pull out the types of all of the arguments...
6717     std::vector<Type *> ParamTypes;
6718     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6719       ParamTypes.push_back(ArgList[i].V->getType());
6720 
6721     if (!FunctionType::isValidReturnType(RetType))
6722       return error(RetTypeLoc, "Invalid result type for LLVM function");
6723 
6724     Ty = FunctionType::get(RetType, ParamTypes, false);
6725   }
6726 
6727   CalleeID.FTy = Ty;
6728 
6729   // Look up the callee.
6730   Value *Callee;
6731   if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6732     return true;
6733 
6734   // Set up the Attribute for the function.
6735   SmallVector<Value *, 8> Args;
6736   SmallVector<AttributeSet, 8> ArgAttrs;
6737 
6738   // Loop through FunctionType's arguments and ensure they are specified
6739   // correctly.  Also, gather any parameter attributes.
6740   FunctionType::param_iterator I = Ty->param_begin();
6741   FunctionType::param_iterator E = Ty->param_end();
6742   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6743     Type *ExpectedTy = nullptr;
6744     if (I != E) {
6745       ExpectedTy = *I++;
6746     } else if (!Ty->isVarArg()) {
6747       return error(ArgList[i].Loc, "too many arguments specified");
6748     }
6749 
6750     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6751       return error(ArgList[i].Loc, "argument is not of expected type '" +
6752                                        getTypeString(ExpectedTy) + "'");
6753     Args.push_back(ArgList[i].V);
6754     ArgAttrs.push_back(ArgList[i].Attrs);
6755   }
6756 
6757   if (I != E)
6758     return error(CallLoc, "not enough parameters specified for call");
6759 
6760   if (FnAttrs.hasAlignmentAttr())
6761     return error(CallLoc, "callbr instructions may not have an alignment");
6762 
6763   // Finish off the Attribute and check them
6764   AttributeList PAL =
6765       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6766                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6767 
6768   CallBrInst *CBI =
6769       CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6770                          BundleList);
6771   CBI->setCallingConv(CC);
6772   CBI->setAttributes(PAL);
6773   ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6774   Inst = CBI;
6775   return false;
6776 }
6777 
6778 //===----------------------------------------------------------------------===//
6779 // Binary Operators.
6780 //===----------------------------------------------------------------------===//
6781 
6782 /// parseArithmetic
6783 ///  ::= ArithmeticOps TypeAndValue ',' Value
6784 ///
6785 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6786 /// operand is allowed.
6787 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6788                                unsigned Opc, bool IsFP) {
6789   LocTy Loc; Value *LHS, *RHS;
6790   if (parseTypeAndValue(LHS, Loc, PFS) ||
6791       parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6792       parseValue(LHS->getType(), RHS, PFS))
6793     return true;
6794 
6795   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6796                     : LHS->getType()->isIntOrIntVectorTy();
6797 
6798   if (!Valid)
6799     return error(Loc, "invalid operand type for instruction");
6800 
6801   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6802   return false;
6803 }
6804 
6805 /// parseLogical
6806 ///  ::= ArithmeticOps TypeAndValue ',' Value {
6807 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6808                             unsigned Opc) {
6809   LocTy Loc; Value *LHS, *RHS;
6810   if (parseTypeAndValue(LHS, Loc, PFS) ||
6811       parseToken(lltok::comma, "expected ',' in logical operation") ||
6812       parseValue(LHS->getType(), RHS, PFS))
6813     return true;
6814 
6815   if (!LHS->getType()->isIntOrIntVectorTy())
6816     return error(Loc,
6817                  "instruction requires integer or integer vector operands");
6818 
6819   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6820   return false;
6821 }
6822 
6823 /// parseCompare
6824 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
6825 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
6826 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
6827                             unsigned Opc) {
6828   // parse the integer/fp comparison predicate.
6829   LocTy Loc;
6830   unsigned Pred;
6831   Value *LHS, *RHS;
6832   if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
6833       parseToken(lltok::comma, "expected ',' after compare value") ||
6834       parseValue(LHS->getType(), RHS, PFS))
6835     return true;
6836 
6837   if (Opc == Instruction::FCmp) {
6838     if (!LHS->getType()->isFPOrFPVectorTy())
6839       return error(Loc, "fcmp requires floating point operands");
6840     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6841   } else {
6842     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6843     if (!LHS->getType()->isIntOrIntVectorTy() &&
6844         !LHS->getType()->isPtrOrPtrVectorTy())
6845       return error(Loc, "icmp requires integer operands");
6846     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6847   }
6848   return false;
6849 }
6850 
6851 //===----------------------------------------------------------------------===//
6852 // Other Instructions.
6853 //===----------------------------------------------------------------------===//
6854 
6855 /// parseCast
6856 ///   ::= CastOpc TypeAndValue 'to' Type
6857 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
6858                          unsigned Opc) {
6859   LocTy Loc;
6860   Value *Op;
6861   Type *DestTy = nullptr;
6862   if (parseTypeAndValue(Op, Loc, PFS) ||
6863       parseToken(lltok::kw_to, "expected 'to' after cast value") ||
6864       parseType(DestTy))
6865     return true;
6866 
6867   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6868     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6869     return error(Loc, "invalid cast opcode for cast from '" +
6870                           getTypeString(Op->getType()) + "' to '" +
6871                           getTypeString(DestTy) + "'");
6872   }
6873   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6874   return false;
6875 }
6876 
6877 /// parseSelect
6878 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6879 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6880   LocTy Loc;
6881   Value *Op0, *Op1, *Op2;
6882   if (parseTypeAndValue(Op0, Loc, PFS) ||
6883       parseToken(lltok::comma, "expected ',' after select condition") ||
6884       parseTypeAndValue(Op1, PFS) ||
6885       parseToken(lltok::comma, "expected ',' after select value") ||
6886       parseTypeAndValue(Op2, PFS))
6887     return true;
6888 
6889   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6890     return error(Loc, Reason);
6891 
6892   Inst = SelectInst::Create(Op0, Op1, Op2);
6893   return false;
6894 }
6895 
6896 /// parseVAArg
6897 ///   ::= 'va_arg' TypeAndValue ',' Type
6898 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
6899   Value *Op;
6900   Type *EltTy = nullptr;
6901   LocTy TypeLoc;
6902   if (parseTypeAndValue(Op, PFS) ||
6903       parseToken(lltok::comma, "expected ',' after vaarg operand") ||
6904       parseType(EltTy, TypeLoc))
6905     return true;
6906 
6907   if (!EltTy->isFirstClassType())
6908     return error(TypeLoc, "va_arg requires operand with first class type");
6909 
6910   Inst = new VAArgInst(Op, EltTy);
6911   return false;
6912 }
6913 
6914 /// parseExtractElement
6915 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
6916 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6917   LocTy Loc;
6918   Value *Op0, *Op1;
6919   if (parseTypeAndValue(Op0, Loc, PFS) ||
6920       parseToken(lltok::comma, "expected ',' after extract value") ||
6921       parseTypeAndValue(Op1, PFS))
6922     return true;
6923 
6924   if (!ExtractElementInst::isValidOperands(Op0, Op1))
6925     return error(Loc, "invalid extractelement operands");
6926 
6927   Inst = ExtractElementInst::Create(Op0, Op1);
6928   return false;
6929 }
6930 
6931 /// parseInsertElement
6932 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6933 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6934   LocTy Loc;
6935   Value *Op0, *Op1, *Op2;
6936   if (parseTypeAndValue(Op0, Loc, PFS) ||
6937       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6938       parseTypeAndValue(Op1, PFS) ||
6939       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6940       parseTypeAndValue(Op2, PFS))
6941     return true;
6942 
6943   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6944     return error(Loc, "invalid insertelement operands");
6945 
6946   Inst = InsertElementInst::Create(Op0, Op1, Op2);
6947   return false;
6948 }
6949 
6950 /// parseShuffleVector
6951 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6952 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6953   LocTy Loc;
6954   Value *Op0, *Op1, *Op2;
6955   if (parseTypeAndValue(Op0, Loc, PFS) ||
6956       parseToken(lltok::comma, "expected ',' after shuffle mask") ||
6957       parseTypeAndValue(Op1, PFS) ||
6958       parseToken(lltok::comma, "expected ',' after shuffle value") ||
6959       parseTypeAndValue(Op2, PFS))
6960     return true;
6961 
6962   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6963     return error(Loc, "invalid shufflevector operands");
6964 
6965   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6966   return false;
6967 }
6968 
6969 /// parsePHI
6970 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6971 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6972   Type *Ty = nullptr;  LocTy TypeLoc;
6973   Value *Op0, *Op1;
6974 
6975   if (parseType(Ty, TypeLoc) ||
6976       parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6977       parseValue(Ty, Op0, PFS) ||
6978       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6979       parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6980       parseToken(lltok::rsquare, "expected ']' in phi value list"))
6981     return true;
6982 
6983   bool AteExtraComma = false;
6984   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6985 
6986   while (true) {
6987     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6988 
6989     if (!EatIfPresent(lltok::comma))
6990       break;
6991 
6992     if (Lex.getKind() == lltok::MetadataVar) {
6993       AteExtraComma = true;
6994       break;
6995     }
6996 
6997     if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6998         parseValue(Ty, Op0, PFS) ||
6999         parseToken(lltok::comma, "expected ',' after insertelement value") ||
7000         parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7001         parseToken(lltok::rsquare, "expected ']' in phi value list"))
7002       return true;
7003   }
7004 
7005   if (!Ty->isFirstClassType())
7006     return error(TypeLoc, "phi node must have first class type");
7007 
7008   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7009   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7010     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7011   Inst = PN;
7012   return AteExtraComma ? InstExtraComma : InstNormal;
7013 }
7014 
7015 /// parseLandingPad
7016 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7017 /// Clause
7018 ///   ::= 'catch' TypeAndValue
7019 ///   ::= 'filter'
7020 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7021 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7022   Type *Ty = nullptr; LocTy TyLoc;
7023 
7024   if (parseType(Ty, TyLoc))
7025     return true;
7026 
7027   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7028   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7029 
7030   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7031     LandingPadInst::ClauseType CT;
7032     if (EatIfPresent(lltok::kw_catch))
7033       CT = LandingPadInst::Catch;
7034     else if (EatIfPresent(lltok::kw_filter))
7035       CT = LandingPadInst::Filter;
7036     else
7037       return tokError("expected 'catch' or 'filter' clause type");
7038 
7039     Value *V;
7040     LocTy VLoc;
7041     if (parseTypeAndValue(V, VLoc, PFS))
7042       return true;
7043 
7044     // A 'catch' type expects a non-array constant. A filter clause expects an
7045     // array constant.
7046     if (CT == LandingPadInst::Catch) {
7047       if (isa<ArrayType>(V->getType()))
7048         error(VLoc, "'catch' clause has an invalid type");
7049     } else {
7050       if (!isa<ArrayType>(V->getType()))
7051         error(VLoc, "'filter' clause has an invalid type");
7052     }
7053 
7054     Constant *CV = dyn_cast<Constant>(V);
7055     if (!CV)
7056       return error(VLoc, "clause argument must be a constant");
7057     LP->addClause(CV);
7058   }
7059 
7060   Inst = LP.release();
7061   return false;
7062 }
7063 
7064 /// parseFreeze
7065 ///   ::= 'freeze' Type Value
7066 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7067   LocTy Loc;
7068   Value *Op;
7069   if (parseTypeAndValue(Op, Loc, PFS))
7070     return true;
7071 
7072   Inst = new FreezeInst(Op);
7073   return false;
7074 }
7075 
7076 /// parseCall
7077 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
7078 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7079 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7080 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7081 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7082 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7083 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
7084 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7085 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7086                          CallInst::TailCallKind TCK) {
7087   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7088   std::vector<unsigned> FwdRefAttrGrps;
7089   LocTy BuiltinLoc;
7090   unsigned CallAddrSpace;
7091   unsigned CC;
7092   Type *RetType = nullptr;
7093   LocTy RetTypeLoc;
7094   ValID CalleeID;
7095   SmallVector<ParamInfo, 16> ArgList;
7096   SmallVector<OperandBundleDef, 2> BundleList;
7097   LocTy CallLoc = Lex.getLoc();
7098 
7099   if (TCK != CallInst::TCK_None &&
7100       parseToken(lltok::kw_call,
7101                  "expected 'tail call', 'musttail call', or 'notail call'"))
7102     return true;
7103 
7104   FastMathFlags FMF = EatFastMathFlagsIfPresent();
7105 
7106   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7107       parseOptionalProgramAddrSpace(CallAddrSpace) ||
7108       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7109       parseValID(CalleeID, &PFS) ||
7110       parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7111                          PFS.getFunction().isVarArg()) ||
7112       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7113       parseOptionalOperandBundles(BundleList, PFS))
7114     return true;
7115 
7116   // If RetType is a non-function pointer type, then this is the short syntax
7117   // for the call, which means that RetType is just the return type.  Infer the
7118   // rest of the function argument types from the arguments that are present.
7119   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
7120   if (!Ty) {
7121     // Pull out the types of all of the arguments...
7122     std::vector<Type*> ParamTypes;
7123     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7124       ParamTypes.push_back(ArgList[i].V->getType());
7125 
7126     if (!FunctionType::isValidReturnType(RetType))
7127       return error(RetTypeLoc, "Invalid result type for LLVM function");
7128 
7129     Ty = FunctionType::get(RetType, ParamTypes, false);
7130   }
7131 
7132   CalleeID.FTy = Ty;
7133 
7134   // Look up the callee.
7135   Value *Callee;
7136   if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7137                           &PFS))
7138     return true;
7139 
7140   // Set up the Attribute for the function.
7141   SmallVector<AttributeSet, 8> Attrs;
7142 
7143   SmallVector<Value*, 8> Args;
7144 
7145   // Loop through FunctionType's arguments and ensure they are specified
7146   // correctly.  Also, gather any parameter attributes.
7147   FunctionType::param_iterator I = Ty->param_begin();
7148   FunctionType::param_iterator E = Ty->param_end();
7149   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7150     Type *ExpectedTy = nullptr;
7151     if (I != E) {
7152       ExpectedTy = *I++;
7153     } else if (!Ty->isVarArg()) {
7154       return error(ArgList[i].Loc, "too many arguments specified");
7155     }
7156 
7157     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7158       return error(ArgList[i].Loc, "argument is not of expected type '" +
7159                                        getTypeString(ExpectedTy) + "'");
7160     Args.push_back(ArgList[i].V);
7161     Attrs.push_back(ArgList[i].Attrs);
7162   }
7163 
7164   if (I != E)
7165     return error(CallLoc, "not enough parameters specified for call");
7166 
7167   if (FnAttrs.hasAlignmentAttr())
7168     return error(CallLoc, "call instructions may not have an alignment");
7169 
7170   // Finish off the Attribute and check them
7171   AttributeList PAL =
7172       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7173                          AttributeSet::get(Context, RetAttrs), Attrs);
7174 
7175   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7176   CI->setTailCallKind(TCK);
7177   CI->setCallingConv(CC);
7178   if (FMF.any()) {
7179     if (!isa<FPMathOperator>(CI)) {
7180       CI->deleteValue();
7181       return error(CallLoc, "fast-math-flags specified for call without "
7182                             "floating-point scalar or vector return type");
7183     }
7184     CI->setFastMathFlags(FMF);
7185   }
7186   CI->setAttributes(PAL);
7187   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7188   Inst = CI;
7189   return false;
7190 }
7191 
7192 //===----------------------------------------------------------------------===//
7193 // Memory Instructions.
7194 //===----------------------------------------------------------------------===//
7195 
7196 /// parseAlloc
7197 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7198 ///       (',' 'align' i32)? (',', 'addrspace(n))?
7199 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7200   Value *Size = nullptr;
7201   LocTy SizeLoc, TyLoc, ASLoc;
7202   MaybeAlign Alignment;
7203   unsigned AddrSpace = 0;
7204   Type *Ty = nullptr;
7205 
7206   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7207   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7208 
7209   if (parseType(Ty, TyLoc))
7210     return true;
7211 
7212   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7213     return error(TyLoc, "invalid type for alloca");
7214 
7215   bool AteExtraComma = false;
7216   if (EatIfPresent(lltok::comma)) {
7217     if (Lex.getKind() == lltok::kw_align) {
7218       if (parseOptionalAlignment(Alignment))
7219         return true;
7220       if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7221         return true;
7222     } else if (Lex.getKind() == lltok::kw_addrspace) {
7223       ASLoc = Lex.getLoc();
7224       if (parseOptionalAddrSpace(AddrSpace))
7225         return true;
7226     } else if (Lex.getKind() == lltok::MetadataVar) {
7227       AteExtraComma = true;
7228     } else {
7229       if (parseTypeAndValue(Size, SizeLoc, PFS))
7230         return true;
7231       if (EatIfPresent(lltok::comma)) {
7232         if (Lex.getKind() == lltok::kw_align) {
7233           if (parseOptionalAlignment(Alignment))
7234             return true;
7235           if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7236             return true;
7237         } else if (Lex.getKind() == lltok::kw_addrspace) {
7238           ASLoc = Lex.getLoc();
7239           if (parseOptionalAddrSpace(AddrSpace))
7240             return true;
7241         } else if (Lex.getKind() == lltok::MetadataVar) {
7242           AteExtraComma = true;
7243         }
7244       }
7245     }
7246   }
7247 
7248   if (Size && !Size->getType()->isIntegerTy())
7249     return error(SizeLoc, "element count must have integer type");
7250 
7251   SmallPtrSet<Type *, 4> Visited;
7252   if (!Alignment && !Ty->isSized(&Visited))
7253     return error(TyLoc, "Cannot allocate unsized type");
7254   if (!Alignment)
7255     Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7256   AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7257   AI->setUsedWithInAlloca(IsInAlloca);
7258   AI->setSwiftError(IsSwiftError);
7259   Inst = AI;
7260   return AteExtraComma ? InstExtraComma : InstNormal;
7261 }
7262 
7263 /// parseLoad
7264 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7265 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
7266 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7267 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7268   Value *Val; LocTy Loc;
7269   MaybeAlign Alignment;
7270   bool AteExtraComma = false;
7271   bool isAtomic = false;
7272   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7273   SyncScope::ID SSID = SyncScope::System;
7274 
7275   if (Lex.getKind() == lltok::kw_atomic) {
7276     isAtomic = true;
7277     Lex.Lex();
7278   }
7279 
7280   bool isVolatile = false;
7281   if (Lex.getKind() == lltok::kw_volatile) {
7282     isVolatile = true;
7283     Lex.Lex();
7284   }
7285 
7286   Type *Ty;
7287   LocTy ExplicitTypeLoc = Lex.getLoc();
7288   if (parseType(Ty) ||
7289       parseToken(lltok::comma, "expected comma after load's type") ||
7290       parseTypeAndValue(Val, Loc, PFS) ||
7291       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7292       parseOptionalCommaAlign(Alignment, AteExtraComma))
7293     return true;
7294 
7295   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7296     return error(Loc, "load operand must be a pointer to a first class type");
7297   if (isAtomic && !Alignment)
7298     return error(Loc, "atomic load must have explicit non-zero alignment");
7299   if (Ordering == AtomicOrdering::Release ||
7300       Ordering == AtomicOrdering::AcquireRelease)
7301     return error(Loc, "atomic load cannot use Release ordering");
7302 
7303   if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
7304     return error(
7305         ExplicitTypeLoc,
7306         typeComparisonErrorMessage(
7307             "explicit pointee type doesn't match operand's pointee type", Ty,
7308             Val->getType()->getNonOpaquePointerElementType()));
7309   }
7310   SmallPtrSet<Type *, 4> Visited;
7311   if (!Alignment && !Ty->isSized(&Visited))
7312     return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7313   if (!Alignment)
7314     Alignment = M->getDataLayout().getABITypeAlign(Ty);
7315   Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7316   return AteExtraComma ? InstExtraComma : InstNormal;
7317 }
7318 
7319 /// parseStore
7320 
7321 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7322 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7323 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7324 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7325   Value *Val, *Ptr; LocTy Loc, PtrLoc;
7326   MaybeAlign Alignment;
7327   bool AteExtraComma = false;
7328   bool isAtomic = false;
7329   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7330   SyncScope::ID SSID = SyncScope::System;
7331 
7332   if (Lex.getKind() == lltok::kw_atomic) {
7333     isAtomic = true;
7334     Lex.Lex();
7335   }
7336 
7337   bool isVolatile = false;
7338   if (Lex.getKind() == lltok::kw_volatile) {
7339     isVolatile = true;
7340     Lex.Lex();
7341   }
7342 
7343   if (parseTypeAndValue(Val, Loc, PFS) ||
7344       parseToken(lltok::comma, "expected ',' after store operand") ||
7345       parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7346       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7347       parseOptionalCommaAlign(Alignment, AteExtraComma))
7348     return true;
7349 
7350   if (!Ptr->getType()->isPointerTy())
7351     return error(PtrLoc, "store operand must be a pointer");
7352   if (!Val->getType()->isFirstClassType())
7353     return error(Loc, "store operand must be a first class value");
7354   if (!cast<PointerType>(Ptr->getType())
7355            ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7356     return error(Loc, "stored value and pointer type do not match");
7357   if (isAtomic && !Alignment)
7358     return error(Loc, "atomic store must have explicit non-zero alignment");
7359   if (Ordering == AtomicOrdering::Acquire ||
7360       Ordering == AtomicOrdering::AcquireRelease)
7361     return error(Loc, "atomic store cannot use Acquire ordering");
7362   SmallPtrSet<Type *, 4> Visited;
7363   if (!Alignment && !Val->getType()->isSized(&Visited))
7364     return error(Loc, "storing unsized types is not allowed");
7365   if (!Alignment)
7366     Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7367 
7368   Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7369   return AteExtraComma ? InstExtraComma : InstNormal;
7370 }
7371 
7372 /// parseCmpXchg
7373 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7374 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7375 ///       'Align'?
7376 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7377   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7378   bool AteExtraComma = false;
7379   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7380   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7381   SyncScope::ID SSID = SyncScope::System;
7382   bool isVolatile = false;
7383   bool isWeak = false;
7384   MaybeAlign Alignment;
7385 
7386   if (EatIfPresent(lltok::kw_weak))
7387     isWeak = true;
7388 
7389   if (EatIfPresent(lltok::kw_volatile))
7390     isVolatile = true;
7391 
7392   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7393       parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7394       parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7395       parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7396       parseTypeAndValue(New, NewLoc, PFS) ||
7397       parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7398       parseOrdering(FailureOrdering) ||
7399       parseOptionalCommaAlign(Alignment, AteExtraComma))
7400     return true;
7401 
7402   if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7403     return tokError("invalid cmpxchg success ordering");
7404   if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7405     return tokError("invalid cmpxchg failure ordering");
7406   if (!Ptr->getType()->isPointerTy())
7407     return error(PtrLoc, "cmpxchg operand must be a pointer");
7408   if (!cast<PointerType>(Ptr->getType())
7409            ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
7410     return error(CmpLoc, "compare value and pointer type do not match");
7411   if (!cast<PointerType>(Ptr->getType())
7412            ->isOpaqueOrPointeeTypeMatches(New->getType()))
7413     return error(NewLoc, "new value and pointer type do not match");
7414   if (Cmp->getType() != New->getType())
7415     return error(NewLoc, "compare value and new value type do not match");
7416   if (!New->getType()->isFirstClassType())
7417     return error(NewLoc, "cmpxchg operand must be a first class value");
7418 
7419   const Align DefaultAlignment(
7420       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7421           Cmp->getType()));
7422 
7423   AtomicCmpXchgInst *CXI =
7424       new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
7425                             SuccessOrdering, FailureOrdering, SSID);
7426   CXI->setVolatile(isVolatile);
7427   CXI->setWeak(isWeak);
7428 
7429   Inst = CXI;
7430   return AteExtraComma ? InstExtraComma : InstNormal;
7431 }
7432 
7433 /// parseAtomicRMW
7434 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7435 ///       'singlethread'? AtomicOrdering
7436 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7437   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7438   bool AteExtraComma = false;
7439   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7440   SyncScope::ID SSID = SyncScope::System;
7441   bool isVolatile = false;
7442   bool IsFP = false;
7443   AtomicRMWInst::BinOp Operation;
7444   MaybeAlign Alignment;
7445 
7446   if (EatIfPresent(lltok::kw_volatile))
7447     isVolatile = true;
7448 
7449   switch (Lex.getKind()) {
7450   default:
7451     return tokError("expected binary operation in atomicrmw");
7452   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7453   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7454   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7455   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7456   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7457   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7458   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7459   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7460   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7461   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7462   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7463   case lltok::kw_fadd:
7464     Operation = AtomicRMWInst::FAdd;
7465     IsFP = true;
7466     break;
7467   case lltok::kw_fsub:
7468     Operation = AtomicRMWInst::FSub;
7469     IsFP = true;
7470     break;
7471   case lltok::kw_fmax:
7472     Operation = AtomicRMWInst::FMax;
7473     IsFP = true;
7474     break;
7475   case lltok::kw_fmin:
7476     Operation = AtomicRMWInst::FMin;
7477     IsFP = true;
7478     break;
7479   }
7480   Lex.Lex();  // Eat the operation.
7481 
7482   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7483       parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7484       parseTypeAndValue(Val, ValLoc, PFS) ||
7485       parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7486       parseOptionalCommaAlign(Alignment, AteExtraComma))
7487     return true;
7488 
7489   if (Ordering == AtomicOrdering::Unordered)
7490     return tokError("atomicrmw cannot be unordered");
7491   if (!Ptr->getType()->isPointerTy())
7492     return error(PtrLoc, "atomicrmw operand must be a pointer");
7493   if (!cast<PointerType>(Ptr->getType())
7494            ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7495     return error(ValLoc, "atomicrmw value and pointer type do not match");
7496 
7497   if (Operation == AtomicRMWInst::Xchg) {
7498     if (!Val->getType()->isIntegerTy() &&
7499         !Val->getType()->isFloatingPointTy() &&
7500         !Val->getType()->isPointerTy()) {
7501       return error(
7502           ValLoc,
7503           "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7504               " operand must be an integer, floating point, or pointer type");
7505     }
7506   } else if (IsFP) {
7507     if (!Val->getType()->isFloatingPointTy()) {
7508       return error(ValLoc, "atomicrmw " +
7509                                AtomicRMWInst::getOperationName(Operation) +
7510                                " operand must be a floating point type");
7511     }
7512   } else {
7513     if (!Val->getType()->isIntegerTy()) {
7514       return error(ValLoc, "atomicrmw " +
7515                                AtomicRMWInst::getOperationName(Operation) +
7516                                " operand must be an integer");
7517     }
7518   }
7519 
7520   unsigned Size =
7521       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
7522           Val->getType());
7523   if (Size < 8 || (Size & (Size - 1)))
7524     return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7525                          " integer");
7526   const Align DefaultAlignment(
7527       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7528           Val->getType()));
7529   AtomicRMWInst *RMWI =
7530       new AtomicRMWInst(Operation, Ptr, Val,
7531                         Alignment.value_or(DefaultAlignment), Ordering, SSID);
7532   RMWI->setVolatile(isVolatile);
7533   Inst = RMWI;
7534   return AteExtraComma ? InstExtraComma : InstNormal;
7535 }
7536 
7537 /// parseFence
7538 ///   ::= 'fence' 'singlethread'? AtomicOrdering
7539 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7540   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7541   SyncScope::ID SSID = SyncScope::System;
7542   if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7543     return true;
7544 
7545   if (Ordering == AtomicOrdering::Unordered)
7546     return tokError("fence cannot be unordered");
7547   if (Ordering == AtomicOrdering::Monotonic)
7548     return tokError("fence cannot be monotonic");
7549 
7550   Inst = new FenceInst(Context, Ordering, SSID);
7551   return InstNormal;
7552 }
7553 
7554 /// parseGetElementPtr
7555 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7556 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7557   Value *Ptr = nullptr;
7558   Value *Val = nullptr;
7559   LocTy Loc, EltLoc;
7560 
7561   bool InBounds = EatIfPresent(lltok::kw_inbounds);
7562 
7563   Type *Ty = nullptr;
7564   LocTy ExplicitTypeLoc = Lex.getLoc();
7565   if (parseType(Ty) ||
7566       parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7567       parseTypeAndValue(Ptr, Loc, PFS))
7568     return true;
7569 
7570   Type *BaseType = Ptr->getType();
7571   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7572   if (!BasePointerType)
7573     return error(Loc, "base of getelementptr must be a pointer");
7574 
7575   if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
7576     return error(
7577         ExplicitTypeLoc,
7578         typeComparisonErrorMessage(
7579             "explicit pointee type doesn't match operand's pointee type", Ty,
7580             BasePointerType->getNonOpaquePointerElementType()));
7581   }
7582 
7583   SmallVector<Value*, 16> Indices;
7584   bool AteExtraComma = false;
7585   // GEP returns a vector of pointers if at least one of parameters is a vector.
7586   // All vector parameters should have the same vector width.
7587   ElementCount GEPWidth = BaseType->isVectorTy()
7588                               ? cast<VectorType>(BaseType)->getElementCount()
7589                               : ElementCount::getFixed(0);
7590 
7591   while (EatIfPresent(lltok::comma)) {
7592     if (Lex.getKind() == lltok::MetadataVar) {
7593       AteExtraComma = true;
7594       break;
7595     }
7596     if (parseTypeAndValue(Val, EltLoc, PFS))
7597       return true;
7598     if (!Val->getType()->isIntOrIntVectorTy())
7599       return error(EltLoc, "getelementptr index must be an integer");
7600 
7601     if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7602       ElementCount ValNumEl = ValVTy->getElementCount();
7603       if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7604         return error(
7605             EltLoc,
7606             "getelementptr vector index has a wrong number of elements");
7607       GEPWidth = ValNumEl;
7608     }
7609     Indices.push_back(Val);
7610   }
7611 
7612   SmallPtrSet<Type*, 4> Visited;
7613   if (!Indices.empty() && !Ty->isSized(&Visited))
7614     return error(Loc, "base element of getelementptr must be sized");
7615 
7616   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7617     return error(Loc, "invalid getelementptr indices");
7618   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7619   if (InBounds)
7620     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7621   return AteExtraComma ? InstExtraComma : InstNormal;
7622 }
7623 
7624 /// parseExtractValue
7625 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
7626 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7627   Value *Val; LocTy Loc;
7628   SmallVector<unsigned, 4> Indices;
7629   bool AteExtraComma;
7630   if (parseTypeAndValue(Val, Loc, PFS) ||
7631       parseIndexList(Indices, AteExtraComma))
7632     return true;
7633 
7634   if (!Val->getType()->isAggregateType())
7635     return error(Loc, "extractvalue operand must be aggregate type");
7636 
7637   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7638     return error(Loc, "invalid indices for extractvalue");
7639   Inst = ExtractValueInst::Create(Val, Indices);
7640   return AteExtraComma ? InstExtraComma : InstNormal;
7641 }
7642 
7643 /// parseInsertValue
7644 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7645 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7646   Value *Val0, *Val1; LocTy Loc0, Loc1;
7647   SmallVector<unsigned, 4> Indices;
7648   bool AteExtraComma;
7649   if (parseTypeAndValue(Val0, Loc0, PFS) ||
7650       parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7651       parseTypeAndValue(Val1, Loc1, PFS) ||
7652       parseIndexList(Indices, AteExtraComma))
7653     return true;
7654 
7655   if (!Val0->getType()->isAggregateType())
7656     return error(Loc0, "insertvalue operand must be aggregate type");
7657 
7658   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7659   if (!IndexedType)
7660     return error(Loc0, "invalid indices for insertvalue");
7661   if (IndexedType != Val1->getType())
7662     return error(Loc1, "insertvalue operand and field disagree in type: '" +
7663                            getTypeString(Val1->getType()) + "' instead of '" +
7664                            getTypeString(IndexedType) + "'");
7665   Inst = InsertValueInst::Create(Val0, Val1, Indices);
7666   return AteExtraComma ? InstExtraComma : InstNormal;
7667 }
7668 
7669 //===----------------------------------------------------------------------===//
7670 // Embedded metadata.
7671 //===----------------------------------------------------------------------===//
7672 
7673 /// parseMDNodeVector
7674 ///   ::= { Element (',' Element)* }
7675 /// Element
7676 ///   ::= 'null' | TypeAndValue
7677 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7678   if (parseToken(lltok::lbrace, "expected '{' here"))
7679     return true;
7680 
7681   // Check for an empty list.
7682   if (EatIfPresent(lltok::rbrace))
7683     return false;
7684 
7685   do {
7686     // Null is a special case since it is typeless.
7687     if (EatIfPresent(lltok::kw_null)) {
7688       Elts.push_back(nullptr);
7689       continue;
7690     }
7691 
7692     Metadata *MD;
7693     if (parseMetadata(MD, nullptr))
7694       return true;
7695     Elts.push_back(MD);
7696   } while (EatIfPresent(lltok::comma));
7697 
7698   return parseToken(lltok::rbrace, "expected end of metadata node");
7699 }
7700 
7701 //===----------------------------------------------------------------------===//
7702 // Use-list order directives.
7703 //===----------------------------------------------------------------------===//
7704 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7705                                 SMLoc Loc) {
7706   if (V->use_empty())
7707     return error(Loc, "value has no uses");
7708 
7709   unsigned NumUses = 0;
7710   SmallDenseMap<const Use *, unsigned, 16> Order;
7711   for (const Use &U : V->uses()) {
7712     if (++NumUses > Indexes.size())
7713       break;
7714     Order[&U] = Indexes[NumUses - 1];
7715   }
7716   if (NumUses < 2)
7717     return error(Loc, "value only has one use");
7718   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7719     return error(Loc,
7720                  "wrong number of indexes, expected " + Twine(V->getNumUses()));
7721 
7722   V->sortUseList([&](const Use &L, const Use &R) {
7723     return Order.lookup(&L) < Order.lookup(&R);
7724   });
7725   return false;
7726 }
7727 
7728 /// parseUseListOrderIndexes
7729 ///   ::= '{' uint32 (',' uint32)+ '}'
7730 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7731   SMLoc Loc = Lex.getLoc();
7732   if (parseToken(lltok::lbrace, "expected '{' here"))
7733     return true;
7734   if (Lex.getKind() == lltok::rbrace)
7735     return Lex.Error("expected non-empty list of uselistorder indexes");
7736 
7737   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
7738   // indexes should be distinct numbers in the range [0, size-1], and should
7739   // not be in order.
7740   unsigned Offset = 0;
7741   unsigned Max = 0;
7742   bool IsOrdered = true;
7743   assert(Indexes.empty() && "Expected empty order vector");
7744   do {
7745     unsigned Index;
7746     if (parseUInt32(Index))
7747       return true;
7748 
7749     // Update consistency checks.
7750     Offset += Index - Indexes.size();
7751     Max = std::max(Max, Index);
7752     IsOrdered &= Index == Indexes.size();
7753 
7754     Indexes.push_back(Index);
7755   } while (EatIfPresent(lltok::comma));
7756 
7757   if (parseToken(lltok::rbrace, "expected '}' here"))
7758     return true;
7759 
7760   if (Indexes.size() < 2)
7761     return error(Loc, "expected >= 2 uselistorder indexes");
7762   if (Offset != 0 || Max >= Indexes.size())
7763     return error(Loc,
7764                  "expected distinct uselistorder indexes in range [0, size)");
7765   if (IsOrdered)
7766     return error(Loc, "expected uselistorder indexes to change the order");
7767 
7768   return false;
7769 }
7770 
7771 /// parseUseListOrder
7772 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7773 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7774   SMLoc Loc = Lex.getLoc();
7775   if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7776     return true;
7777 
7778   Value *V;
7779   SmallVector<unsigned, 16> Indexes;
7780   if (parseTypeAndValue(V, PFS) ||
7781       parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7782       parseUseListOrderIndexes(Indexes))
7783     return true;
7784 
7785   return sortUseListOrder(V, Indexes, Loc);
7786 }
7787 
7788 /// parseUseListOrderBB
7789 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7790 bool LLParser::parseUseListOrderBB() {
7791   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7792   SMLoc Loc = Lex.getLoc();
7793   Lex.Lex();
7794 
7795   ValID Fn, Label;
7796   SmallVector<unsigned, 16> Indexes;
7797   if (parseValID(Fn, /*PFS=*/nullptr) ||
7798       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7799       parseValID(Label, /*PFS=*/nullptr) ||
7800       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7801       parseUseListOrderIndexes(Indexes))
7802     return true;
7803 
7804   // Check the function.
7805   GlobalValue *GV;
7806   if (Fn.Kind == ValID::t_GlobalName)
7807     GV = M->getNamedValue(Fn.StrVal);
7808   else if (Fn.Kind == ValID::t_GlobalID)
7809     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7810   else
7811     return error(Fn.Loc, "expected function name in uselistorder_bb");
7812   if (!GV)
7813     return error(Fn.Loc,
7814                  "invalid function forward reference in uselistorder_bb");
7815   auto *F = dyn_cast<Function>(GV);
7816   if (!F)
7817     return error(Fn.Loc, "expected function name in uselistorder_bb");
7818   if (F->isDeclaration())
7819     return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7820 
7821   // Check the basic block.
7822   if (Label.Kind == ValID::t_LocalID)
7823     return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7824   if (Label.Kind != ValID::t_LocalName)
7825     return error(Label.Loc, "expected basic block name in uselistorder_bb");
7826   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7827   if (!V)
7828     return error(Label.Loc, "invalid basic block in uselistorder_bb");
7829   if (!isa<BasicBlock>(V))
7830     return error(Label.Loc, "expected basic block in uselistorder_bb");
7831 
7832   return sortUseListOrder(V, Indexes, Loc);
7833 }
7834 
7835 /// ModuleEntry
7836 ///   ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7837 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7838 bool LLParser::parseModuleEntry(unsigned ID) {
7839   assert(Lex.getKind() == lltok::kw_module);
7840   Lex.Lex();
7841 
7842   std::string Path;
7843   if (parseToken(lltok::colon, "expected ':' here") ||
7844       parseToken(lltok::lparen, "expected '(' here") ||
7845       parseToken(lltok::kw_path, "expected 'path' here") ||
7846       parseToken(lltok::colon, "expected ':' here") ||
7847       parseStringConstant(Path) ||
7848       parseToken(lltok::comma, "expected ',' here") ||
7849       parseToken(lltok::kw_hash, "expected 'hash' here") ||
7850       parseToken(lltok::colon, "expected ':' here") ||
7851       parseToken(lltok::lparen, "expected '(' here"))
7852     return true;
7853 
7854   ModuleHash Hash;
7855   if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
7856       parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
7857       parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
7858       parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
7859       parseUInt32(Hash[4]))
7860     return true;
7861 
7862   if (parseToken(lltok::rparen, "expected ')' here") ||
7863       parseToken(lltok::rparen, "expected ')' here"))
7864     return true;
7865 
7866   auto ModuleEntry = Index->addModule(Path, ID, Hash);
7867   ModuleIdMap[ID] = ModuleEntry->first();
7868 
7869   return false;
7870 }
7871 
7872 /// TypeIdEntry
7873 ///   ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7874 bool LLParser::parseTypeIdEntry(unsigned ID) {
7875   assert(Lex.getKind() == lltok::kw_typeid);
7876   Lex.Lex();
7877 
7878   std::string Name;
7879   if (parseToken(lltok::colon, "expected ':' here") ||
7880       parseToken(lltok::lparen, "expected '(' here") ||
7881       parseToken(lltok::kw_name, "expected 'name' here") ||
7882       parseToken(lltok::colon, "expected ':' here") ||
7883       parseStringConstant(Name))
7884     return true;
7885 
7886   TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7887   if (parseToken(lltok::comma, "expected ',' here") ||
7888       parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
7889     return true;
7890 
7891   // Check if this ID was forward referenced, and if so, update the
7892   // corresponding GUIDs.
7893   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7894   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7895     for (auto TIDRef : FwdRefTIDs->second) {
7896       assert(!*TIDRef.first &&
7897              "Forward referenced type id GUID expected to be 0");
7898       *TIDRef.first = GlobalValue::getGUID(Name);
7899     }
7900     ForwardRefTypeIds.erase(FwdRefTIDs);
7901   }
7902 
7903   return false;
7904 }
7905 
7906 /// TypeIdSummary
7907 ///   ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7908 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
7909   if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
7910       parseToken(lltok::colon, "expected ':' here") ||
7911       parseToken(lltok::lparen, "expected '(' here") ||
7912       parseTypeTestResolution(TIS.TTRes))
7913     return true;
7914 
7915   if (EatIfPresent(lltok::comma)) {
7916     // Expect optional wpdResolutions field
7917     if (parseOptionalWpdResolutions(TIS.WPDRes))
7918       return true;
7919   }
7920 
7921   if (parseToken(lltok::rparen, "expected ')' here"))
7922     return true;
7923 
7924   return false;
7925 }
7926 
7927 static ValueInfo EmptyVI =
7928     ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7929 
7930 /// TypeIdCompatibleVtableEntry
7931 ///   ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7932 ///   TypeIdCompatibleVtableInfo
7933 ///   ')'
7934 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
7935   assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7936   Lex.Lex();
7937 
7938   std::string Name;
7939   if (parseToken(lltok::colon, "expected ':' here") ||
7940       parseToken(lltok::lparen, "expected '(' here") ||
7941       parseToken(lltok::kw_name, "expected 'name' here") ||
7942       parseToken(lltok::colon, "expected ':' here") ||
7943       parseStringConstant(Name))
7944     return true;
7945 
7946   TypeIdCompatibleVtableInfo &TI =
7947       Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7948   if (parseToken(lltok::comma, "expected ',' here") ||
7949       parseToken(lltok::kw_summary, "expected 'summary' here") ||
7950       parseToken(lltok::colon, "expected ':' here") ||
7951       parseToken(lltok::lparen, "expected '(' here"))
7952     return true;
7953 
7954   IdToIndexMapType IdToIndexMap;
7955   // parse each call edge
7956   do {
7957     uint64_t Offset;
7958     if (parseToken(lltok::lparen, "expected '(' here") ||
7959         parseToken(lltok::kw_offset, "expected 'offset' here") ||
7960         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7961         parseToken(lltok::comma, "expected ',' here"))
7962       return true;
7963 
7964     LocTy Loc = Lex.getLoc();
7965     unsigned GVId;
7966     ValueInfo VI;
7967     if (parseGVReference(VI, GVId))
7968       return true;
7969 
7970     // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7971     // forward reference. We will save the location of the ValueInfo needing an
7972     // update, but can only do so once the std::vector is finalized.
7973     if (VI == EmptyVI)
7974       IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7975     TI.push_back({Offset, VI});
7976 
7977     if (parseToken(lltok::rparen, "expected ')' in call"))
7978       return true;
7979   } while (EatIfPresent(lltok::comma));
7980 
7981   // Now that the TI vector is finalized, it is safe to save the locations
7982   // of any forward GV references that need updating later.
7983   for (auto I : IdToIndexMap) {
7984     auto &Infos = ForwardRefValueInfos[I.first];
7985     for (auto P : I.second) {
7986       assert(TI[P.first].VTableVI == EmptyVI &&
7987              "Forward referenced ValueInfo expected to be empty");
7988       Infos.emplace_back(&TI[P.first].VTableVI, P.second);
7989     }
7990   }
7991 
7992   if (parseToken(lltok::rparen, "expected ')' here") ||
7993       parseToken(lltok::rparen, "expected ')' here"))
7994     return true;
7995 
7996   // Check if this ID was forward referenced, and if so, update the
7997   // corresponding GUIDs.
7998   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7999   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8000     for (auto TIDRef : FwdRefTIDs->second) {
8001       assert(!*TIDRef.first &&
8002              "Forward referenced type id GUID expected to be 0");
8003       *TIDRef.first = GlobalValue::getGUID(Name);
8004     }
8005     ForwardRefTypeIds.erase(FwdRefTIDs);
8006   }
8007 
8008   return false;
8009 }
8010 
8011 /// TypeTestResolution
8012 ///   ::= 'typeTestRes' ':' '(' 'kind' ':'
8013 ///         ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8014 ///         'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8015 ///         [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8016 ///         [',' 'inlinesBits' ':' UInt64]? ')'
8017 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8018   if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8019       parseToken(lltok::colon, "expected ':' here") ||
8020       parseToken(lltok::lparen, "expected '(' here") ||
8021       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8022       parseToken(lltok::colon, "expected ':' here"))
8023     return true;
8024 
8025   switch (Lex.getKind()) {
8026   case lltok::kw_unknown:
8027     TTRes.TheKind = TypeTestResolution::Unknown;
8028     break;
8029   case lltok::kw_unsat:
8030     TTRes.TheKind = TypeTestResolution::Unsat;
8031     break;
8032   case lltok::kw_byteArray:
8033     TTRes.TheKind = TypeTestResolution::ByteArray;
8034     break;
8035   case lltok::kw_inline:
8036     TTRes.TheKind = TypeTestResolution::Inline;
8037     break;
8038   case lltok::kw_single:
8039     TTRes.TheKind = TypeTestResolution::Single;
8040     break;
8041   case lltok::kw_allOnes:
8042     TTRes.TheKind = TypeTestResolution::AllOnes;
8043     break;
8044   default:
8045     return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8046   }
8047   Lex.Lex();
8048 
8049   if (parseToken(lltok::comma, "expected ',' here") ||
8050       parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8051       parseToken(lltok::colon, "expected ':' here") ||
8052       parseUInt32(TTRes.SizeM1BitWidth))
8053     return true;
8054 
8055   // parse optional fields
8056   while (EatIfPresent(lltok::comma)) {
8057     switch (Lex.getKind()) {
8058     case lltok::kw_alignLog2:
8059       Lex.Lex();
8060       if (parseToken(lltok::colon, "expected ':'") ||
8061           parseUInt64(TTRes.AlignLog2))
8062         return true;
8063       break;
8064     case lltok::kw_sizeM1:
8065       Lex.Lex();
8066       if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8067         return true;
8068       break;
8069     case lltok::kw_bitMask: {
8070       unsigned Val;
8071       Lex.Lex();
8072       if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8073         return true;
8074       assert(Val <= 0xff);
8075       TTRes.BitMask = (uint8_t)Val;
8076       break;
8077     }
8078     case lltok::kw_inlineBits:
8079       Lex.Lex();
8080       if (parseToken(lltok::colon, "expected ':'") ||
8081           parseUInt64(TTRes.InlineBits))
8082         return true;
8083       break;
8084     default:
8085       return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8086     }
8087   }
8088 
8089   if (parseToken(lltok::rparen, "expected ')' here"))
8090     return true;
8091 
8092   return false;
8093 }
8094 
8095 /// OptionalWpdResolutions
8096 ///   ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8097 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8098 bool LLParser::parseOptionalWpdResolutions(
8099     std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8100   if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8101       parseToken(lltok::colon, "expected ':' here") ||
8102       parseToken(lltok::lparen, "expected '(' here"))
8103     return true;
8104 
8105   do {
8106     uint64_t Offset;
8107     WholeProgramDevirtResolution WPDRes;
8108     if (parseToken(lltok::lparen, "expected '(' here") ||
8109         parseToken(lltok::kw_offset, "expected 'offset' here") ||
8110         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8111         parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8112         parseToken(lltok::rparen, "expected ')' here"))
8113       return true;
8114     WPDResMap[Offset] = WPDRes;
8115   } while (EatIfPresent(lltok::comma));
8116 
8117   if (parseToken(lltok::rparen, "expected ')' here"))
8118     return true;
8119 
8120   return false;
8121 }
8122 
8123 /// WpdRes
8124 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8125 ///         [',' OptionalResByArg]? ')'
8126 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8127 ///         ',' 'singleImplName' ':' STRINGCONSTANT ','
8128 ///         [',' OptionalResByArg]? ')'
8129 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8130 ///         [',' OptionalResByArg]? ')'
8131 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8132   if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8133       parseToken(lltok::colon, "expected ':' here") ||
8134       parseToken(lltok::lparen, "expected '(' here") ||
8135       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8136       parseToken(lltok::colon, "expected ':' here"))
8137     return true;
8138 
8139   switch (Lex.getKind()) {
8140   case lltok::kw_indir:
8141     WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8142     break;
8143   case lltok::kw_singleImpl:
8144     WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8145     break;
8146   case lltok::kw_branchFunnel:
8147     WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8148     break;
8149   default:
8150     return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8151   }
8152   Lex.Lex();
8153 
8154   // parse optional fields
8155   while (EatIfPresent(lltok::comma)) {
8156     switch (Lex.getKind()) {
8157     case lltok::kw_singleImplName:
8158       Lex.Lex();
8159       if (parseToken(lltok::colon, "expected ':' here") ||
8160           parseStringConstant(WPDRes.SingleImplName))
8161         return true;
8162       break;
8163     case lltok::kw_resByArg:
8164       if (parseOptionalResByArg(WPDRes.ResByArg))
8165         return true;
8166       break;
8167     default:
8168       return error(Lex.getLoc(),
8169                    "expected optional WholeProgramDevirtResolution field");
8170     }
8171   }
8172 
8173   if (parseToken(lltok::rparen, "expected ')' here"))
8174     return true;
8175 
8176   return false;
8177 }
8178 
8179 /// OptionalResByArg
8180 ///   ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8181 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8182 ///                ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8183 ///                  'virtualConstProp' )
8184 ///                [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8185 ///                [',' 'bit' ':' UInt32]? ')'
8186 bool LLParser::parseOptionalResByArg(
8187     std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8188         &ResByArg) {
8189   if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8190       parseToken(lltok::colon, "expected ':' here") ||
8191       parseToken(lltok::lparen, "expected '(' here"))
8192     return true;
8193 
8194   do {
8195     std::vector<uint64_t> Args;
8196     if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8197         parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8198         parseToken(lltok::colon, "expected ':' here") ||
8199         parseToken(lltok::lparen, "expected '(' here") ||
8200         parseToken(lltok::kw_kind, "expected 'kind' here") ||
8201         parseToken(lltok::colon, "expected ':' here"))
8202       return true;
8203 
8204     WholeProgramDevirtResolution::ByArg ByArg;
8205     switch (Lex.getKind()) {
8206     case lltok::kw_indir:
8207       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8208       break;
8209     case lltok::kw_uniformRetVal:
8210       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8211       break;
8212     case lltok::kw_uniqueRetVal:
8213       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8214       break;
8215     case lltok::kw_virtualConstProp:
8216       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8217       break;
8218     default:
8219       return error(Lex.getLoc(),
8220                    "unexpected WholeProgramDevirtResolution::ByArg kind");
8221     }
8222     Lex.Lex();
8223 
8224     // parse optional fields
8225     while (EatIfPresent(lltok::comma)) {
8226       switch (Lex.getKind()) {
8227       case lltok::kw_info:
8228         Lex.Lex();
8229         if (parseToken(lltok::colon, "expected ':' here") ||
8230             parseUInt64(ByArg.Info))
8231           return true;
8232         break;
8233       case lltok::kw_byte:
8234         Lex.Lex();
8235         if (parseToken(lltok::colon, "expected ':' here") ||
8236             parseUInt32(ByArg.Byte))
8237           return true;
8238         break;
8239       case lltok::kw_bit:
8240         Lex.Lex();
8241         if (parseToken(lltok::colon, "expected ':' here") ||
8242             parseUInt32(ByArg.Bit))
8243           return true;
8244         break;
8245       default:
8246         return error(Lex.getLoc(),
8247                      "expected optional whole program devirt field");
8248       }
8249     }
8250 
8251     if (parseToken(lltok::rparen, "expected ')' here"))
8252       return true;
8253 
8254     ResByArg[Args] = ByArg;
8255   } while (EatIfPresent(lltok::comma));
8256 
8257   if (parseToken(lltok::rparen, "expected ')' here"))
8258     return true;
8259 
8260   return false;
8261 }
8262 
8263 /// OptionalResByArg
8264 ///   ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8265 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8266   if (parseToken(lltok::kw_args, "expected 'args' here") ||
8267       parseToken(lltok::colon, "expected ':' here") ||
8268       parseToken(lltok::lparen, "expected '(' here"))
8269     return true;
8270 
8271   do {
8272     uint64_t Val;
8273     if (parseUInt64(Val))
8274       return true;
8275     Args.push_back(Val);
8276   } while (EatIfPresent(lltok::comma));
8277 
8278   if (parseToken(lltok::rparen, "expected ')' here"))
8279     return true;
8280 
8281   return false;
8282 }
8283 
8284 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8285 
8286 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8287   bool ReadOnly = Fwd->isReadOnly();
8288   bool WriteOnly = Fwd->isWriteOnly();
8289   assert(!(ReadOnly && WriteOnly));
8290   *Fwd = Resolved;
8291   if (ReadOnly)
8292     Fwd->setReadOnly();
8293   if (WriteOnly)
8294     Fwd->setWriteOnly();
8295 }
8296 
8297 /// Stores the given Name/GUID and associated summary into the Index.
8298 /// Also updates any forward references to the associated entry ID.
8299 void LLParser::addGlobalValueToIndex(
8300     std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8301     unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8302   // First create the ValueInfo utilizing the Name or GUID.
8303   ValueInfo VI;
8304   if (GUID != 0) {
8305     assert(Name.empty());
8306     VI = Index->getOrInsertValueInfo(GUID);
8307   } else {
8308     assert(!Name.empty());
8309     if (M) {
8310       auto *GV = M->getNamedValue(Name);
8311       assert(GV);
8312       VI = Index->getOrInsertValueInfo(GV);
8313     } else {
8314       assert(
8315           (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8316           "Need a source_filename to compute GUID for local");
8317       GUID = GlobalValue::getGUID(
8318           GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8319       VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8320     }
8321   }
8322 
8323   // Resolve forward references from calls/refs
8324   auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8325   if (FwdRefVIs != ForwardRefValueInfos.end()) {
8326     for (auto VIRef : FwdRefVIs->second) {
8327       assert(VIRef.first->getRef() == FwdVIRef &&
8328              "Forward referenced ValueInfo expected to be empty");
8329       resolveFwdRef(VIRef.first, VI);
8330     }
8331     ForwardRefValueInfos.erase(FwdRefVIs);
8332   }
8333 
8334   // Resolve forward references from aliases
8335   auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8336   if (FwdRefAliasees != ForwardRefAliasees.end()) {
8337     for (auto AliaseeRef : FwdRefAliasees->second) {
8338       assert(!AliaseeRef.first->hasAliasee() &&
8339              "Forward referencing alias already has aliasee");
8340       assert(Summary && "Aliasee must be a definition");
8341       AliaseeRef.first->setAliasee(VI, Summary.get());
8342     }
8343     ForwardRefAliasees.erase(FwdRefAliasees);
8344   }
8345 
8346   // Add the summary if one was provided.
8347   if (Summary)
8348     Index->addGlobalValueSummary(VI, std::move(Summary));
8349 
8350   // Save the associated ValueInfo for use in later references by ID.
8351   if (ID == NumberedValueInfos.size())
8352     NumberedValueInfos.push_back(VI);
8353   else {
8354     // Handle non-continuous numbers (to make test simplification easier).
8355     if (ID > NumberedValueInfos.size())
8356       NumberedValueInfos.resize(ID + 1);
8357     NumberedValueInfos[ID] = VI;
8358   }
8359 }
8360 
8361 /// parseSummaryIndexFlags
8362 ///   ::= 'flags' ':' UInt64
8363 bool LLParser::parseSummaryIndexFlags() {
8364   assert(Lex.getKind() == lltok::kw_flags);
8365   Lex.Lex();
8366 
8367   if (parseToken(lltok::colon, "expected ':' here"))
8368     return true;
8369   uint64_t Flags;
8370   if (parseUInt64(Flags))
8371     return true;
8372   if (Index)
8373     Index->setFlags(Flags);
8374   return false;
8375 }
8376 
8377 /// parseBlockCount
8378 ///   ::= 'blockcount' ':' UInt64
8379 bool LLParser::parseBlockCount() {
8380   assert(Lex.getKind() == lltok::kw_blockcount);
8381   Lex.Lex();
8382 
8383   if (parseToken(lltok::colon, "expected ':' here"))
8384     return true;
8385   uint64_t BlockCount;
8386   if (parseUInt64(BlockCount))
8387     return true;
8388   if (Index)
8389     Index->setBlockCount(BlockCount);
8390   return false;
8391 }
8392 
8393 /// parseGVEntry
8394 ///   ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8395 ///         [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8396 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8397 bool LLParser::parseGVEntry(unsigned ID) {
8398   assert(Lex.getKind() == lltok::kw_gv);
8399   Lex.Lex();
8400 
8401   if (parseToken(lltok::colon, "expected ':' here") ||
8402       parseToken(lltok::lparen, "expected '(' here"))
8403     return true;
8404 
8405   std::string Name;
8406   GlobalValue::GUID GUID = 0;
8407   switch (Lex.getKind()) {
8408   case lltok::kw_name:
8409     Lex.Lex();
8410     if (parseToken(lltok::colon, "expected ':' here") ||
8411         parseStringConstant(Name))
8412       return true;
8413     // Can't create GUID/ValueInfo until we have the linkage.
8414     break;
8415   case lltok::kw_guid:
8416     Lex.Lex();
8417     if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8418       return true;
8419     break;
8420   default:
8421     return error(Lex.getLoc(), "expected name or guid tag");
8422   }
8423 
8424   if (!EatIfPresent(lltok::comma)) {
8425     // No summaries. Wrap up.
8426     if (parseToken(lltok::rparen, "expected ')' here"))
8427       return true;
8428     // This was created for a call to an external or indirect target.
8429     // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8430     // created for indirect calls with VP. A Name with no GUID came from
8431     // an external definition. We pass ExternalLinkage since that is only
8432     // used when the GUID must be computed from Name, and in that case
8433     // the symbol must have external linkage.
8434     addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8435                           nullptr);
8436     return false;
8437   }
8438 
8439   // Have a list of summaries
8440   if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8441       parseToken(lltok::colon, "expected ':' here") ||
8442       parseToken(lltok::lparen, "expected '(' here"))
8443     return true;
8444   do {
8445     switch (Lex.getKind()) {
8446     case lltok::kw_function:
8447       if (parseFunctionSummary(Name, GUID, ID))
8448         return true;
8449       break;
8450     case lltok::kw_variable:
8451       if (parseVariableSummary(Name, GUID, ID))
8452         return true;
8453       break;
8454     case lltok::kw_alias:
8455       if (parseAliasSummary(Name, GUID, ID))
8456         return true;
8457       break;
8458     default:
8459       return error(Lex.getLoc(), "expected summary type");
8460     }
8461   } while (EatIfPresent(lltok::comma));
8462 
8463   if (parseToken(lltok::rparen, "expected ')' here") ||
8464       parseToken(lltok::rparen, "expected ')' here"))
8465     return true;
8466 
8467   return false;
8468 }
8469 
8470 /// FunctionSummary
8471 ///   ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8472 ///         ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8473 ///         [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8474 ///         [',' OptionalRefs]? ')'
8475 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8476                                     unsigned ID) {
8477   assert(Lex.getKind() == lltok::kw_function);
8478   Lex.Lex();
8479 
8480   StringRef ModulePath;
8481   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8482       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8483       /*NotEligibleToImport=*/false,
8484       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8485   unsigned InstCount;
8486   std::vector<FunctionSummary::EdgeTy> Calls;
8487   FunctionSummary::TypeIdInfo TypeIdInfo;
8488   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8489   std::vector<ValueInfo> Refs;
8490   // Default is all-zeros (conservative values).
8491   FunctionSummary::FFlags FFlags = {};
8492   if (parseToken(lltok::colon, "expected ':' here") ||
8493       parseToken(lltok::lparen, "expected '(' here") ||
8494       parseModuleReference(ModulePath) ||
8495       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8496       parseToken(lltok::comma, "expected ',' here") ||
8497       parseToken(lltok::kw_insts, "expected 'insts' here") ||
8498       parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8499     return true;
8500 
8501   // parse optional fields
8502   while (EatIfPresent(lltok::comma)) {
8503     switch (Lex.getKind()) {
8504     case lltok::kw_funcFlags:
8505       if (parseOptionalFFlags(FFlags))
8506         return true;
8507       break;
8508     case lltok::kw_calls:
8509       if (parseOptionalCalls(Calls))
8510         return true;
8511       break;
8512     case lltok::kw_typeIdInfo:
8513       if (parseOptionalTypeIdInfo(TypeIdInfo))
8514         return true;
8515       break;
8516     case lltok::kw_refs:
8517       if (parseOptionalRefs(Refs))
8518         return true;
8519       break;
8520     case lltok::kw_params:
8521       if (parseOptionalParamAccesses(ParamAccesses))
8522         return true;
8523       break;
8524     default:
8525       return error(Lex.getLoc(), "expected optional function summary field");
8526     }
8527   }
8528 
8529   if (parseToken(lltok::rparen, "expected ')' here"))
8530     return true;
8531 
8532   auto FS = std::make_unique<FunctionSummary>(
8533       GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8534       std::move(Calls), std::move(TypeIdInfo.TypeTests),
8535       std::move(TypeIdInfo.TypeTestAssumeVCalls),
8536       std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8537       std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8538       std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8539       std::move(ParamAccesses));
8540 
8541   FS->setModulePath(ModulePath);
8542 
8543   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8544                         ID, std::move(FS));
8545 
8546   return false;
8547 }
8548 
8549 /// VariableSummary
8550 ///   ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8551 ///         [',' OptionalRefs]? ')'
8552 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8553                                     unsigned ID) {
8554   assert(Lex.getKind() == lltok::kw_variable);
8555   Lex.Lex();
8556 
8557   StringRef ModulePath;
8558   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8559       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8560       /*NotEligibleToImport=*/false,
8561       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8562   GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8563                                         /* WriteOnly */ false,
8564                                         /* Constant */ false,
8565                                         GlobalObject::VCallVisibilityPublic);
8566   std::vector<ValueInfo> Refs;
8567   VTableFuncList VTableFuncs;
8568   if (parseToken(lltok::colon, "expected ':' here") ||
8569       parseToken(lltok::lparen, "expected '(' here") ||
8570       parseModuleReference(ModulePath) ||
8571       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8572       parseToken(lltok::comma, "expected ',' here") ||
8573       parseGVarFlags(GVarFlags))
8574     return true;
8575 
8576   // parse optional fields
8577   while (EatIfPresent(lltok::comma)) {
8578     switch (Lex.getKind()) {
8579     case lltok::kw_vTableFuncs:
8580       if (parseOptionalVTableFuncs(VTableFuncs))
8581         return true;
8582       break;
8583     case lltok::kw_refs:
8584       if (parseOptionalRefs(Refs))
8585         return true;
8586       break;
8587     default:
8588       return error(Lex.getLoc(), "expected optional variable summary field");
8589     }
8590   }
8591 
8592   if (parseToken(lltok::rparen, "expected ')' here"))
8593     return true;
8594 
8595   auto GS =
8596       std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8597 
8598   GS->setModulePath(ModulePath);
8599   GS->setVTableFuncs(std::move(VTableFuncs));
8600 
8601   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8602                         ID, std::move(GS));
8603 
8604   return false;
8605 }
8606 
8607 /// AliasSummary
8608 ///   ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8609 ///         'aliasee' ':' GVReference ')'
8610 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8611                                  unsigned ID) {
8612   assert(Lex.getKind() == lltok::kw_alias);
8613   LocTy Loc = Lex.getLoc();
8614   Lex.Lex();
8615 
8616   StringRef ModulePath;
8617   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8618       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8619       /*NotEligibleToImport=*/false,
8620       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8621   if (parseToken(lltok::colon, "expected ':' here") ||
8622       parseToken(lltok::lparen, "expected '(' here") ||
8623       parseModuleReference(ModulePath) ||
8624       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8625       parseToken(lltok::comma, "expected ',' here") ||
8626       parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8627       parseToken(lltok::colon, "expected ':' here"))
8628     return true;
8629 
8630   ValueInfo AliaseeVI;
8631   unsigned GVId;
8632   if (parseGVReference(AliaseeVI, GVId))
8633     return true;
8634 
8635   if (parseToken(lltok::rparen, "expected ')' here"))
8636     return true;
8637 
8638   auto AS = std::make_unique<AliasSummary>(GVFlags);
8639 
8640   AS->setModulePath(ModulePath);
8641 
8642   // Record forward reference if the aliasee is not parsed yet.
8643   if (AliaseeVI.getRef() == FwdVIRef) {
8644     ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8645   } else {
8646     auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8647     assert(Summary && "Aliasee must be a definition");
8648     AS->setAliasee(AliaseeVI, Summary);
8649   }
8650 
8651   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8652                         ID, std::move(AS));
8653 
8654   return false;
8655 }
8656 
8657 /// Flag
8658 ///   ::= [0|1]
8659 bool LLParser::parseFlag(unsigned &Val) {
8660   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8661     return tokError("expected integer");
8662   Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8663   Lex.Lex();
8664   return false;
8665 }
8666 
8667 /// OptionalFFlags
8668 ///   := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8669 ///        [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8670 ///        [',' 'returnDoesNotAlias' ':' Flag]? ')'
8671 ///        [',' 'noInline' ':' Flag]? ')'
8672 ///        [',' 'alwaysInline' ':' Flag]? ')'
8673 ///        [',' 'noUnwind' ':' Flag]? ')'
8674 ///        [',' 'mayThrow' ':' Flag]? ')'
8675 ///        [',' 'hasUnknownCall' ':' Flag]? ')'
8676 ///        [',' 'mustBeUnreachable' ':' Flag]? ')'
8677 
8678 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8679   assert(Lex.getKind() == lltok::kw_funcFlags);
8680   Lex.Lex();
8681 
8682   if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
8683       parseToken(lltok::lparen, "expected '(' in funcFlags"))
8684     return true;
8685 
8686   do {
8687     unsigned Val = 0;
8688     switch (Lex.getKind()) {
8689     case lltok::kw_readNone:
8690       Lex.Lex();
8691       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8692         return true;
8693       FFlags.ReadNone = Val;
8694       break;
8695     case lltok::kw_readOnly:
8696       Lex.Lex();
8697       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8698         return true;
8699       FFlags.ReadOnly = Val;
8700       break;
8701     case lltok::kw_noRecurse:
8702       Lex.Lex();
8703       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8704         return true;
8705       FFlags.NoRecurse = Val;
8706       break;
8707     case lltok::kw_returnDoesNotAlias:
8708       Lex.Lex();
8709       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8710         return true;
8711       FFlags.ReturnDoesNotAlias = Val;
8712       break;
8713     case lltok::kw_noInline:
8714       Lex.Lex();
8715       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8716         return true;
8717       FFlags.NoInline = Val;
8718       break;
8719     case lltok::kw_alwaysInline:
8720       Lex.Lex();
8721       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8722         return true;
8723       FFlags.AlwaysInline = Val;
8724       break;
8725     case lltok::kw_noUnwind:
8726       Lex.Lex();
8727       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8728         return true;
8729       FFlags.NoUnwind = Val;
8730       break;
8731     case lltok::kw_mayThrow:
8732       Lex.Lex();
8733       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8734         return true;
8735       FFlags.MayThrow = Val;
8736       break;
8737     case lltok::kw_hasUnknownCall:
8738       Lex.Lex();
8739       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8740         return true;
8741       FFlags.HasUnknownCall = Val;
8742       break;
8743     case lltok::kw_mustBeUnreachable:
8744       Lex.Lex();
8745       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8746         return true;
8747       FFlags.MustBeUnreachable = Val;
8748       break;
8749     default:
8750       return error(Lex.getLoc(), "expected function flag type");
8751     }
8752   } while (EatIfPresent(lltok::comma));
8753 
8754   if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8755     return true;
8756 
8757   return false;
8758 }
8759 
8760 /// OptionalCalls
8761 ///   := 'calls' ':' '(' Call [',' Call]* ')'
8762 /// Call ::= '(' 'callee' ':' GVReference
8763 ///            [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8764 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8765   assert(Lex.getKind() == lltok::kw_calls);
8766   Lex.Lex();
8767 
8768   if (parseToken(lltok::colon, "expected ':' in calls") ||
8769       parseToken(lltok::lparen, "expected '(' in calls"))
8770     return true;
8771 
8772   IdToIndexMapType IdToIndexMap;
8773   // parse each call edge
8774   do {
8775     ValueInfo VI;
8776     if (parseToken(lltok::lparen, "expected '(' in call") ||
8777         parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8778         parseToken(lltok::colon, "expected ':'"))
8779       return true;
8780 
8781     LocTy Loc = Lex.getLoc();
8782     unsigned GVId;
8783     if (parseGVReference(VI, GVId))
8784       return true;
8785 
8786     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8787     unsigned RelBF = 0;
8788     if (EatIfPresent(lltok::comma)) {
8789       // Expect either hotness or relbf
8790       if (EatIfPresent(lltok::kw_hotness)) {
8791         if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8792           return true;
8793       } else {
8794         if (parseToken(lltok::kw_relbf, "expected relbf") ||
8795             parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8796           return true;
8797       }
8798     }
8799     // Keep track of the Call array index needing a forward reference.
8800     // We will save the location of the ValueInfo needing an update, but
8801     // can only do so once the std::vector is finalized.
8802     if (VI.getRef() == FwdVIRef)
8803       IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8804     Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8805 
8806     if (parseToken(lltok::rparen, "expected ')' in call"))
8807       return true;
8808   } while (EatIfPresent(lltok::comma));
8809 
8810   // Now that the Calls vector is finalized, it is safe to save the locations
8811   // of any forward GV references that need updating later.
8812   for (auto I : IdToIndexMap) {
8813     auto &Infos = ForwardRefValueInfos[I.first];
8814     for (auto P : I.second) {
8815       assert(Calls[P.first].first.getRef() == FwdVIRef &&
8816              "Forward referenced ValueInfo expected to be empty");
8817       Infos.emplace_back(&Calls[P.first].first, P.second);
8818     }
8819   }
8820 
8821   if (parseToken(lltok::rparen, "expected ')' in calls"))
8822     return true;
8823 
8824   return false;
8825 }
8826 
8827 /// Hotness
8828 ///   := ('unknown'|'cold'|'none'|'hot'|'critical')
8829 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8830   switch (Lex.getKind()) {
8831   case lltok::kw_unknown:
8832     Hotness = CalleeInfo::HotnessType::Unknown;
8833     break;
8834   case lltok::kw_cold:
8835     Hotness = CalleeInfo::HotnessType::Cold;
8836     break;
8837   case lltok::kw_none:
8838     Hotness = CalleeInfo::HotnessType::None;
8839     break;
8840   case lltok::kw_hot:
8841     Hotness = CalleeInfo::HotnessType::Hot;
8842     break;
8843   case lltok::kw_critical:
8844     Hotness = CalleeInfo::HotnessType::Critical;
8845     break;
8846   default:
8847     return error(Lex.getLoc(), "invalid call edge hotness");
8848   }
8849   Lex.Lex();
8850   return false;
8851 }
8852 
8853 /// OptionalVTableFuncs
8854 ///   := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8855 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8856 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8857   assert(Lex.getKind() == lltok::kw_vTableFuncs);
8858   Lex.Lex();
8859 
8860   if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
8861       parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8862     return true;
8863 
8864   IdToIndexMapType IdToIndexMap;
8865   // parse each virtual function pair
8866   do {
8867     ValueInfo VI;
8868     if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8869         parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8870         parseToken(lltok::colon, "expected ':'"))
8871       return true;
8872 
8873     LocTy Loc = Lex.getLoc();
8874     unsigned GVId;
8875     if (parseGVReference(VI, GVId))
8876       return true;
8877 
8878     uint64_t Offset;
8879     if (parseToken(lltok::comma, "expected comma") ||
8880         parseToken(lltok::kw_offset, "expected offset") ||
8881         parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
8882       return true;
8883 
8884     // Keep track of the VTableFuncs array index needing a forward reference.
8885     // We will save the location of the ValueInfo needing an update, but
8886     // can only do so once the std::vector is finalized.
8887     if (VI == EmptyVI)
8888       IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8889     VTableFuncs.push_back({VI, Offset});
8890 
8891     if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
8892       return true;
8893   } while (EatIfPresent(lltok::comma));
8894 
8895   // Now that the VTableFuncs vector is finalized, it is safe to save the
8896   // locations of any forward GV references that need updating later.
8897   for (auto I : IdToIndexMap) {
8898     auto &Infos = ForwardRefValueInfos[I.first];
8899     for (auto P : I.second) {
8900       assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8901              "Forward referenced ValueInfo expected to be empty");
8902       Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
8903     }
8904   }
8905 
8906   if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8907     return true;
8908 
8909   return false;
8910 }
8911 
8912 /// ParamNo := 'param' ':' UInt64
8913 bool LLParser::parseParamNo(uint64_t &ParamNo) {
8914   if (parseToken(lltok::kw_param, "expected 'param' here") ||
8915       parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
8916     return true;
8917   return false;
8918 }
8919 
8920 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
8921 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
8922   APSInt Lower;
8923   APSInt Upper;
8924   auto ParseAPSInt = [&](APSInt &Val) {
8925     if (Lex.getKind() != lltok::APSInt)
8926       return tokError("expected integer");
8927     Val = Lex.getAPSIntVal();
8928     Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
8929     Val.setIsSigned(true);
8930     Lex.Lex();
8931     return false;
8932   };
8933   if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
8934       parseToken(lltok::colon, "expected ':' here") ||
8935       parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
8936       parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
8937       parseToken(lltok::rsquare, "expected ']' here"))
8938     return true;
8939 
8940   ++Upper;
8941   Range =
8942       (Lower == Upper && !Lower.isMaxValue())
8943           ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
8944           : ConstantRange(Lower, Upper);
8945 
8946   return false;
8947 }
8948 
8949 /// ParamAccessCall
8950 ///   := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
8951 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
8952                                     IdLocListType &IdLocList) {
8953   if (parseToken(lltok::lparen, "expected '(' here") ||
8954       parseToken(lltok::kw_callee, "expected 'callee' here") ||
8955       parseToken(lltok::colon, "expected ':' here"))
8956     return true;
8957 
8958   unsigned GVId;
8959   ValueInfo VI;
8960   LocTy Loc = Lex.getLoc();
8961   if (parseGVReference(VI, GVId))
8962     return true;
8963 
8964   Call.Callee = VI;
8965   IdLocList.emplace_back(GVId, Loc);
8966 
8967   if (parseToken(lltok::comma, "expected ',' here") ||
8968       parseParamNo(Call.ParamNo) ||
8969       parseToken(lltok::comma, "expected ',' here") ||
8970       parseParamAccessOffset(Call.Offsets))
8971     return true;
8972 
8973   if (parseToken(lltok::rparen, "expected ')' here"))
8974     return true;
8975 
8976   return false;
8977 }
8978 
8979 /// ParamAccess
8980 ///   := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
8981 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
8982 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
8983                                 IdLocListType &IdLocList) {
8984   if (parseToken(lltok::lparen, "expected '(' here") ||
8985       parseParamNo(Param.ParamNo) ||
8986       parseToken(lltok::comma, "expected ',' here") ||
8987       parseParamAccessOffset(Param.Use))
8988     return true;
8989 
8990   if (EatIfPresent(lltok::comma)) {
8991     if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
8992         parseToken(lltok::colon, "expected ':' here") ||
8993         parseToken(lltok::lparen, "expected '(' here"))
8994       return true;
8995     do {
8996       FunctionSummary::ParamAccess::Call Call;
8997       if (parseParamAccessCall(Call, IdLocList))
8998         return true;
8999       Param.Calls.push_back(Call);
9000     } while (EatIfPresent(lltok::comma));
9001 
9002     if (parseToken(lltok::rparen, "expected ')' here"))
9003       return true;
9004   }
9005 
9006   if (parseToken(lltok::rparen, "expected ')' here"))
9007     return true;
9008 
9009   return false;
9010 }
9011 
9012 /// OptionalParamAccesses
9013 ///   := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9014 bool LLParser::parseOptionalParamAccesses(
9015     std::vector<FunctionSummary::ParamAccess> &Params) {
9016   assert(Lex.getKind() == lltok::kw_params);
9017   Lex.Lex();
9018 
9019   if (parseToken(lltok::colon, "expected ':' here") ||
9020       parseToken(lltok::lparen, "expected '(' here"))
9021     return true;
9022 
9023   IdLocListType VContexts;
9024   size_t CallsNum = 0;
9025   do {
9026     FunctionSummary::ParamAccess ParamAccess;
9027     if (parseParamAccess(ParamAccess, VContexts))
9028       return true;
9029     CallsNum += ParamAccess.Calls.size();
9030     assert(VContexts.size() == CallsNum);
9031     (void)CallsNum;
9032     Params.emplace_back(std::move(ParamAccess));
9033   } while (EatIfPresent(lltok::comma));
9034 
9035   if (parseToken(lltok::rparen, "expected ')' here"))
9036     return true;
9037 
9038   // Now that the Params is finalized, it is safe to save the locations
9039   // of any forward GV references that need updating later.
9040   IdLocListType::const_iterator ItContext = VContexts.begin();
9041   for (auto &PA : Params) {
9042     for (auto &C : PA.Calls) {
9043       if (C.Callee.getRef() == FwdVIRef)
9044         ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9045                                                             ItContext->second);
9046       ++ItContext;
9047     }
9048   }
9049   assert(ItContext == VContexts.end());
9050 
9051   return false;
9052 }
9053 
9054 /// OptionalRefs
9055 ///   := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9056 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9057   assert(Lex.getKind() == lltok::kw_refs);
9058   Lex.Lex();
9059 
9060   if (parseToken(lltok::colon, "expected ':' in refs") ||
9061       parseToken(lltok::lparen, "expected '(' in refs"))
9062     return true;
9063 
9064   struct ValueContext {
9065     ValueInfo VI;
9066     unsigned GVId;
9067     LocTy Loc;
9068   };
9069   std::vector<ValueContext> VContexts;
9070   // parse each ref edge
9071   do {
9072     ValueContext VC;
9073     VC.Loc = Lex.getLoc();
9074     if (parseGVReference(VC.VI, VC.GVId))
9075       return true;
9076     VContexts.push_back(VC);
9077   } while (EatIfPresent(lltok::comma));
9078 
9079   // Sort value contexts so that ones with writeonly
9080   // and readonly ValueInfo  are at the end of VContexts vector.
9081   // See FunctionSummary::specialRefCounts()
9082   llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9083     return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9084   });
9085 
9086   IdToIndexMapType IdToIndexMap;
9087   for (auto &VC : VContexts) {
9088     // Keep track of the Refs array index needing a forward reference.
9089     // We will save the location of the ValueInfo needing an update, but
9090     // can only do so once the std::vector is finalized.
9091     if (VC.VI.getRef() == FwdVIRef)
9092       IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9093     Refs.push_back(VC.VI);
9094   }
9095 
9096   // Now that the Refs vector is finalized, it is safe to save the locations
9097   // of any forward GV references that need updating later.
9098   for (auto I : IdToIndexMap) {
9099     auto &Infos = ForwardRefValueInfos[I.first];
9100     for (auto P : I.second) {
9101       assert(Refs[P.first].getRef() == FwdVIRef &&
9102              "Forward referenced ValueInfo expected to be empty");
9103       Infos.emplace_back(&Refs[P.first], P.second);
9104     }
9105   }
9106 
9107   if (parseToken(lltok::rparen, "expected ')' in refs"))
9108     return true;
9109 
9110   return false;
9111 }
9112 
9113 /// OptionalTypeIdInfo
9114 ///   := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9115 ///         [',' TypeCheckedLoadVCalls]?  [',' TypeTestAssumeConstVCalls]?
9116 ///         [',' TypeCheckedLoadConstVCalls]? ')'
9117 bool LLParser::parseOptionalTypeIdInfo(
9118     FunctionSummary::TypeIdInfo &TypeIdInfo) {
9119   assert(Lex.getKind() == lltok::kw_typeIdInfo);
9120   Lex.Lex();
9121 
9122   if (parseToken(lltok::colon, "expected ':' here") ||
9123       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9124     return true;
9125 
9126   do {
9127     switch (Lex.getKind()) {
9128     case lltok::kw_typeTests:
9129       if (parseTypeTests(TypeIdInfo.TypeTests))
9130         return true;
9131       break;
9132     case lltok::kw_typeTestAssumeVCalls:
9133       if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9134                            TypeIdInfo.TypeTestAssumeVCalls))
9135         return true;
9136       break;
9137     case lltok::kw_typeCheckedLoadVCalls:
9138       if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9139                            TypeIdInfo.TypeCheckedLoadVCalls))
9140         return true;
9141       break;
9142     case lltok::kw_typeTestAssumeConstVCalls:
9143       if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9144                               TypeIdInfo.TypeTestAssumeConstVCalls))
9145         return true;
9146       break;
9147     case lltok::kw_typeCheckedLoadConstVCalls:
9148       if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9149                               TypeIdInfo.TypeCheckedLoadConstVCalls))
9150         return true;
9151       break;
9152     default:
9153       return error(Lex.getLoc(), "invalid typeIdInfo list type");
9154     }
9155   } while (EatIfPresent(lltok::comma));
9156 
9157   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9158     return true;
9159 
9160   return false;
9161 }
9162 
9163 /// TypeTests
9164 ///   ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9165 ///         [',' (SummaryID | UInt64)]* ')'
9166 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9167   assert(Lex.getKind() == lltok::kw_typeTests);
9168   Lex.Lex();
9169 
9170   if (parseToken(lltok::colon, "expected ':' here") ||
9171       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9172     return true;
9173 
9174   IdToIndexMapType IdToIndexMap;
9175   do {
9176     GlobalValue::GUID GUID = 0;
9177     if (Lex.getKind() == lltok::SummaryID) {
9178       unsigned ID = Lex.getUIntVal();
9179       LocTy Loc = Lex.getLoc();
9180       // Keep track of the TypeTests array index needing a forward reference.
9181       // We will save the location of the GUID needing an update, but
9182       // can only do so once the std::vector is finalized.
9183       IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9184       Lex.Lex();
9185     } else if (parseUInt64(GUID))
9186       return true;
9187     TypeTests.push_back(GUID);
9188   } while (EatIfPresent(lltok::comma));
9189 
9190   // Now that the TypeTests vector is finalized, it is safe to save the
9191   // locations of any forward GV references that need updating later.
9192   for (auto I : IdToIndexMap) {
9193     auto &Ids = ForwardRefTypeIds[I.first];
9194     for (auto P : I.second) {
9195       assert(TypeTests[P.first] == 0 &&
9196              "Forward referenced type id GUID expected to be 0");
9197       Ids.emplace_back(&TypeTests[P.first], P.second);
9198     }
9199   }
9200 
9201   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9202     return true;
9203 
9204   return false;
9205 }
9206 
9207 /// VFuncIdList
9208 ///   ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9209 bool LLParser::parseVFuncIdList(
9210     lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9211   assert(Lex.getKind() == Kind);
9212   Lex.Lex();
9213 
9214   if (parseToken(lltok::colon, "expected ':' here") ||
9215       parseToken(lltok::lparen, "expected '(' here"))
9216     return true;
9217 
9218   IdToIndexMapType IdToIndexMap;
9219   do {
9220     FunctionSummary::VFuncId VFuncId;
9221     if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9222       return true;
9223     VFuncIdList.push_back(VFuncId);
9224   } while (EatIfPresent(lltok::comma));
9225 
9226   if (parseToken(lltok::rparen, "expected ')' here"))
9227     return true;
9228 
9229   // Now that the VFuncIdList vector is finalized, it is safe to save the
9230   // locations of any forward GV references that need updating later.
9231   for (auto I : IdToIndexMap) {
9232     auto &Ids = ForwardRefTypeIds[I.first];
9233     for (auto P : I.second) {
9234       assert(VFuncIdList[P.first].GUID == 0 &&
9235              "Forward referenced type id GUID expected to be 0");
9236       Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9237     }
9238   }
9239 
9240   return false;
9241 }
9242 
9243 /// ConstVCallList
9244 ///   ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9245 bool LLParser::parseConstVCallList(
9246     lltok::Kind Kind,
9247     std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9248   assert(Lex.getKind() == Kind);
9249   Lex.Lex();
9250 
9251   if (parseToken(lltok::colon, "expected ':' here") ||
9252       parseToken(lltok::lparen, "expected '(' here"))
9253     return true;
9254 
9255   IdToIndexMapType IdToIndexMap;
9256   do {
9257     FunctionSummary::ConstVCall ConstVCall;
9258     if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9259       return true;
9260     ConstVCallList.push_back(ConstVCall);
9261   } while (EatIfPresent(lltok::comma));
9262 
9263   if (parseToken(lltok::rparen, "expected ')' here"))
9264     return true;
9265 
9266   // Now that the ConstVCallList vector is finalized, it is safe to save the
9267   // locations of any forward GV references that need updating later.
9268   for (auto I : IdToIndexMap) {
9269     auto &Ids = ForwardRefTypeIds[I.first];
9270     for (auto P : I.second) {
9271       assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9272              "Forward referenced type id GUID expected to be 0");
9273       Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9274     }
9275   }
9276 
9277   return false;
9278 }
9279 
9280 /// ConstVCall
9281 ///   ::= '(' VFuncId ',' Args ')'
9282 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9283                                IdToIndexMapType &IdToIndexMap, unsigned Index) {
9284   if (parseToken(lltok::lparen, "expected '(' here") ||
9285       parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9286     return true;
9287 
9288   if (EatIfPresent(lltok::comma))
9289     if (parseArgs(ConstVCall.Args))
9290       return true;
9291 
9292   if (parseToken(lltok::rparen, "expected ')' here"))
9293     return true;
9294 
9295   return false;
9296 }
9297 
9298 /// VFuncId
9299 ///   ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9300 ///         'offset' ':' UInt64 ')'
9301 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9302                             IdToIndexMapType &IdToIndexMap, unsigned Index) {
9303   assert(Lex.getKind() == lltok::kw_vFuncId);
9304   Lex.Lex();
9305 
9306   if (parseToken(lltok::colon, "expected ':' here") ||
9307       parseToken(lltok::lparen, "expected '(' here"))
9308     return true;
9309 
9310   if (Lex.getKind() == lltok::SummaryID) {
9311     VFuncId.GUID = 0;
9312     unsigned ID = Lex.getUIntVal();
9313     LocTy Loc = Lex.getLoc();
9314     // Keep track of the array index needing a forward reference.
9315     // We will save the location of the GUID needing an update, but
9316     // can only do so once the caller's std::vector is finalized.
9317     IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9318     Lex.Lex();
9319   } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9320              parseToken(lltok::colon, "expected ':' here") ||
9321              parseUInt64(VFuncId.GUID))
9322     return true;
9323 
9324   if (parseToken(lltok::comma, "expected ',' here") ||
9325       parseToken(lltok::kw_offset, "expected 'offset' here") ||
9326       parseToken(lltok::colon, "expected ':' here") ||
9327       parseUInt64(VFuncId.Offset) ||
9328       parseToken(lltok::rparen, "expected ')' here"))
9329     return true;
9330 
9331   return false;
9332 }
9333 
9334 /// GVFlags
9335 ///   ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9336 ///         'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9337 ///         'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9338 ///         'canAutoHide' ':' Flag ',' ')'
9339 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9340   assert(Lex.getKind() == lltok::kw_flags);
9341   Lex.Lex();
9342 
9343   if (parseToken(lltok::colon, "expected ':' here") ||
9344       parseToken(lltok::lparen, "expected '(' here"))
9345     return true;
9346 
9347   do {
9348     unsigned Flag = 0;
9349     switch (Lex.getKind()) {
9350     case lltok::kw_linkage:
9351       Lex.Lex();
9352       if (parseToken(lltok::colon, "expected ':'"))
9353         return true;
9354       bool HasLinkage;
9355       GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9356       assert(HasLinkage && "Linkage not optional in summary entry");
9357       Lex.Lex();
9358       break;
9359     case lltok::kw_visibility:
9360       Lex.Lex();
9361       if (parseToken(lltok::colon, "expected ':'"))
9362         return true;
9363       parseOptionalVisibility(Flag);
9364       GVFlags.Visibility = Flag;
9365       break;
9366     case lltok::kw_notEligibleToImport:
9367       Lex.Lex();
9368       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9369         return true;
9370       GVFlags.NotEligibleToImport = Flag;
9371       break;
9372     case lltok::kw_live:
9373       Lex.Lex();
9374       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9375         return true;
9376       GVFlags.Live = Flag;
9377       break;
9378     case lltok::kw_dsoLocal:
9379       Lex.Lex();
9380       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9381         return true;
9382       GVFlags.DSOLocal = Flag;
9383       break;
9384     case lltok::kw_canAutoHide:
9385       Lex.Lex();
9386       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9387         return true;
9388       GVFlags.CanAutoHide = Flag;
9389       break;
9390     default:
9391       return error(Lex.getLoc(), "expected gv flag type");
9392     }
9393   } while (EatIfPresent(lltok::comma));
9394 
9395   if (parseToken(lltok::rparen, "expected ')' here"))
9396     return true;
9397 
9398   return false;
9399 }
9400 
9401 /// GVarFlags
9402 ///   ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9403 ///                      ',' 'writeonly' ':' Flag
9404 ///                      ',' 'constant' ':' Flag ')'
9405 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9406   assert(Lex.getKind() == lltok::kw_varFlags);
9407   Lex.Lex();
9408 
9409   if (parseToken(lltok::colon, "expected ':' here") ||
9410       parseToken(lltok::lparen, "expected '(' here"))
9411     return true;
9412 
9413   auto ParseRest = [this](unsigned int &Val) {
9414     Lex.Lex();
9415     if (parseToken(lltok::colon, "expected ':'"))
9416       return true;
9417     return parseFlag(Val);
9418   };
9419 
9420   do {
9421     unsigned Flag = 0;
9422     switch (Lex.getKind()) {
9423     case lltok::kw_readonly:
9424       if (ParseRest(Flag))
9425         return true;
9426       GVarFlags.MaybeReadOnly = Flag;
9427       break;
9428     case lltok::kw_writeonly:
9429       if (ParseRest(Flag))
9430         return true;
9431       GVarFlags.MaybeWriteOnly = Flag;
9432       break;
9433     case lltok::kw_constant:
9434       if (ParseRest(Flag))
9435         return true;
9436       GVarFlags.Constant = Flag;
9437       break;
9438     case lltok::kw_vcall_visibility:
9439       if (ParseRest(Flag))
9440         return true;
9441       GVarFlags.VCallVisibility = Flag;
9442       break;
9443     default:
9444       return error(Lex.getLoc(), "expected gvar flag type");
9445     }
9446   } while (EatIfPresent(lltok::comma));
9447   return parseToken(lltok::rparen, "expected ')' here");
9448 }
9449 
9450 /// ModuleReference
9451 ///   ::= 'module' ':' UInt
9452 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9453   // parse module id.
9454   if (parseToken(lltok::kw_module, "expected 'module' here") ||
9455       parseToken(lltok::colon, "expected ':' here") ||
9456       parseToken(lltok::SummaryID, "expected module ID"))
9457     return true;
9458 
9459   unsigned ModuleID = Lex.getUIntVal();
9460   auto I = ModuleIdMap.find(ModuleID);
9461   // We should have already parsed all module IDs
9462   assert(I != ModuleIdMap.end());
9463   ModulePath = I->second;
9464   return false;
9465 }
9466 
9467 /// GVReference
9468 ///   ::= SummaryID
9469 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9470   bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9471   if (!ReadOnly)
9472     WriteOnly = EatIfPresent(lltok::kw_writeonly);
9473   if (parseToken(lltok::SummaryID, "expected GV ID"))
9474     return true;
9475 
9476   GVId = Lex.getUIntVal();
9477   // Check if we already have a VI for this GV
9478   if (GVId < NumberedValueInfos.size()) {
9479     assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9480     VI = NumberedValueInfos[GVId];
9481   } else
9482     // We will create a forward reference to the stored location.
9483     VI = ValueInfo(false, FwdVIRef);
9484 
9485   if (ReadOnly)
9486     VI.setReadOnly();
9487   if (WriteOnly)
9488     VI.setWriteOnly();
9489   return false;
9490 }
9491