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