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