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