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