1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LLParser.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.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/Constants.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalObject.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/IR/ValueSymbolTable.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstring>
52 #include <iterator>
53 #include <vector>
54 
55 using namespace llvm;
56 
57 static std::string getTypeString(Type *T) {
58   std::string Result;
59   raw_string_ostream Tmp(Result);
60   Tmp << *T;
61   return Tmp.str();
62 }
63 
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run() {
66   // Prime the lexer.
67   Lex.Lex();
68 
69   if (Context.shouldDiscardValueNames())
70     return Error(
71         Lex.getLoc(),
72         "Can't read textual IR with a Context that discards named Values");
73 
74   return ParseTopLevelEntities() ||
75          ValidateEndOfModule();
76 }
77 
78 bool LLParser::parseStandaloneConstantValue(Constant *&C,
79                                             const SlotMapping *Slots) {
80   restoreParsingState(Slots);
81   Lex.Lex();
82 
83   Type *Ty = nullptr;
84   if (ParseType(Ty) || parseConstantValue(Ty, C))
85     return true;
86   if (Lex.getKind() != lltok::Eof)
87     return Error(Lex.getLoc(), "expected end of string");
88   return false;
89 }
90 
91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92                                     const SlotMapping *Slots) {
93   restoreParsingState(Slots);
94   Lex.Lex();
95 
96   Read = 0;
97   SMLoc Start = Lex.getLoc();
98   Ty = nullptr;
99   if (ParseType(Ty))
100     return true;
101   SMLoc End = Lex.getLoc();
102   Read = End.getPointer() - Start.getPointer();
103 
104   return false;
105 }
106 
107 void LLParser::restoreParsingState(const SlotMapping *Slots) {
108   if (!Slots)
109     return;
110   NumberedVals = Slots->GlobalValues;
111   NumberedMetadata = Slots->MetadataNodes;
112   for (const auto &I : Slots->NamedTypes)
113     NamedTypes.insert(
114         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115   for (const auto &I : Slots->Types)
116     NumberedTypes.insert(
117         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118 }
119 
120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121 /// module.
122 bool LLParser::ValidateEndOfModule() {
123   // Handle any function attribute group forward references.
124   for (const auto &RAG : ForwardRefAttrGroups) {
125     Value *V = RAG.first;
126     const std::vector<unsigned> &Attrs = RAG.second;
127     AttrBuilder B;
128 
129     for (const auto &Attr : Attrs)
130       B.merge(NumberedAttrBuilders[Attr]);
131 
132     if (Function *Fn = dyn_cast<Function>(V)) {
133       AttributeList AS = Fn->getAttributes();
134       AttrBuilder FnAttrs(AS.getFnAttributes());
135       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
136 
137       FnAttrs.merge(B);
138 
139       // If the alignment was parsed as an attribute, move to the alignment
140       // field.
141       if (FnAttrs.hasAlignmentAttr()) {
142         Fn->setAlignment(FnAttrs.getAlignment());
143         FnAttrs.removeAttribute(Attribute::Alignment);
144       }
145 
146       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147                             AttributeSet::get(Context, FnAttrs));
148       Fn->setAttributes(AS);
149     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
150       AttributeList AS = CI->getAttributes();
151       AttrBuilder FnAttrs(AS.getFnAttributes());
152       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
153       FnAttrs.merge(B);
154       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155                             AttributeSet::get(Context, FnAttrs));
156       CI->setAttributes(AS);
157     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
158       AttributeList AS = II->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       II->setAttributes(AS);
165     } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166       AttrBuilder Attrs(GV->getAttributes());
167       Attrs.merge(B);
168       GV->setAttributes(AttributeSet::get(Context,Attrs));
169     } else {
170       llvm_unreachable("invalid object with forward attribute group reference");
171     }
172   }
173 
174   // If there are entries in ForwardRefBlockAddresses at this point, the
175   // function was never defined.
176   if (!ForwardRefBlockAddresses.empty())
177     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178                  "expected function name in blockaddress");
179 
180   for (const auto &NT : NumberedTypes)
181     if (NT.second.second.isValid())
182       return Error(NT.second.second,
183                    "use of undefined type '%" + Twine(NT.first) + "'");
184 
185   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187     if (I->second.second.isValid())
188       return Error(I->second.second,
189                    "use of undefined type named '" + I->getKey() + "'");
190 
191   if (!ForwardRefComdats.empty())
192     return Error(ForwardRefComdats.begin()->second,
193                  "use of undefined comdat '$" +
194                      ForwardRefComdats.begin()->first + "'");
195 
196   if (!ForwardRefVals.empty())
197     return Error(ForwardRefVals.begin()->second.second,
198                  "use of undefined value '@" + ForwardRefVals.begin()->first +
199                  "'");
200 
201   if (!ForwardRefValIDs.empty())
202     return Error(ForwardRefValIDs.begin()->second.second,
203                  "use of undefined value '@" +
204                  Twine(ForwardRefValIDs.begin()->first) + "'");
205 
206   if (!ForwardRefMDNodes.empty())
207     return Error(ForwardRefMDNodes.begin()->second.second,
208                  "use of undefined metadata '!" +
209                  Twine(ForwardRefMDNodes.begin()->first) + "'");
210 
211   // Resolve metadata cycles.
212   for (auto &N : NumberedMetadata) {
213     if (N.second && !N.second->isResolved())
214       N.second->resolveCycles();
215   }
216 
217   for (auto *Inst : InstsWithTBAATag) {
218     MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219     assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220     auto *UpgradedMD = UpgradeTBAANode(*MD);
221     if (MD != UpgradedMD)
222       Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
223   }
224 
225   // Look for intrinsic functions and CallInst that need to be upgraded
226   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
227     UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
228 
229   // Some types could be renamed during loading if several modules are
230   // loaded in the same LLVMContext (LTO scenario). In this case we should
231   // remangle intrinsics names as well.
232   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233     Function *F = &*FI++;
234     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235       F->replaceAllUsesWith(Remangled.getValue());
236       F->eraseFromParent();
237     }
238   }
239 
240   UpgradeDebugInfo(*M);
241 
242   UpgradeModuleFlags(*M);
243 
244   if (!Slots)
245     return false;
246   // Initialize the slot mapping.
247   // Because by this point we've parsed and validated everything, we can "steal"
248   // the mapping from LLParser as it doesn't need it anymore.
249   Slots->GlobalValues = std::move(NumberedVals);
250   Slots->MetadataNodes = std::move(NumberedMetadata);
251   for (const auto &I : NamedTypes)
252     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
253   for (const auto &I : NumberedTypes)
254     Slots->Types.insert(std::make_pair(I.first, I.second.first));
255 
256   return false;
257 }
258 
259 //===----------------------------------------------------------------------===//
260 // Top-Level Entities
261 //===----------------------------------------------------------------------===//
262 
263 bool LLParser::ParseTopLevelEntities() {
264   while (true) {
265     switch (Lex.getKind()) {
266     default:         return TokError("expected top-level entity");
267     case lltok::Eof: return false;
268     case lltok::kw_declare: if (ParseDeclare()) return true; break;
269     case lltok::kw_define:  if (ParseDefine()) return true; break;
270     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
271     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
272     case lltok::kw_source_filename:
273       if (ParseSourceFileName())
274         return true;
275       break;
276     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
277     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
278     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
279     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
280     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
281     case lltok::ComdatVar:  if (parseComdat()) return true; break;
282     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
283     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
284     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
285     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
286     case lltok::kw_uselistorder_bb:
287       if (ParseUseListOrderBB())
288         return true;
289       break;
290     }
291   }
292 }
293 
294 /// toplevelentity
295 ///   ::= 'module' 'asm' STRINGCONSTANT
296 bool LLParser::ParseModuleAsm() {
297   assert(Lex.getKind() == lltok::kw_module);
298   Lex.Lex();
299 
300   std::string AsmStr;
301   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
302       ParseStringConstant(AsmStr)) return true;
303 
304   M->appendModuleInlineAsm(AsmStr);
305   return false;
306 }
307 
308 /// toplevelentity
309 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
310 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
311 bool LLParser::ParseTargetDefinition() {
312   assert(Lex.getKind() == lltok::kw_target);
313   std::string Str;
314   switch (Lex.Lex()) {
315   default: return TokError("unknown target property");
316   case lltok::kw_triple:
317     Lex.Lex();
318     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
319         ParseStringConstant(Str))
320       return true;
321     M->setTargetTriple(Str);
322     return false;
323   case lltok::kw_datalayout:
324     Lex.Lex();
325     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
326         ParseStringConstant(Str))
327       return true;
328     M->setDataLayout(Str);
329     return false;
330   }
331 }
332 
333 /// toplevelentity
334 ///   ::= 'source_filename' '=' STRINGCONSTANT
335 bool LLParser::ParseSourceFileName() {
336   assert(Lex.getKind() == lltok::kw_source_filename);
337   std::string Str;
338   Lex.Lex();
339   if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
340       ParseStringConstant(Str))
341     return true;
342   M->setSourceFileName(Str);
343   return false;
344 }
345 
346 /// toplevelentity
347 ///   ::= 'deplibs' '=' '[' ']'
348 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
349 /// FIXME: Remove in 4.0. Currently parse, but ignore.
350 bool LLParser::ParseDepLibs() {
351   assert(Lex.getKind() == lltok::kw_deplibs);
352   Lex.Lex();
353   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
354       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
355     return true;
356 
357   if (EatIfPresent(lltok::rsquare))
358     return false;
359 
360   do {
361     std::string Str;
362     if (ParseStringConstant(Str)) return true;
363   } while (EatIfPresent(lltok::comma));
364 
365   return ParseToken(lltok::rsquare, "expected ']' at end of list");
366 }
367 
368 /// ParseUnnamedType:
369 ///   ::= LocalVarID '=' 'type' type
370 bool LLParser::ParseUnnamedType() {
371   LocTy TypeLoc = Lex.getLoc();
372   unsigned TypeID = Lex.getUIntVal();
373   Lex.Lex(); // eat LocalVarID;
374 
375   if (ParseToken(lltok::equal, "expected '=' after name") ||
376       ParseToken(lltok::kw_type, "expected 'type' after '='"))
377     return true;
378 
379   Type *Result = nullptr;
380   if (ParseStructDefinition(TypeLoc, "",
381                             NumberedTypes[TypeID], Result)) return true;
382 
383   if (!isa<StructType>(Result)) {
384     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
385     if (Entry.first)
386       return Error(TypeLoc, "non-struct types may not be recursive");
387     Entry.first = Result;
388     Entry.second = SMLoc();
389   }
390 
391   return false;
392 }
393 
394 /// toplevelentity
395 ///   ::= LocalVar '=' 'type' type
396 bool LLParser::ParseNamedType() {
397   std::string Name = Lex.getStrVal();
398   LocTy NameLoc = Lex.getLoc();
399   Lex.Lex();  // eat LocalVar.
400 
401   if (ParseToken(lltok::equal, "expected '=' after name") ||
402       ParseToken(lltok::kw_type, "expected 'type' after name"))
403     return true;
404 
405   Type *Result = nullptr;
406   if (ParseStructDefinition(NameLoc, Name,
407                             NamedTypes[Name], Result)) return true;
408 
409   if (!isa<StructType>(Result)) {
410     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
411     if (Entry.first)
412       return Error(NameLoc, "non-struct types may not be recursive");
413     Entry.first = Result;
414     Entry.second = SMLoc();
415   }
416 
417   return false;
418 }
419 
420 /// toplevelentity
421 ///   ::= 'declare' FunctionHeader
422 bool LLParser::ParseDeclare() {
423   assert(Lex.getKind() == lltok::kw_declare);
424   Lex.Lex();
425 
426   std::vector<std::pair<unsigned, MDNode *>> MDs;
427   while (Lex.getKind() == lltok::MetadataVar) {
428     unsigned MDK;
429     MDNode *N;
430     if (ParseMetadataAttachment(MDK, N))
431       return true;
432     MDs.push_back({MDK, N});
433   }
434 
435   Function *F;
436   if (ParseFunctionHeader(F, false))
437     return true;
438   for (auto &MD : MDs)
439     F->addMetadata(MD.first, *MD.second);
440   return false;
441 }
442 
443 /// toplevelentity
444 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
445 bool LLParser::ParseDefine() {
446   assert(Lex.getKind() == lltok::kw_define);
447   Lex.Lex();
448 
449   Function *F;
450   return ParseFunctionHeader(F, true) ||
451          ParseOptionalFunctionMetadata(*F) ||
452          ParseFunctionBody(*F);
453 }
454 
455 /// ParseGlobalType
456 ///   ::= 'constant'
457 ///   ::= 'global'
458 bool LLParser::ParseGlobalType(bool &IsConstant) {
459   if (Lex.getKind() == lltok::kw_constant)
460     IsConstant = true;
461   else if (Lex.getKind() == lltok::kw_global)
462     IsConstant = false;
463   else {
464     IsConstant = false;
465     return TokError("expected 'global' or 'constant'");
466   }
467   Lex.Lex();
468   return false;
469 }
470 
471 bool LLParser::ParseOptionalUnnamedAddr(
472     GlobalVariable::UnnamedAddr &UnnamedAddr) {
473   if (EatIfPresent(lltok::kw_unnamed_addr))
474     UnnamedAddr = GlobalValue::UnnamedAddr::Global;
475   else if (EatIfPresent(lltok::kw_local_unnamed_addr))
476     UnnamedAddr = GlobalValue::UnnamedAddr::Local;
477   else
478     UnnamedAddr = GlobalValue::UnnamedAddr::None;
479   return false;
480 }
481 
482 /// ParseUnnamedGlobal:
483 ///   OptionalVisibility (ALIAS | IFUNC) ...
484 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
485 ///                                                     ...   -> global variable
486 ///   GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
487 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
488 ///                                                     ...   -> global variable
489 bool LLParser::ParseUnnamedGlobal() {
490   unsigned VarID = NumberedVals.size();
491   std::string Name;
492   LocTy NameLoc = Lex.getLoc();
493 
494   // Handle the GlobalID form.
495   if (Lex.getKind() == lltok::GlobalID) {
496     if (Lex.getUIntVal() != VarID)
497       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
498                    Twine(VarID) + "'");
499     Lex.Lex(); // eat GlobalID;
500 
501     if (ParseToken(lltok::equal, "expected '=' after name"))
502       return true;
503   }
504 
505   bool HasLinkage;
506   unsigned Linkage, Visibility, DLLStorageClass;
507   GlobalVariable::ThreadLocalMode TLM;
508   GlobalVariable::UnnamedAddr UnnamedAddr;
509   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
510       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
511     return true;
512 
513   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
514     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
515                        DLLStorageClass, TLM, UnnamedAddr);
516 
517   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
518                              DLLStorageClass, TLM, UnnamedAddr);
519 }
520 
521 /// ParseNamedGlobal:
522 ///   GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
523 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
524 ///                                                     ...   -> global variable
525 bool LLParser::ParseNamedGlobal() {
526   assert(Lex.getKind() == lltok::GlobalVar);
527   LocTy NameLoc = Lex.getLoc();
528   std::string Name = Lex.getStrVal();
529   Lex.Lex();
530 
531   bool HasLinkage;
532   unsigned Linkage, Visibility, DLLStorageClass;
533   GlobalVariable::ThreadLocalMode TLM;
534   GlobalVariable::UnnamedAddr UnnamedAddr;
535   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
536       ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
537       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
538     return true;
539 
540   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
541     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
542                        DLLStorageClass, TLM, UnnamedAddr);
543 
544   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
545                              DLLStorageClass, TLM, UnnamedAddr);
546 }
547 
548 bool LLParser::parseComdat() {
549   assert(Lex.getKind() == lltok::ComdatVar);
550   std::string Name = Lex.getStrVal();
551   LocTy NameLoc = Lex.getLoc();
552   Lex.Lex();
553 
554   if (ParseToken(lltok::equal, "expected '=' here"))
555     return true;
556 
557   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
558     return TokError("expected comdat type");
559 
560   Comdat::SelectionKind SK;
561   switch (Lex.getKind()) {
562   default:
563     return TokError("unknown selection kind");
564   case lltok::kw_any:
565     SK = Comdat::Any;
566     break;
567   case lltok::kw_exactmatch:
568     SK = Comdat::ExactMatch;
569     break;
570   case lltok::kw_largest:
571     SK = Comdat::Largest;
572     break;
573   case lltok::kw_noduplicates:
574     SK = Comdat::NoDuplicates;
575     break;
576   case lltok::kw_samesize:
577     SK = Comdat::SameSize;
578     break;
579   }
580   Lex.Lex();
581 
582   // See if the comdat was forward referenced, if so, use the comdat.
583   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
584   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
585   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
586     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
587 
588   Comdat *C;
589   if (I != ComdatSymTab.end())
590     C = &I->second;
591   else
592     C = M->getOrInsertComdat(Name);
593   C->setSelectionKind(SK);
594 
595   return false;
596 }
597 
598 // MDString:
599 //   ::= '!' STRINGCONSTANT
600 bool LLParser::ParseMDString(MDString *&Result) {
601   std::string Str;
602   if (ParseStringConstant(Str)) return true;
603   Result = MDString::get(Context, Str);
604   return false;
605 }
606 
607 // MDNode:
608 //   ::= '!' MDNodeNumber
609 bool LLParser::ParseMDNodeID(MDNode *&Result) {
610   // !{ ..., !42, ... }
611   LocTy IDLoc = Lex.getLoc();
612   unsigned MID = 0;
613   if (ParseUInt32(MID))
614     return true;
615 
616   // If not a forward reference, just return it now.
617   if (NumberedMetadata.count(MID)) {
618     Result = NumberedMetadata[MID];
619     return false;
620   }
621 
622   // Otherwise, create MDNode forward reference.
623   auto &FwdRef = ForwardRefMDNodes[MID];
624   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
625 
626   Result = FwdRef.first.get();
627   NumberedMetadata[MID].reset(Result);
628   return false;
629 }
630 
631 /// ParseNamedMetadata:
632 ///   !foo = !{ !1, !2 }
633 bool LLParser::ParseNamedMetadata() {
634   assert(Lex.getKind() == lltok::MetadataVar);
635   std::string Name = Lex.getStrVal();
636   Lex.Lex();
637 
638   if (ParseToken(lltok::equal, "expected '=' here") ||
639       ParseToken(lltok::exclaim, "Expected '!' here") ||
640       ParseToken(lltok::lbrace, "Expected '{' here"))
641     return true;
642 
643   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
644   if (Lex.getKind() != lltok::rbrace)
645     do {
646       if (ParseToken(lltok::exclaim, "Expected '!' here"))
647         return true;
648 
649       MDNode *N = nullptr;
650       if (ParseMDNodeID(N)) return true;
651       NMD->addOperand(N);
652     } while (EatIfPresent(lltok::comma));
653 
654   return ParseToken(lltok::rbrace, "expected end of metadata node");
655 }
656 
657 /// ParseStandaloneMetadata:
658 ///   !42 = !{...}
659 bool LLParser::ParseStandaloneMetadata() {
660   assert(Lex.getKind() == lltok::exclaim);
661   Lex.Lex();
662   unsigned MetadataID = 0;
663 
664   MDNode *Init;
665   if (ParseUInt32(MetadataID) ||
666       ParseToken(lltok::equal, "expected '=' here"))
667     return true;
668 
669   // Detect common error, from old metadata syntax.
670   if (Lex.getKind() == lltok::Type)
671     return TokError("unexpected type in metadata definition");
672 
673   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
674   if (Lex.getKind() == lltok::MetadataVar) {
675     if (ParseSpecializedMDNode(Init, IsDistinct))
676       return true;
677   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
678              ParseMDTuple(Init, IsDistinct))
679     return true;
680 
681   // See if this was forward referenced, if so, handle it.
682   auto FI = ForwardRefMDNodes.find(MetadataID);
683   if (FI != ForwardRefMDNodes.end()) {
684     FI->second.first->replaceAllUsesWith(Init);
685     ForwardRefMDNodes.erase(FI);
686 
687     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
688   } else {
689     if (NumberedMetadata.count(MetadataID))
690       return TokError("Metadata id is already used");
691     NumberedMetadata[MetadataID].reset(Init);
692   }
693 
694   return false;
695 }
696 
697 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
698   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
699          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
700 }
701 
702 /// parseIndirectSymbol:
703 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
704 ///                     OptionalDLLStorageClass OptionalThreadLocal
705 ///                     OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
706 ///
707 /// IndirectSymbol
708 ///   ::= TypeAndValue
709 ///
710 /// Everything through OptionalUnnamedAddr has already been parsed.
711 ///
712 bool LLParser::parseIndirectSymbol(
713     const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
714     unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
715     GlobalVariable::UnnamedAddr UnnamedAddr) {
716   bool IsAlias;
717   if (Lex.getKind() == lltok::kw_alias)
718     IsAlias = true;
719   else if (Lex.getKind() == lltok::kw_ifunc)
720     IsAlias = false;
721   else
722     llvm_unreachable("Not an alias or ifunc!");
723   Lex.Lex();
724 
725   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
726 
727   if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
728     return Error(NameLoc, "invalid linkage type for alias");
729 
730   if (!isValidVisibilityForLinkage(Visibility, L))
731     return Error(NameLoc,
732                  "symbol with local linkage must have default visibility");
733 
734   Type *Ty;
735   LocTy ExplicitTypeLoc = Lex.getLoc();
736   if (ParseType(Ty) ||
737       ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
738     return true;
739 
740   Constant *Aliasee;
741   LocTy AliaseeLoc = Lex.getLoc();
742   if (Lex.getKind() != lltok::kw_bitcast &&
743       Lex.getKind() != lltok::kw_getelementptr &&
744       Lex.getKind() != lltok::kw_addrspacecast &&
745       Lex.getKind() != lltok::kw_inttoptr) {
746     if (ParseGlobalTypeAndValue(Aliasee))
747       return true;
748   } else {
749     // The bitcast dest type is not present, it is implied by the dest type.
750     ValID ID;
751     if (ParseValID(ID))
752       return true;
753     if (ID.Kind != ValID::t_Constant)
754       return Error(AliaseeLoc, "invalid aliasee");
755     Aliasee = ID.ConstantVal;
756   }
757 
758   Type *AliaseeType = Aliasee->getType();
759   auto *PTy = dyn_cast<PointerType>(AliaseeType);
760   if (!PTy)
761     return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
762   unsigned AddrSpace = PTy->getAddressSpace();
763 
764   if (IsAlias && Ty != PTy->getElementType())
765     return Error(
766         ExplicitTypeLoc,
767         "explicit pointee type doesn't match operand's pointee type");
768 
769   if (!IsAlias && !PTy->getElementType()->isFunctionTy())
770     return Error(
771         ExplicitTypeLoc,
772         "explicit pointee type should be a function type");
773 
774   GlobalValue *GVal = nullptr;
775 
776   // See if the alias was forward referenced, if so, prepare to replace the
777   // forward reference.
778   if (!Name.empty()) {
779     GVal = M->getNamedValue(Name);
780     if (GVal) {
781       if (!ForwardRefVals.erase(Name))
782         return Error(NameLoc, "redefinition of global '@" + Name + "'");
783     }
784   } else {
785     auto I = ForwardRefValIDs.find(NumberedVals.size());
786     if (I != ForwardRefValIDs.end()) {
787       GVal = I->second.first;
788       ForwardRefValIDs.erase(I);
789     }
790   }
791 
792   // Okay, create the alias but do not insert it into the module yet.
793   std::unique_ptr<GlobalIndirectSymbol> GA;
794   if (IsAlias)
795     GA.reset(GlobalAlias::create(Ty, AddrSpace,
796                                  (GlobalValue::LinkageTypes)Linkage, Name,
797                                  Aliasee, /*Parent*/ nullptr));
798   else
799     GA.reset(GlobalIFunc::create(Ty, AddrSpace,
800                                  (GlobalValue::LinkageTypes)Linkage, Name,
801                                  Aliasee, /*Parent*/ nullptr));
802   GA->setThreadLocalMode(TLM);
803   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
804   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
805   GA->setUnnamedAddr(UnnamedAddr);
806 
807   if (Name.empty())
808     NumberedVals.push_back(GA.get());
809 
810   if (GVal) {
811     // Verify that types agree.
812     if (GVal->getType() != GA->getType())
813       return Error(
814           ExplicitTypeLoc,
815           "forward reference and definition of alias have different types");
816 
817     // If they agree, just RAUW the old value with the alias and remove the
818     // forward ref info.
819     GVal->replaceAllUsesWith(GA.get());
820     GVal->eraseFromParent();
821   }
822 
823   // Insert into the module, we know its name won't collide now.
824   if (IsAlias)
825     M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
826   else
827     M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
828   assert(GA->getName() == Name && "Should not be a name conflict!");
829 
830   // The module owns this now
831   GA.release();
832 
833   return false;
834 }
835 
836 /// ParseGlobal
837 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
838 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
839 ///       OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
840 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
841 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
842 ///       OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
843 ///
844 /// Everything up to and including OptionalUnnamedAddr has been parsed
845 /// already.
846 ///
847 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
848                            unsigned Linkage, bool HasLinkage,
849                            unsigned Visibility, unsigned DLLStorageClass,
850                            GlobalVariable::ThreadLocalMode TLM,
851                            GlobalVariable::UnnamedAddr UnnamedAddr) {
852   if (!isValidVisibilityForLinkage(Visibility, Linkage))
853     return Error(NameLoc,
854                  "symbol with local linkage must have default visibility");
855 
856   unsigned AddrSpace;
857   bool IsConstant, IsExternallyInitialized;
858   LocTy IsExternallyInitializedLoc;
859   LocTy TyLoc;
860 
861   Type *Ty = nullptr;
862   if (ParseOptionalAddrSpace(AddrSpace) ||
863       ParseOptionalToken(lltok::kw_externally_initialized,
864                          IsExternallyInitialized,
865                          &IsExternallyInitializedLoc) ||
866       ParseGlobalType(IsConstant) ||
867       ParseType(Ty, TyLoc))
868     return true;
869 
870   // If the linkage is specified and is external, then no initializer is
871   // present.
872   Constant *Init = nullptr;
873   if (!HasLinkage ||
874       !GlobalValue::isValidDeclarationLinkage(
875           (GlobalValue::LinkageTypes)Linkage)) {
876     if (ParseGlobalValue(Ty, Init))
877       return true;
878   }
879 
880   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
881     return Error(TyLoc, "invalid type for global variable");
882 
883   GlobalValue *GVal = nullptr;
884 
885   // See if the global was forward referenced, if so, use the global.
886   if (!Name.empty()) {
887     GVal = M->getNamedValue(Name);
888     if (GVal) {
889       if (!ForwardRefVals.erase(Name))
890         return Error(NameLoc, "redefinition of global '@" + Name + "'");
891     }
892   } else {
893     auto I = ForwardRefValIDs.find(NumberedVals.size());
894     if (I != ForwardRefValIDs.end()) {
895       GVal = I->second.first;
896       ForwardRefValIDs.erase(I);
897     }
898   }
899 
900   GlobalVariable *GV;
901   if (!GVal) {
902     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
903                             Name, nullptr, GlobalVariable::NotThreadLocal,
904                             AddrSpace);
905   } else {
906     if (GVal->getValueType() != Ty)
907       return Error(TyLoc,
908             "forward reference and definition of global have different types");
909 
910     GV = cast<GlobalVariable>(GVal);
911 
912     // Move the forward-reference to the correct spot in the module.
913     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
914   }
915 
916   if (Name.empty())
917     NumberedVals.push_back(GV);
918 
919   // Set the parsed properties on the global.
920   if (Init)
921     GV->setInitializer(Init);
922   GV->setConstant(IsConstant);
923   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
924   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
925   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
926   GV->setExternallyInitialized(IsExternallyInitialized);
927   GV->setThreadLocalMode(TLM);
928   GV->setUnnamedAddr(UnnamedAddr);
929 
930   // Parse attributes on the global.
931   while (Lex.getKind() == lltok::comma) {
932     Lex.Lex();
933 
934     if (Lex.getKind() == lltok::kw_section) {
935       Lex.Lex();
936       GV->setSection(Lex.getStrVal());
937       if (ParseToken(lltok::StringConstant, "expected global section string"))
938         return true;
939     } else if (Lex.getKind() == lltok::kw_align) {
940       unsigned Alignment;
941       if (ParseOptionalAlignment(Alignment)) return true;
942       GV->setAlignment(Alignment);
943     } else if (Lex.getKind() == lltok::MetadataVar) {
944       if (ParseGlobalObjectMetadataAttachment(*GV))
945         return true;
946     } else {
947       Comdat *C;
948       if (parseOptionalComdat(Name, C))
949         return true;
950       if (C)
951         GV->setComdat(C);
952       else
953         return TokError("unknown global variable property!");
954     }
955   }
956 
957   AttrBuilder Attrs;
958   LocTy BuiltinLoc;
959   std::vector<unsigned> FwdRefAttrGrps;
960   if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
961     return true;
962   if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
963     GV->setAttributes(AttributeSet::get(Context, Attrs));
964     ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
965   }
966 
967   return false;
968 }
969 
970 /// ParseUnnamedAttrGrp
971 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
972 bool LLParser::ParseUnnamedAttrGrp() {
973   assert(Lex.getKind() == lltok::kw_attributes);
974   LocTy AttrGrpLoc = Lex.getLoc();
975   Lex.Lex();
976 
977   if (Lex.getKind() != lltok::AttrGrpID)
978     return TokError("expected attribute group id");
979 
980   unsigned VarID = Lex.getUIntVal();
981   std::vector<unsigned> unused;
982   LocTy BuiltinLoc;
983   Lex.Lex();
984 
985   if (ParseToken(lltok::equal, "expected '=' here") ||
986       ParseToken(lltok::lbrace, "expected '{' here") ||
987       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
988                                  BuiltinLoc) ||
989       ParseToken(lltok::rbrace, "expected end of attribute group"))
990     return true;
991 
992   if (!NumberedAttrBuilders[VarID].hasAttributes())
993     return Error(AttrGrpLoc, "attribute group has no attributes");
994 
995   return false;
996 }
997 
998 /// ParseFnAttributeValuePairs
999 ///   ::= <attr> | <attr> '=' <value>
1000 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1001                                           std::vector<unsigned> &FwdRefAttrGrps,
1002                                           bool inAttrGrp, LocTy &BuiltinLoc) {
1003   bool HaveError = false;
1004 
1005   B.clear();
1006 
1007   while (true) {
1008     lltok::Kind Token = Lex.getKind();
1009     if (Token == lltok::kw_builtin)
1010       BuiltinLoc = Lex.getLoc();
1011     switch (Token) {
1012     default:
1013       if (!inAttrGrp) return HaveError;
1014       return Error(Lex.getLoc(), "unterminated attribute group");
1015     case lltok::rbrace:
1016       // Finished.
1017       return false;
1018 
1019     case lltok::AttrGrpID: {
1020       // Allow a function to reference an attribute group:
1021       //
1022       //   define void @foo() #1 { ... }
1023       if (inAttrGrp)
1024         HaveError |=
1025           Error(Lex.getLoc(),
1026               "cannot have an attribute group reference in an attribute group");
1027 
1028       unsigned AttrGrpNum = Lex.getUIntVal();
1029       if (inAttrGrp) break;
1030 
1031       // Save the reference to the attribute group. We'll fill it in later.
1032       FwdRefAttrGrps.push_back(AttrGrpNum);
1033       break;
1034     }
1035     // Target-dependent attributes:
1036     case lltok::StringConstant: {
1037       if (ParseStringAttribute(B))
1038         return true;
1039       continue;
1040     }
1041 
1042     // Target-independent attributes:
1043     case lltok::kw_align: {
1044       // As a hack, we allow function alignment to be initially parsed as an
1045       // attribute on a function declaration/definition or added to an attribute
1046       // group and later moved to the alignment field.
1047       unsigned Alignment;
1048       if (inAttrGrp) {
1049         Lex.Lex();
1050         if (ParseToken(lltok::equal, "expected '=' here") ||
1051             ParseUInt32(Alignment))
1052           return true;
1053       } else {
1054         if (ParseOptionalAlignment(Alignment))
1055           return true;
1056       }
1057       B.addAlignmentAttr(Alignment);
1058       continue;
1059     }
1060     case lltok::kw_alignstack: {
1061       unsigned Alignment;
1062       if (inAttrGrp) {
1063         Lex.Lex();
1064         if (ParseToken(lltok::equal, "expected '=' here") ||
1065             ParseUInt32(Alignment))
1066           return true;
1067       } else {
1068         if (ParseOptionalStackAlignment(Alignment))
1069           return true;
1070       }
1071       B.addStackAlignmentAttr(Alignment);
1072       continue;
1073     }
1074     case lltok::kw_allocsize: {
1075       unsigned ElemSizeArg;
1076       Optional<unsigned> NumElemsArg;
1077       // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1078       if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1079         return true;
1080       B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1081       continue;
1082     }
1083     case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1084     case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1085     case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1086     case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1087     case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1088     case lltok::kw_inaccessiblememonly:
1089       B.addAttribute(Attribute::InaccessibleMemOnly); break;
1090     case lltok::kw_inaccessiblemem_or_argmemonly:
1091       B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1092     case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1093     case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1094     case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1095     case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1096     case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1097     case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1098     case lltok::kw_noimplicitfloat:
1099       B.addAttribute(Attribute::NoImplicitFloat); break;
1100     case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1101     case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1102     case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1103     case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1104     case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1105     case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1106     case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1107     case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1108     case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1109     case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1110     case lltok::kw_returns_twice:
1111       B.addAttribute(Attribute::ReturnsTwice); break;
1112     case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1113     case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1114     case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1115     case lltok::kw_sspstrong:
1116       B.addAttribute(Attribute::StackProtectStrong); break;
1117     case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1118     case lltok::kw_sanitize_address:
1119       B.addAttribute(Attribute::SanitizeAddress); break;
1120     case lltok::kw_sanitize_thread:
1121       B.addAttribute(Attribute::SanitizeThread); break;
1122     case lltok::kw_sanitize_memory:
1123       B.addAttribute(Attribute::SanitizeMemory); break;
1124     case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1125     case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1126 
1127     // Error handling.
1128     case lltok::kw_inreg:
1129     case lltok::kw_signext:
1130     case lltok::kw_zeroext:
1131       HaveError |=
1132         Error(Lex.getLoc(),
1133               "invalid use of attribute on a function");
1134       break;
1135     case lltok::kw_byval:
1136     case lltok::kw_dereferenceable:
1137     case lltok::kw_dereferenceable_or_null:
1138     case lltok::kw_inalloca:
1139     case lltok::kw_nest:
1140     case lltok::kw_noalias:
1141     case lltok::kw_nocapture:
1142     case lltok::kw_nonnull:
1143     case lltok::kw_returned:
1144     case lltok::kw_sret:
1145     case lltok::kw_swifterror:
1146     case lltok::kw_swiftself:
1147       HaveError |=
1148         Error(Lex.getLoc(),
1149               "invalid use of parameter-only attribute on a function");
1150       break;
1151     }
1152 
1153     Lex.Lex();
1154   }
1155 }
1156 
1157 //===----------------------------------------------------------------------===//
1158 // GlobalValue Reference/Resolution Routines.
1159 //===----------------------------------------------------------------------===//
1160 
1161 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1162                                               const std::string &Name) {
1163   if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1164     return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1165   else
1166     return new GlobalVariable(*M, PTy->getElementType(), false,
1167                               GlobalValue::ExternalWeakLinkage, nullptr, Name,
1168                               nullptr, GlobalVariable::NotThreadLocal,
1169                               PTy->getAddressSpace());
1170 }
1171 
1172 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1173 /// forward reference record if needed.  This can return null if the value
1174 /// exists but does not have the right type.
1175 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1176                                     LocTy Loc) {
1177   PointerType *PTy = dyn_cast<PointerType>(Ty);
1178   if (!PTy) {
1179     Error(Loc, "global variable reference must have pointer type");
1180     return nullptr;
1181   }
1182 
1183   // Look this name up in the normal function symbol table.
1184   GlobalValue *Val =
1185     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1186 
1187   // If this is a forward reference for the value, see if we already created a
1188   // forward ref record.
1189   if (!Val) {
1190     auto I = ForwardRefVals.find(Name);
1191     if (I != ForwardRefVals.end())
1192       Val = I->second.first;
1193   }
1194 
1195   // If we have the value in the symbol table or fwd-ref table, return it.
1196   if (Val) {
1197     if (Val->getType() == Ty) return Val;
1198     Error(Loc, "'@" + Name + "' defined with type '" +
1199           getTypeString(Val->getType()) + "'");
1200     return nullptr;
1201   }
1202 
1203   // Otherwise, create a new forward reference for this value and remember it.
1204   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1205   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1206   return FwdVal;
1207 }
1208 
1209 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1210   PointerType *PTy = dyn_cast<PointerType>(Ty);
1211   if (!PTy) {
1212     Error(Loc, "global variable reference must have pointer type");
1213     return nullptr;
1214   }
1215 
1216   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1217 
1218   // If this is a forward reference for the value, see if we already created a
1219   // forward ref record.
1220   if (!Val) {
1221     auto I = ForwardRefValIDs.find(ID);
1222     if (I != ForwardRefValIDs.end())
1223       Val = I->second.first;
1224   }
1225 
1226   // If we have the value in the symbol table or fwd-ref table, return it.
1227   if (Val) {
1228     if (Val->getType() == Ty) return Val;
1229     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1230           getTypeString(Val->getType()) + "'");
1231     return nullptr;
1232   }
1233 
1234   // Otherwise, create a new forward reference for this value and remember it.
1235   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1236   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1237   return FwdVal;
1238 }
1239 
1240 //===----------------------------------------------------------------------===//
1241 // Comdat Reference/Resolution Routines.
1242 //===----------------------------------------------------------------------===//
1243 
1244 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1245   // Look this name up in the comdat symbol table.
1246   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1247   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1248   if (I != ComdatSymTab.end())
1249     return &I->second;
1250 
1251   // Otherwise, create a new forward reference for this value and remember it.
1252   Comdat *C = M->getOrInsertComdat(Name);
1253   ForwardRefComdats[Name] = Loc;
1254   return C;
1255 }
1256 
1257 //===----------------------------------------------------------------------===//
1258 // Helper Routines.
1259 //===----------------------------------------------------------------------===//
1260 
1261 /// ParseToken - If the current token has the specified kind, eat it and return
1262 /// success.  Otherwise, emit the specified error and return failure.
1263 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1264   if (Lex.getKind() != T)
1265     return TokError(ErrMsg);
1266   Lex.Lex();
1267   return false;
1268 }
1269 
1270 /// ParseStringConstant
1271 ///   ::= StringConstant
1272 bool LLParser::ParseStringConstant(std::string &Result) {
1273   if (Lex.getKind() != lltok::StringConstant)
1274     return TokError("expected string constant");
1275   Result = Lex.getStrVal();
1276   Lex.Lex();
1277   return false;
1278 }
1279 
1280 /// ParseUInt32
1281 ///   ::= uint32
1282 bool LLParser::ParseUInt32(uint32_t &Val) {
1283   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1284     return TokError("expected integer");
1285   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1286   if (Val64 != unsigned(Val64))
1287     return TokError("expected 32-bit integer (too large)");
1288   Val = Val64;
1289   Lex.Lex();
1290   return false;
1291 }
1292 
1293 /// ParseUInt64
1294 ///   ::= uint64
1295 bool LLParser::ParseUInt64(uint64_t &Val) {
1296   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1297     return TokError("expected integer");
1298   Val = Lex.getAPSIntVal().getLimitedValue();
1299   Lex.Lex();
1300   return false;
1301 }
1302 
1303 /// ParseTLSModel
1304 ///   := 'localdynamic'
1305 ///   := 'initialexec'
1306 ///   := 'localexec'
1307 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1308   switch (Lex.getKind()) {
1309     default:
1310       return TokError("expected localdynamic, initialexec or localexec");
1311     case lltok::kw_localdynamic:
1312       TLM = GlobalVariable::LocalDynamicTLSModel;
1313       break;
1314     case lltok::kw_initialexec:
1315       TLM = GlobalVariable::InitialExecTLSModel;
1316       break;
1317     case lltok::kw_localexec:
1318       TLM = GlobalVariable::LocalExecTLSModel;
1319       break;
1320   }
1321 
1322   Lex.Lex();
1323   return false;
1324 }
1325 
1326 /// ParseOptionalThreadLocal
1327 ///   := /*empty*/
1328 ///   := 'thread_local'
1329 ///   := 'thread_local' '(' tlsmodel ')'
1330 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1331   TLM = GlobalVariable::NotThreadLocal;
1332   if (!EatIfPresent(lltok::kw_thread_local))
1333     return false;
1334 
1335   TLM = GlobalVariable::GeneralDynamicTLSModel;
1336   if (Lex.getKind() == lltok::lparen) {
1337     Lex.Lex();
1338     return ParseTLSModel(TLM) ||
1339       ParseToken(lltok::rparen, "expected ')' after thread local model");
1340   }
1341   return false;
1342 }
1343 
1344 /// ParseOptionalAddrSpace
1345 ///   := /*empty*/
1346 ///   := 'addrspace' '(' uint32 ')'
1347 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1348   AddrSpace = 0;
1349   if (!EatIfPresent(lltok::kw_addrspace))
1350     return false;
1351   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1352          ParseUInt32(AddrSpace) ||
1353          ParseToken(lltok::rparen, "expected ')' in address space");
1354 }
1355 
1356 /// ParseStringAttribute
1357 ///   := StringConstant
1358 ///   := StringConstant '=' StringConstant
1359 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1360   std::string Attr = Lex.getStrVal();
1361   Lex.Lex();
1362   std::string Val;
1363   if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1364     return true;
1365   B.addAttribute(Attr, Val);
1366   return false;
1367 }
1368 
1369 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1370 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1371   bool HaveError = false;
1372 
1373   B.clear();
1374 
1375   while (true) {
1376     lltok::Kind Token = Lex.getKind();
1377     switch (Token) {
1378     default:  // End of attributes.
1379       return HaveError;
1380     case lltok::StringConstant: {
1381       if (ParseStringAttribute(B))
1382         return true;
1383       continue;
1384     }
1385     case lltok::kw_align: {
1386       unsigned Alignment;
1387       if (ParseOptionalAlignment(Alignment))
1388         return true;
1389       B.addAlignmentAttr(Alignment);
1390       continue;
1391     }
1392     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1393     case lltok::kw_dereferenceable: {
1394       uint64_t Bytes;
1395       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1396         return true;
1397       B.addDereferenceableAttr(Bytes);
1398       continue;
1399     }
1400     case lltok::kw_dereferenceable_or_null: {
1401       uint64_t Bytes;
1402       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1403         return true;
1404       B.addDereferenceableOrNullAttr(Bytes);
1405       continue;
1406     }
1407     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1408     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1409     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1410     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1411     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1412     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1413     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1414     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1415     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1416     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1417     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1418     case lltok::kw_swifterror:      B.addAttribute(Attribute::SwiftError); break;
1419     case lltok::kw_swiftself:       B.addAttribute(Attribute::SwiftSelf); break;
1420     case lltok::kw_writeonly:       B.addAttribute(Attribute::WriteOnly); break;
1421     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1422 
1423     case lltok::kw_alignstack:
1424     case lltok::kw_alwaysinline:
1425     case lltok::kw_argmemonly:
1426     case lltok::kw_builtin:
1427     case lltok::kw_inlinehint:
1428     case lltok::kw_jumptable:
1429     case lltok::kw_minsize:
1430     case lltok::kw_naked:
1431     case lltok::kw_nobuiltin:
1432     case lltok::kw_noduplicate:
1433     case lltok::kw_noimplicitfloat:
1434     case lltok::kw_noinline:
1435     case lltok::kw_nonlazybind:
1436     case lltok::kw_noredzone:
1437     case lltok::kw_noreturn:
1438     case lltok::kw_nounwind:
1439     case lltok::kw_optnone:
1440     case lltok::kw_optsize:
1441     case lltok::kw_returns_twice:
1442     case lltok::kw_sanitize_address:
1443     case lltok::kw_sanitize_memory:
1444     case lltok::kw_sanitize_thread:
1445     case lltok::kw_ssp:
1446     case lltok::kw_sspreq:
1447     case lltok::kw_sspstrong:
1448     case lltok::kw_safestack:
1449     case lltok::kw_uwtable:
1450       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1451       break;
1452     }
1453 
1454     Lex.Lex();
1455   }
1456 }
1457 
1458 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1459 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1460   bool HaveError = false;
1461 
1462   B.clear();
1463 
1464   while (true) {
1465     lltok::Kind Token = Lex.getKind();
1466     switch (Token) {
1467     default:  // End of attributes.
1468       return HaveError;
1469     case lltok::StringConstant: {
1470       if (ParseStringAttribute(B))
1471         return true;
1472       continue;
1473     }
1474     case lltok::kw_dereferenceable: {
1475       uint64_t Bytes;
1476       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1477         return true;
1478       B.addDereferenceableAttr(Bytes);
1479       continue;
1480     }
1481     case lltok::kw_dereferenceable_or_null: {
1482       uint64_t Bytes;
1483       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1484         return true;
1485       B.addDereferenceableOrNullAttr(Bytes);
1486       continue;
1487     }
1488     case lltok::kw_align: {
1489       unsigned Alignment;
1490       if (ParseOptionalAlignment(Alignment))
1491         return true;
1492       B.addAlignmentAttr(Alignment);
1493       continue;
1494     }
1495     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1496     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1497     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1498     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1499     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1500 
1501     // Error handling.
1502     case lltok::kw_byval:
1503     case lltok::kw_inalloca:
1504     case lltok::kw_nest:
1505     case lltok::kw_nocapture:
1506     case lltok::kw_returned:
1507     case lltok::kw_sret:
1508     case lltok::kw_swifterror:
1509     case lltok::kw_swiftself:
1510       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1511       break;
1512 
1513     case lltok::kw_alignstack:
1514     case lltok::kw_alwaysinline:
1515     case lltok::kw_argmemonly:
1516     case lltok::kw_builtin:
1517     case lltok::kw_cold:
1518     case lltok::kw_inlinehint:
1519     case lltok::kw_jumptable:
1520     case lltok::kw_minsize:
1521     case lltok::kw_naked:
1522     case lltok::kw_nobuiltin:
1523     case lltok::kw_noduplicate:
1524     case lltok::kw_noimplicitfloat:
1525     case lltok::kw_noinline:
1526     case lltok::kw_nonlazybind:
1527     case lltok::kw_noredzone:
1528     case lltok::kw_noreturn:
1529     case lltok::kw_nounwind:
1530     case lltok::kw_optnone:
1531     case lltok::kw_optsize:
1532     case lltok::kw_returns_twice:
1533     case lltok::kw_sanitize_address:
1534     case lltok::kw_sanitize_memory:
1535     case lltok::kw_sanitize_thread:
1536     case lltok::kw_ssp:
1537     case lltok::kw_sspreq:
1538     case lltok::kw_sspstrong:
1539     case lltok::kw_safestack:
1540     case lltok::kw_uwtable:
1541       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1542       break;
1543 
1544     case lltok::kw_readnone:
1545     case lltok::kw_readonly:
1546       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1547     }
1548 
1549     Lex.Lex();
1550   }
1551 }
1552 
1553 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1554   HasLinkage = true;
1555   switch (Kind) {
1556   default:
1557     HasLinkage = false;
1558     return GlobalValue::ExternalLinkage;
1559   case lltok::kw_private:
1560     return GlobalValue::PrivateLinkage;
1561   case lltok::kw_internal:
1562     return GlobalValue::InternalLinkage;
1563   case lltok::kw_weak:
1564     return GlobalValue::WeakAnyLinkage;
1565   case lltok::kw_weak_odr:
1566     return GlobalValue::WeakODRLinkage;
1567   case lltok::kw_linkonce:
1568     return GlobalValue::LinkOnceAnyLinkage;
1569   case lltok::kw_linkonce_odr:
1570     return GlobalValue::LinkOnceODRLinkage;
1571   case lltok::kw_available_externally:
1572     return GlobalValue::AvailableExternallyLinkage;
1573   case lltok::kw_appending:
1574     return GlobalValue::AppendingLinkage;
1575   case lltok::kw_common:
1576     return GlobalValue::CommonLinkage;
1577   case lltok::kw_extern_weak:
1578     return GlobalValue::ExternalWeakLinkage;
1579   case lltok::kw_external:
1580     return GlobalValue::ExternalLinkage;
1581   }
1582 }
1583 
1584 /// ParseOptionalLinkage
1585 ///   ::= /*empty*/
1586 ///   ::= 'private'
1587 ///   ::= 'internal'
1588 ///   ::= 'weak'
1589 ///   ::= 'weak_odr'
1590 ///   ::= 'linkonce'
1591 ///   ::= 'linkonce_odr'
1592 ///   ::= 'available_externally'
1593 ///   ::= 'appending'
1594 ///   ::= 'common'
1595 ///   ::= 'extern_weak'
1596 ///   ::= 'external'
1597 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1598                                     unsigned &Visibility,
1599                                     unsigned &DLLStorageClass) {
1600   Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1601   if (HasLinkage)
1602     Lex.Lex();
1603   ParseOptionalVisibility(Visibility);
1604   ParseOptionalDLLStorageClass(DLLStorageClass);
1605   return false;
1606 }
1607 
1608 /// ParseOptionalVisibility
1609 ///   ::= /*empty*/
1610 ///   ::= 'default'
1611 ///   ::= 'hidden'
1612 ///   ::= 'protected'
1613 ///
1614 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1615   switch (Lex.getKind()) {
1616   default:
1617     Res = GlobalValue::DefaultVisibility;
1618     return;
1619   case lltok::kw_default:
1620     Res = GlobalValue::DefaultVisibility;
1621     break;
1622   case lltok::kw_hidden:
1623     Res = GlobalValue::HiddenVisibility;
1624     break;
1625   case lltok::kw_protected:
1626     Res = GlobalValue::ProtectedVisibility;
1627     break;
1628   }
1629   Lex.Lex();
1630 }
1631 
1632 /// ParseOptionalDLLStorageClass
1633 ///   ::= /*empty*/
1634 ///   ::= 'dllimport'
1635 ///   ::= 'dllexport'
1636 ///
1637 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1638   switch (Lex.getKind()) {
1639   default:
1640     Res = GlobalValue::DefaultStorageClass;
1641     return;
1642   case lltok::kw_dllimport:
1643     Res = GlobalValue::DLLImportStorageClass;
1644     break;
1645   case lltok::kw_dllexport:
1646     Res = GlobalValue::DLLExportStorageClass;
1647     break;
1648   }
1649   Lex.Lex();
1650 }
1651 
1652 /// ParseOptionalCallingConv
1653 ///   ::= /*empty*/
1654 ///   ::= 'ccc'
1655 ///   ::= 'fastcc'
1656 ///   ::= 'intel_ocl_bicc'
1657 ///   ::= 'coldcc'
1658 ///   ::= 'x86_stdcallcc'
1659 ///   ::= 'x86_fastcallcc'
1660 ///   ::= 'x86_thiscallcc'
1661 ///   ::= 'x86_vectorcallcc'
1662 ///   ::= 'arm_apcscc'
1663 ///   ::= 'arm_aapcscc'
1664 ///   ::= 'arm_aapcs_vfpcc'
1665 ///   ::= 'msp430_intrcc'
1666 ///   ::= 'avr_intrcc'
1667 ///   ::= 'avr_signalcc'
1668 ///   ::= 'ptx_kernel'
1669 ///   ::= 'ptx_device'
1670 ///   ::= 'spir_func'
1671 ///   ::= 'spir_kernel'
1672 ///   ::= 'x86_64_sysvcc'
1673 ///   ::= 'x86_64_win64cc'
1674 ///   ::= 'webkit_jscc'
1675 ///   ::= 'anyregcc'
1676 ///   ::= 'preserve_mostcc'
1677 ///   ::= 'preserve_allcc'
1678 ///   ::= 'ghccc'
1679 ///   ::= 'swiftcc'
1680 ///   ::= 'x86_intrcc'
1681 ///   ::= 'hhvmcc'
1682 ///   ::= 'hhvm_ccc'
1683 ///   ::= 'cxx_fast_tlscc'
1684 ///   ::= 'amdgpu_vs'
1685 ///   ::= 'amdgpu_hs'
1686 ///   ::= 'amdgpu_gs'
1687 ///   ::= 'amdgpu_ps'
1688 ///   ::= 'amdgpu_cs'
1689 ///   ::= 'amdgpu_kernel'
1690 ///   ::= 'cc' UINT
1691 ///
1692 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1693   switch (Lex.getKind()) {
1694   default:                       CC = CallingConv::C; return false;
1695   case lltok::kw_ccc:            CC = CallingConv::C; break;
1696   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1697   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1698   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1699   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1700   case lltok::kw_x86_regcallcc:  CC = CallingConv::X86_RegCall; break;
1701   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1702   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1703   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1704   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1705   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1706   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1707   case lltok::kw_avr_intrcc:     CC = CallingConv::AVR_INTR; break;
1708   case lltok::kw_avr_signalcc:   CC = CallingConv::AVR_SIGNAL; break;
1709   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1710   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1711   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1712   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1713   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1714   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1715   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1716   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1717   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1718   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1719   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1720   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1721   case lltok::kw_swiftcc:        CC = CallingConv::Swift; break;
1722   case lltok::kw_x86_intrcc:     CC = CallingConv::X86_INTR; break;
1723   case lltok::kw_hhvmcc:         CC = CallingConv::HHVM; break;
1724   case lltok::kw_hhvm_ccc:       CC = CallingConv::HHVM_C; break;
1725   case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1726   case lltok::kw_amdgpu_vs:      CC = CallingConv::AMDGPU_VS; break;
1727   case lltok::kw_amdgpu_hs:      CC = CallingConv::AMDGPU_HS; break;
1728   case lltok::kw_amdgpu_gs:      CC = CallingConv::AMDGPU_GS; break;
1729   case lltok::kw_amdgpu_ps:      CC = CallingConv::AMDGPU_PS; break;
1730   case lltok::kw_amdgpu_cs:      CC = CallingConv::AMDGPU_CS; break;
1731   case lltok::kw_amdgpu_kernel:  CC = CallingConv::AMDGPU_KERNEL; break;
1732   case lltok::kw_cc: {
1733       Lex.Lex();
1734       return ParseUInt32(CC);
1735     }
1736   }
1737 
1738   Lex.Lex();
1739   return false;
1740 }
1741 
1742 /// ParseMetadataAttachment
1743 ///   ::= !dbg !42
1744 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1745   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1746 
1747   std::string Name = Lex.getStrVal();
1748   Kind = M->getMDKindID(Name);
1749   Lex.Lex();
1750 
1751   return ParseMDNode(MD);
1752 }
1753 
1754 /// ParseInstructionMetadata
1755 ///   ::= !dbg !42 (',' !dbg !57)*
1756 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1757   do {
1758     if (Lex.getKind() != lltok::MetadataVar)
1759       return TokError("expected metadata after comma");
1760 
1761     unsigned MDK;
1762     MDNode *N;
1763     if (ParseMetadataAttachment(MDK, N))
1764       return true;
1765 
1766     Inst.setMetadata(MDK, N);
1767     if (MDK == LLVMContext::MD_tbaa)
1768       InstsWithTBAATag.push_back(&Inst);
1769 
1770     // If this is the end of the list, we're done.
1771   } while (EatIfPresent(lltok::comma));
1772   return false;
1773 }
1774 
1775 /// ParseGlobalObjectMetadataAttachment
1776 ///   ::= !dbg !57
1777 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1778   unsigned MDK;
1779   MDNode *N;
1780   if (ParseMetadataAttachment(MDK, N))
1781     return true;
1782 
1783   GO.addMetadata(MDK, *N);
1784   return false;
1785 }
1786 
1787 /// ParseOptionalFunctionMetadata
1788 ///   ::= (!dbg !57)*
1789 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1790   while (Lex.getKind() == lltok::MetadataVar)
1791     if (ParseGlobalObjectMetadataAttachment(F))
1792       return true;
1793   return false;
1794 }
1795 
1796 /// ParseOptionalAlignment
1797 ///   ::= /* empty */
1798 ///   ::= 'align' 4
1799 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1800   Alignment = 0;
1801   if (!EatIfPresent(lltok::kw_align))
1802     return false;
1803   LocTy AlignLoc = Lex.getLoc();
1804   if (ParseUInt32(Alignment)) return true;
1805   if (!isPowerOf2_32(Alignment))
1806     return Error(AlignLoc, "alignment is not a power of two");
1807   if (Alignment > Value::MaximumAlignment)
1808     return Error(AlignLoc, "huge alignments are not supported yet");
1809   return false;
1810 }
1811 
1812 /// ParseOptionalDerefAttrBytes
1813 ///   ::= /* empty */
1814 ///   ::= AttrKind '(' 4 ')'
1815 ///
1816 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1817 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1818                                            uint64_t &Bytes) {
1819   assert((AttrKind == lltok::kw_dereferenceable ||
1820           AttrKind == lltok::kw_dereferenceable_or_null) &&
1821          "contract!");
1822 
1823   Bytes = 0;
1824   if (!EatIfPresent(AttrKind))
1825     return false;
1826   LocTy ParenLoc = Lex.getLoc();
1827   if (!EatIfPresent(lltok::lparen))
1828     return Error(ParenLoc, "expected '('");
1829   LocTy DerefLoc = Lex.getLoc();
1830   if (ParseUInt64(Bytes)) return true;
1831   ParenLoc = Lex.getLoc();
1832   if (!EatIfPresent(lltok::rparen))
1833     return Error(ParenLoc, "expected ')'");
1834   if (!Bytes)
1835     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1836   return false;
1837 }
1838 
1839 /// ParseOptionalCommaAlign
1840 ///   ::=
1841 ///   ::= ',' align 4
1842 ///
1843 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1844 /// end.
1845 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1846                                        bool &AteExtraComma) {
1847   AteExtraComma = false;
1848   while (EatIfPresent(lltok::comma)) {
1849     // Metadata at the end is an early exit.
1850     if (Lex.getKind() == lltok::MetadataVar) {
1851       AteExtraComma = true;
1852       return false;
1853     }
1854 
1855     if (Lex.getKind() != lltok::kw_align)
1856       return Error(Lex.getLoc(), "expected metadata or 'align'");
1857 
1858     if (ParseOptionalAlignment(Alignment)) return true;
1859   }
1860 
1861   return false;
1862 }
1863 
1864 /// ParseOptionalCommaAddrSpace
1865 ///   ::=
1866 ///   ::= ',' addrspace(1)
1867 ///
1868 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1869 /// end.
1870 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1871                                            LocTy &Loc,
1872                                            bool &AteExtraComma) {
1873   AteExtraComma = false;
1874   while (EatIfPresent(lltok::comma)) {
1875     // Metadata at the end is an early exit.
1876     if (Lex.getKind() == lltok::MetadataVar) {
1877       AteExtraComma = true;
1878       return false;
1879     }
1880 
1881     Loc = Lex.getLoc();
1882     if (Lex.getKind() != lltok::kw_addrspace)
1883       return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1884 
1885     if (ParseOptionalAddrSpace(AddrSpace))
1886       return true;
1887   }
1888 
1889   return false;
1890 }
1891 
1892 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1893                                        Optional<unsigned> &HowManyArg) {
1894   Lex.Lex();
1895 
1896   auto StartParen = Lex.getLoc();
1897   if (!EatIfPresent(lltok::lparen))
1898     return Error(StartParen, "expected '('");
1899 
1900   if (ParseUInt32(BaseSizeArg))
1901     return true;
1902 
1903   if (EatIfPresent(lltok::comma)) {
1904     auto HowManyAt = Lex.getLoc();
1905     unsigned HowMany;
1906     if (ParseUInt32(HowMany))
1907       return true;
1908     if (HowMany == BaseSizeArg)
1909       return Error(HowManyAt,
1910                    "'allocsize' indices can't refer to the same parameter");
1911     HowManyArg = HowMany;
1912   } else
1913     HowManyArg = None;
1914 
1915   auto EndParen = Lex.getLoc();
1916   if (!EatIfPresent(lltok::rparen))
1917     return Error(EndParen, "expected ')'");
1918   return false;
1919 }
1920 
1921 /// ParseScopeAndOrdering
1922 ///   if isAtomic: ::= SyncScope? AtomicOrdering
1923 ///   else: ::=
1924 ///
1925 /// This sets Scope and Ordering to the parsed values.
1926 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
1927                                      AtomicOrdering &Ordering) {
1928   if (!isAtomic)
1929     return false;
1930 
1931   return ParseScope(SSID) || ParseOrdering(Ordering);
1932 }
1933 
1934 /// ParseScope
1935 ///   ::= syncscope("singlethread" | "<target scope>")?
1936 ///
1937 /// This sets synchronization scope ID to the ID of the parsed value.
1938 bool LLParser::ParseScope(SyncScope::ID &SSID) {
1939   SSID = SyncScope::System;
1940   if (EatIfPresent(lltok::kw_syncscope)) {
1941     auto StartParenAt = Lex.getLoc();
1942     if (!EatIfPresent(lltok::lparen))
1943       return Error(StartParenAt, "Expected '(' in syncscope");
1944 
1945     std::string SSN;
1946     auto SSNAt = Lex.getLoc();
1947     if (ParseStringConstant(SSN))
1948       return Error(SSNAt, "Expected synchronization scope name");
1949 
1950     auto EndParenAt = Lex.getLoc();
1951     if (!EatIfPresent(lltok::rparen))
1952       return Error(EndParenAt, "Expected ')' in syncscope");
1953 
1954     SSID = Context.getOrInsertSyncScopeID(SSN);
1955   }
1956 
1957   return false;
1958 }
1959 
1960 /// ParseOrdering
1961 ///   ::= AtomicOrdering
1962 ///
1963 /// This sets Ordering to the parsed value.
1964 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1965   switch (Lex.getKind()) {
1966   default: return TokError("Expected ordering on atomic instruction");
1967   case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1968   case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1969   // Not specified yet:
1970   // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1971   case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1972   case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1973   case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1974   case lltok::kw_seq_cst:
1975     Ordering = AtomicOrdering::SequentiallyConsistent;
1976     break;
1977   }
1978   Lex.Lex();
1979   return false;
1980 }
1981 
1982 /// ParseOptionalStackAlignment
1983 ///   ::= /* empty */
1984 ///   ::= 'alignstack' '(' 4 ')'
1985 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1986   Alignment = 0;
1987   if (!EatIfPresent(lltok::kw_alignstack))
1988     return false;
1989   LocTy ParenLoc = Lex.getLoc();
1990   if (!EatIfPresent(lltok::lparen))
1991     return Error(ParenLoc, "expected '('");
1992   LocTy AlignLoc = Lex.getLoc();
1993   if (ParseUInt32(Alignment)) return true;
1994   ParenLoc = Lex.getLoc();
1995   if (!EatIfPresent(lltok::rparen))
1996     return Error(ParenLoc, "expected ')'");
1997   if (!isPowerOf2_32(Alignment))
1998     return Error(AlignLoc, "stack alignment is not a power of two");
1999   return false;
2000 }
2001 
2002 /// ParseIndexList - This parses the index list for an insert/extractvalue
2003 /// instruction.  This sets AteExtraComma in the case where we eat an extra
2004 /// comma at the end of the line and find that it is followed by metadata.
2005 /// Clients that don't allow metadata can call the version of this function that
2006 /// only takes one argument.
2007 ///
2008 /// ParseIndexList
2009 ///    ::=  (',' uint32)+
2010 ///
2011 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2012                               bool &AteExtraComma) {
2013   AteExtraComma = false;
2014 
2015   if (Lex.getKind() != lltok::comma)
2016     return TokError("expected ',' as start of index list");
2017 
2018   while (EatIfPresent(lltok::comma)) {
2019     if (Lex.getKind() == lltok::MetadataVar) {
2020       if (Indices.empty()) return TokError("expected index");
2021       AteExtraComma = true;
2022       return false;
2023     }
2024     unsigned Idx = 0;
2025     if (ParseUInt32(Idx)) return true;
2026     Indices.push_back(Idx);
2027   }
2028 
2029   return false;
2030 }
2031 
2032 //===----------------------------------------------------------------------===//
2033 // Type Parsing.
2034 //===----------------------------------------------------------------------===//
2035 
2036 /// ParseType - Parse a type.
2037 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2038   SMLoc TypeLoc = Lex.getLoc();
2039   switch (Lex.getKind()) {
2040   default:
2041     return TokError(Msg);
2042   case lltok::Type:
2043     // Type ::= 'float' | 'void' (etc)
2044     Result = Lex.getTyVal();
2045     Lex.Lex();
2046     break;
2047   case lltok::lbrace:
2048     // Type ::= StructType
2049     if (ParseAnonStructType(Result, false))
2050       return true;
2051     break;
2052   case lltok::lsquare:
2053     // Type ::= '[' ... ']'
2054     Lex.Lex(); // eat the lsquare.
2055     if (ParseArrayVectorType(Result, false))
2056       return true;
2057     break;
2058   case lltok::less: // Either vector or packed struct.
2059     // Type ::= '<' ... '>'
2060     Lex.Lex();
2061     if (Lex.getKind() == lltok::lbrace) {
2062       if (ParseAnonStructType(Result, true) ||
2063           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2064         return true;
2065     } else if (ParseArrayVectorType(Result, true))
2066       return true;
2067     break;
2068   case lltok::LocalVar: {
2069     // Type ::= %foo
2070     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2071 
2072     // If the type hasn't been defined yet, create a forward definition and
2073     // remember where that forward def'n was seen (in case it never is defined).
2074     if (!Entry.first) {
2075       Entry.first = StructType::create(Context, Lex.getStrVal());
2076       Entry.second = Lex.getLoc();
2077     }
2078     Result = Entry.first;
2079     Lex.Lex();
2080     break;
2081   }
2082 
2083   case lltok::LocalVarID: {
2084     // Type ::= %4
2085     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2086 
2087     // If the type hasn't been defined yet, create a forward definition and
2088     // remember where that forward def'n was seen (in case it never is defined).
2089     if (!Entry.first) {
2090       Entry.first = StructType::create(Context);
2091       Entry.second = Lex.getLoc();
2092     }
2093     Result = Entry.first;
2094     Lex.Lex();
2095     break;
2096   }
2097   }
2098 
2099   // Parse the type suffixes.
2100   while (true) {
2101     switch (Lex.getKind()) {
2102     // End of type.
2103     default:
2104       if (!AllowVoid && Result->isVoidTy())
2105         return Error(TypeLoc, "void type only allowed for function results");
2106       return false;
2107 
2108     // Type ::= Type '*'
2109     case lltok::star:
2110       if (Result->isLabelTy())
2111         return TokError("basic block pointers are invalid");
2112       if (Result->isVoidTy())
2113         return TokError("pointers to void are invalid - use i8* instead");
2114       if (!PointerType::isValidElementType(Result))
2115         return TokError("pointer to this type is invalid");
2116       Result = PointerType::getUnqual(Result);
2117       Lex.Lex();
2118       break;
2119 
2120     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2121     case lltok::kw_addrspace: {
2122       if (Result->isLabelTy())
2123         return TokError("basic block pointers are invalid");
2124       if (Result->isVoidTy())
2125         return TokError("pointers to void are invalid; use i8* instead");
2126       if (!PointerType::isValidElementType(Result))
2127         return TokError("pointer to this type is invalid");
2128       unsigned AddrSpace;
2129       if (ParseOptionalAddrSpace(AddrSpace) ||
2130           ParseToken(lltok::star, "expected '*' in address space"))
2131         return true;
2132 
2133       Result = PointerType::get(Result, AddrSpace);
2134       break;
2135     }
2136 
2137     /// Types '(' ArgTypeListI ')' OptFuncAttrs
2138     case lltok::lparen:
2139       if (ParseFunctionType(Result))
2140         return true;
2141       break;
2142     }
2143   }
2144 }
2145 
2146 /// ParseParameterList
2147 ///    ::= '(' ')'
2148 ///    ::= '(' Arg (',' Arg)* ')'
2149 ///  Arg
2150 ///    ::= Type OptionalAttributes Value OptionalAttributes
2151 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2152                                   PerFunctionState &PFS, bool IsMustTailCall,
2153                                   bool InVarArgsFunc) {
2154   if (ParseToken(lltok::lparen, "expected '(' in call"))
2155     return true;
2156 
2157   while (Lex.getKind() != lltok::rparen) {
2158     // If this isn't the first argument, we need a comma.
2159     if (!ArgList.empty() &&
2160         ParseToken(lltok::comma, "expected ',' in argument list"))
2161       return true;
2162 
2163     // Parse an ellipsis if this is a musttail call in a variadic function.
2164     if (Lex.getKind() == lltok::dotdotdot) {
2165       const char *Msg = "unexpected ellipsis in argument list for ";
2166       if (!IsMustTailCall)
2167         return TokError(Twine(Msg) + "non-musttail call");
2168       if (!InVarArgsFunc)
2169         return TokError(Twine(Msg) + "musttail call in non-varargs function");
2170       Lex.Lex();  // Lex the '...', it is purely for readability.
2171       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2172     }
2173 
2174     // Parse the argument.
2175     LocTy ArgLoc;
2176     Type *ArgTy = nullptr;
2177     AttrBuilder ArgAttrs;
2178     Value *V;
2179     if (ParseType(ArgTy, ArgLoc))
2180       return true;
2181 
2182     if (ArgTy->isMetadataTy()) {
2183       if (ParseMetadataAsValue(V, PFS))
2184         return true;
2185     } else {
2186       // Otherwise, handle normal operands.
2187       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2188         return true;
2189     }
2190     ArgList.push_back(ParamInfo(
2191         ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2192   }
2193 
2194   if (IsMustTailCall && InVarArgsFunc)
2195     return TokError("expected '...' at end of argument list for musttail call "
2196                     "in varargs function");
2197 
2198   Lex.Lex();  // Lex the ')'.
2199   return false;
2200 }
2201 
2202 /// ParseOptionalOperandBundles
2203 ///    ::= /*empty*/
2204 ///    ::= '[' OperandBundle [, OperandBundle ]* ']'
2205 ///
2206 /// OperandBundle
2207 ///    ::= bundle-tag '(' ')'
2208 ///    ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2209 ///
2210 /// bundle-tag ::= String Constant
2211 bool LLParser::ParseOptionalOperandBundles(
2212     SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2213   LocTy BeginLoc = Lex.getLoc();
2214   if (!EatIfPresent(lltok::lsquare))
2215     return false;
2216 
2217   while (Lex.getKind() != lltok::rsquare) {
2218     // If this isn't the first operand bundle, we need a comma.
2219     if (!BundleList.empty() &&
2220         ParseToken(lltok::comma, "expected ',' in input list"))
2221       return true;
2222 
2223     std::string Tag;
2224     if (ParseStringConstant(Tag))
2225       return true;
2226 
2227     if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2228       return true;
2229 
2230     std::vector<Value *> Inputs;
2231     while (Lex.getKind() != lltok::rparen) {
2232       // If this isn't the first input, we need a comma.
2233       if (!Inputs.empty() &&
2234           ParseToken(lltok::comma, "expected ',' in input list"))
2235         return true;
2236 
2237       Type *Ty = nullptr;
2238       Value *Input = nullptr;
2239       if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2240         return true;
2241       Inputs.push_back(Input);
2242     }
2243 
2244     BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2245 
2246     Lex.Lex(); // Lex the ')'.
2247   }
2248 
2249   if (BundleList.empty())
2250     return Error(BeginLoc, "operand bundle set must not be empty");
2251 
2252   Lex.Lex(); // Lex the ']'.
2253   return false;
2254 }
2255 
2256 /// ParseArgumentList - Parse the argument list for a function type or function
2257 /// prototype.
2258 ///   ::= '(' ArgTypeListI ')'
2259 /// ArgTypeListI
2260 ///   ::= /*empty*/
2261 ///   ::= '...'
2262 ///   ::= ArgTypeList ',' '...'
2263 ///   ::= ArgType (',' ArgType)*
2264 ///
2265 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2266                                  bool &isVarArg){
2267   isVarArg = false;
2268   assert(Lex.getKind() == lltok::lparen);
2269   Lex.Lex(); // eat the (.
2270 
2271   if (Lex.getKind() == lltok::rparen) {
2272     // empty
2273   } else if (Lex.getKind() == lltok::dotdotdot) {
2274     isVarArg = true;
2275     Lex.Lex();
2276   } else {
2277     LocTy TypeLoc = Lex.getLoc();
2278     Type *ArgTy = nullptr;
2279     AttrBuilder Attrs;
2280     std::string Name;
2281 
2282     if (ParseType(ArgTy) ||
2283         ParseOptionalParamAttrs(Attrs)) return true;
2284 
2285     if (ArgTy->isVoidTy())
2286       return Error(TypeLoc, "argument can not have void type");
2287 
2288     if (Lex.getKind() == lltok::LocalVar) {
2289       Name = Lex.getStrVal();
2290       Lex.Lex();
2291     }
2292 
2293     if (!FunctionType::isValidArgumentType(ArgTy))
2294       return Error(TypeLoc, "invalid type for function argument");
2295 
2296     ArgList.emplace_back(TypeLoc, ArgTy,
2297                          AttributeSet::get(ArgTy->getContext(), Attrs),
2298                          std::move(Name));
2299 
2300     while (EatIfPresent(lltok::comma)) {
2301       // Handle ... at end of arg list.
2302       if (EatIfPresent(lltok::dotdotdot)) {
2303         isVarArg = true;
2304         break;
2305       }
2306 
2307       // Otherwise must be an argument type.
2308       TypeLoc = Lex.getLoc();
2309       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2310 
2311       if (ArgTy->isVoidTy())
2312         return Error(TypeLoc, "argument can not have void type");
2313 
2314       if (Lex.getKind() == lltok::LocalVar) {
2315         Name = Lex.getStrVal();
2316         Lex.Lex();
2317       } else {
2318         Name = "";
2319       }
2320 
2321       if (!ArgTy->isFirstClassType())
2322         return Error(TypeLoc, "invalid type for function argument");
2323 
2324       ArgList.emplace_back(TypeLoc, ArgTy,
2325                            AttributeSet::get(ArgTy->getContext(), Attrs),
2326                            std::move(Name));
2327     }
2328   }
2329 
2330   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2331 }
2332 
2333 /// ParseFunctionType
2334 ///  ::= Type ArgumentList OptionalAttrs
2335 bool LLParser::ParseFunctionType(Type *&Result) {
2336   assert(Lex.getKind() == lltok::lparen);
2337 
2338   if (!FunctionType::isValidReturnType(Result))
2339     return TokError("invalid function return type");
2340 
2341   SmallVector<ArgInfo, 8> ArgList;
2342   bool isVarArg;
2343   if (ParseArgumentList(ArgList, isVarArg))
2344     return true;
2345 
2346   // Reject names on the arguments lists.
2347   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2348     if (!ArgList[i].Name.empty())
2349       return Error(ArgList[i].Loc, "argument name invalid in function type");
2350     if (ArgList[i].Attrs.hasAttributes())
2351       return Error(ArgList[i].Loc,
2352                    "argument attributes invalid in function type");
2353   }
2354 
2355   SmallVector<Type*, 16> ArgListTy;
2356   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2357     ArgListTy.push_back(ArgList[i].Ty);
2358 
2359   Result = FunctionType::get(Result, ArgListTy, isVarArg);
2360   return false;
2361 }
2362 
2363 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2364 /// other structs.
2365 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2366   SmallVector<Type*, 8> Elts;
2367   if (ParseStructBody(Elts)) return true;
2368 
2369   Result = StructType::get(Context, Elts, Packed);
2370   return false;
2371 }
2372 
2373 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2374 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2375                                      std::pair<Type*, LocTy> &Entry,
2376                                      Type *&ResultTy) {
2377   // If the type was already defined, diagnose the redefinition.
2378   if (Entry.first && !Entry.second.isValid())
2379     return Error(TypeLoc, "redefinition of type");
2380 
2381   // If we have opaque, just return without filling in the definition for the
2382   // struct.  This counts as a definition as far as the .ll file goes.
2383   if (EatIfPresent(lltok::kw_opaque)) {
2384     // This type is being defined, so clear the location to indicate this.
2385     Entry.second = SMLoc();
2386 
2387     // If this type number has never been uttered, create it.
2388     if (!Entry.first)
2389       Entry.first = StructType::create(Context, Name);
2390     ResultTy = Entry.first;
2391     return false;
2392   }
2393 
2394   // If the type starts with '<', then it is either a packed struct or a vector.
2395   bool isPacked = EatIfPresent(lltok::less);
2396 
2397   // If we don't have a struct, then we have a random type alias, which we
2398   // accept for compatibility with old files.  These types are not allowed to be
2399   // forward referenced and not allowed to be recursive.
2400   if (Lex.getKind() != lltok::lbrace) {
2401     if (Entry.first)
2402       return Error(TypeLoc, "forward references to non-struct type");
2403 
2404     ResultTy = nullptr;
2405     if (isPacked)
2406       return ParseArrayVectorType(ResultTy, true);
2407     return ParseType(ResultTy);
2408   }
2409 
2410   // This type is being defined, so clear the location to indicate this.
2411   Entry.second = SMLoc();
2412 
2413   // If this type number has never been uttered, create it.
2414   if (!Entry.first)
2415     Entry.first = StructType::create(Context, Name);
2416 
2417   StructType *STy = cast<StructType>(Entry.first);
2418 
2419   SmallVector<Type*, 8> Body;
2420   if (ParseStructBody(Body) ||
2421       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2422     return true;
2423 
2424   STy->setBody(Body, isPacked);
2425   ResultTy = STy;
2426   return false;
2427 }
2428 
2429 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2430 ///   StructType
2431 ///     ::= '{' '}'
2432 ///     ::= '{' Type (',' Type)* '}'
2433 ///     ::= '<' '{' '}' '>'
2434 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2435 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2436   assert(Lex.getKind() == lltok::lbrace);
2437   Lex.Lex(); // Consume the '{'
2438 
2439   // Handle the empty struct.
2440   if (EatIfPresent(lltok::rbrace))
2441     return false;
2442 
2443   LocTy EltTyLoc = Lex.getLoc();
2444   Type *Ty = nullptr;
2445   if (ParseType(Ty)) return true;
2446   Body.push_back(Ty);
2447 
2448   if (!StructType::isValidElementType(Ty))
2449     return Error(EltTyLoc, "invalid element type for struct");
2450 
2451   while (EatIfPresent(lltok::comma)) {
2452     EltTyLoc = Lex.getLoc();
2453     if (ParseType(Ty)) return true;
2454 
2455     if (!StructType::isValidElementType(Ty))
2456       return Error(EltTyLoc, "invalid element type for struct");
2457 
2458     Body.push_back(Ty);
2459   }
2460 
2461   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2462 }
2463 
2464 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2465 /// token has already been consumed.
2466 ///   Type
2467 ///     ::= '[' APSINTVAL 'x' Types ']'
2468 ///     ::= '<' APSINTVAL 'x' Types '>'
2469 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2470   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2471       Lex.getAPSIntVal().getBitWidth() > 64)
2472     return TokError("expected number in address space");
2473 
2474   LocTy SizeLoc = Lex.getLoc();
2475   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2476   Lex.Lex();
2477 
2478   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2479       return true;
2480 
2481   LocTy TypeLoc = Lex.getLoc();
2482   Type *EltTy = nullptr;
2483   if (ParseType(EltTy)) return true;
2484 
2485   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2486                  "expected end of sequential type"))
2487     return true;
2488 
2489   if (isVector) {
2490     if (Size == 0)
2491       return Error(SizeLoc, "zero element vector is illegal");
2492     if ((unsigned)Size != Size)
2493       return Error(SizeLoc, "size too large for vector");
2494     if (!VectorType::isValidElementType(EltTy))
2495       return Error(TypeLoc, "invalid vector element type");
2496     Result = VectorType::get(EltTy, unsigned(Size));
2497   } else {
2498     if (!ArrayType::isValidElementType(EltTy))
2499       return Error(TypeLoc, "invalid array element type");
2500     Result = ArrayType::get(EltTy, Size);
2501   }
2502   return false;
2503 }
2504 
2505 //===----------------------------------------------------------------------===//
2506 // Function Semantic Analysis.
2507 //===----------------------------------------------------------------------===//
2508 
2509 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2510                                              int functionNumber)
2511   : P(p), F(f), FunctionNumber(functionNumber) {
2512 
2513   // Insert unnamed arguments into the NumberedVals list.
2514   for (Argument &A : F.args())
2515     if (!A.hasName())
2516       NumberedVals.push_back(&A);
2517 }
2518 
2519 LLParser::PerFunctionState::~PerFunctionState() {
2520   // If there were any forward referenced non-basicblock values, delete them.
2521 
2522   for (const auto &P : ForwardRefVals) {
2523     if (isa<BasicBlock>(P.second.first))
2524       continue;
2525     P.second.first->replaceAllUsesWith(
2526         UndefValue::get(P.second.first->getType()));
2527     P.second.first->deleteValue();
2528   }
2529 
2530   for (const auto &P : ForwardRefValIDs) {
2531     if (isa<BasicBlock>(P.second.first))
2532       continue;
2533     P.second.first->replaceAllUsesWith(
2534         UndefValue::get(P.second.first->getType()));
2535     P.second.first->deleteValue();
2536   }
2537 }
2538 
2539 bool LLParser::PerFunctionState::FinishFunction() {
2540   if (!ForwardRefVals.empty())
2541     return P.Error(ForwardRefVals.begin()->second.second,
2542                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2543                    "'");
2544   if (!ForwardRefValIDs.empty())
2545     return P.Error(ForwardRefValIDs.begin()->second.second,
2546                    "use of undefined value '%" +
2547                    Twine(ForwardRefValIDs.begin()->first) + "'");
2548   return false;
2549 }
2550 
2551 /// GetVal - Get a value with the specified name or ID, creating a
2552 /// forward reference record if needed.  This can return null if the value
2553 /// exists but does not have the right type.
2554 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2555                                           LocTy Loc) {
2556   // Look this name up in the normal function symbol table.
2557   Value *Val = F.getValueSymbolTable()->lookup(Name);
2558 
2559   // If this is a forward reference for the value, see if we already created a
2560   // forward ref record.
2561   if (!Val) {
2562     auto I = ForwardRefVals.find(Name);
2563     if (I != ForwardRefVals.end())
2564       Val = I->second.first;
2565   }
2566 
2567   // If we have the value in the symbol table or fwd-ref table, return it.
2568   if (Val) {
2569     if (Val->getType() == Ty) return Val;
2570     if (Ty->isLabelTy())
2571       P.Error(Loc, "'%" + Name + "' is not a basic block");
2572     else
2573       P.Error(Loc, "'%" + Name + "' defined with type '" +
2574               getTypeString(Val->getType()) + "'");
2575     return nullptr;
2576   }
2577 
2578   // Don't make placeholders with invalid type.
2579   if (!Ty->isFirstClassType()) {
2580     P.Error(Loc, "invalid use of a non-first-class type");
2581     return nullptr;
2582   }
2583 
2584   // Otherwise, create a new forward reference for this value and remember it.
2585   Value *FwdVal;
2586   if (Ty->isLabelTy()) {
2587     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2588   } else {
2589     FwdVal = new Argument(Ty, Name);
2590   }
2591 
2592   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2593   return FwdVal;
2594 }
2595 
2596 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2597   // Look this name up in the normal function symbol table.
2598   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2599 
2600   // If this is a forward reference for the value, see if we already created a
2601   // forward ref record.
2602   if (!Val) {
2603     auto I = ForwardRefValIDs.find(ID);
2604     if (I != ForwardRefValIDs.end())
2605       Val = I->second.first;
2606   }
2607 
2608   // If we have the value in the symbol table or fwd-ref table, return it.
2609   if (Val) {
2610     if (Val->getType() == Ty) return Val;
2611     if (Ty->isLabelTy())
2612       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2613     else
2614       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2615               getTypeString(Val->getType()) + "'");
2616     return nullptr;
2617   }
2618 
2619   if (!Ty->isFirstClassType()) {
2620     P.Error(Loc, "invalid use of a non-first-class type");
2621     return nullptr;
2622   }
2623 
2624   // Otherwise, create a new forward reference for this value and remember it.
2625   Value *FwdVal;
2626   if (Ty->isLabelTy()) {
2627     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2628   } else {
2629     FwdVal = new Argument(Ty);
2630   }
2631 
2632   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2633   return FwdVal;
2634 }
2635 
2636 /// SetInstName - After an instruction is parsed and inserted into its
2637 /// basic block, this installs its name.
2638 bool LLParser::PerFunctionState::SetInstName(int NameID,
2639                                              const std::string &NameStr,
2640                                              LocTy NameLoc, Instruction *Inst) {
2641   // If this instruction has void type, it cannot have a name or ID specified.
2642   if (Inst->getType()->isVoidTy()) {
2643     if (NameID != -1 || !NameStr.empty())
2644       return P.Error(NameLoc, "instructions returning void cannot have a name");
2645     return false;
2646   }
2647 
2648   // If this was a numbered instruction, verify that the instruction is the
2649   // expected value and resolve any forward references.
2650   if (NameStr.empty()) {
2651     // If neither a name nor an ID was specified, just use the next ID.
2652     if (NameID == -1)
2653       NameID = NumberedVals.size();
2654 
2655     if (unsigned(NameID) != NumberedVals.size())
2656       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2657                      Twine(NumberedVals.size()) + "'");
2658 
2659     auto FI = ForwardRefValIDs.find(NameID);
2660     if (FI != ForwardRefValIDs.end()) {
2661       Value *Sentinel = FI->second.first;
2662       if (Sentinel->getType() != Inst->getType())
2663         return P.Error(NameLoc, "instruction forward referenced with type '" +
2664                        getTypeString(FI->second.first->getType()) + "'");
2665 
2666       Sentinel->replaceAllUsesWith(Inst);
2667       Sentinel->deleteValue();
2668       ForwardRefValIDs.erase(FI);
2669     }
2670 
2671     NumberedVals.push_back(Inst);
2672     return false;
2673   }
2674 
2675   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2676   auto FI = ForwardRefVals.find(NameStr);
2677   if (FI != ForwardRefVals.end()) {
2678     Value *Sentinel = FI->second.first;
2679     if (Sentinel->getType() != Inst->getType())
2680       return P.Error(NameLoc, "instruction forward referenced with type '" +
2681                      getTypeString(FI->second.first->getType()) + "'");
2682 
2683     Sentinel->replaceAllUsesWith(Inst);
2684     Sentinel->deleteValue();
2685     ForwardRefVals.erase(FI);
2686   }
2687 
2688   // Set the name on the instruction.
2689   Inst->setName(NameStr);
2690 
2691   if (Inst->getName() != NameStr)
2692     return P.Error(NameLoc, "multiple definition of local value named '" +
2693                    NameStr + "'");
2694   return false;
2695 }
2696 
2697 /// GetBB - Get a basic block with the specified name or ID, creating a
2698 /// forward reference record if needed.
2699 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2700                                               LocTy Loc) {
2701   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2702                                       Type::getLabelTy(F.getContext()), Loc));
2703 }
2704 
2705 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2706   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2707                                       Type::getLabelTy(F.getContext()), Loc));
2708 }
2709 
2710 /// DefineBB - Define the specified basic block, which is either named or
2711 /// unnamed.  If there is an error, this returns null otherwise it returns
2712 /// the block being defined.
2713 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2714                                                  LocTy Loc) {
2715   BasicBlock *BB;
2716   if (Name.empty())
2717     BB = GetBB(NumberedVals.size(), Loc);
2718   else
2719     BB = GetBB(Name, Loc);
2720   if (!BB) return nullptr; // Already diagnosed error.
2721 
2722   // Move the block to the end of the function.  Forward ref'd blocks are
2723   // inserted wherever they happen to be referenced.
2724   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2725 
2726   // Remove the block from forward ref sets.
2727   if (Name.empty()) {
2728     ForwardRefValIDs.erase(NumberedVals.size());
2729     NumberedVals.push_back(BB);
2730   } else {
2731     // BB forward references are already in the function symbol table.
2732     ForwardRefVals.erase(Name);
2733   }
2734 
2735   return BB;
2736 }
2737 
2738 //===----------------------------------------------------------------------===//
2739 // Constants.
2740 //===----------------------------------------------------------------------===//
2741 
2742 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2743 /// type implied.  For example, if we parse "4" we don't know what integer type
2744 /// it has.  The value will later be combined with its type and checked for
2745 /// sanity.  PFS is used to convert function-local operands of metadata (since
2746 /// metadata operands are not just parsed here but also converted to values).
2747 /// PFS can be null when we are not parsing metadata values inside a function.
2748 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2749   ID.Loc = Lex.getLoc();
2750   switch (Lex.getKind()) {
2751   default: return TokError("expected value token");
2752   case lltok::GlobalID:  // @42
2753     ID.UIntVal = Lex.getUIntVal();
2754     ID.Kind = ValID::t_GlobalID;
2755     break;
2756   case lltok::GlobalVar:  // @foo
2757     ID.StrVal = Lex.getStrVal();
2758     ID.Kind = ValID::t_GlobalName;
2759     break;
2760   case lltok::LocalVarID:  // %42
2761     ID.UIntVal = Lex.getUIntVal();
2762     ID.Kind = ValID::t_LocalID;
2763     break;
2764   case lltok::LocalVar:  // %foo
2765     ID.StrVal = Lex.getStrVal();
2766     ID.Kind = ValID::t_LocalName;
2767     break;
2768   case lltok::APSInt:
2769     ID.APSIntVal = Lex.getAPSIntVal();
2770     ID.Kind = ValID::t_APSInt;
2771     break;
2772   case lltok::APFloat:
2773     ID.APFloatVal = Lex.getAPFloatVal();
2774     ID.Kind = ValID::t_APFloat;
2775     break;
2776   case lltok::kw_true:
2777     ID.ConstantVal = ConstantInt::getTrue(Context);
2778     ID.Kind = ValID::t_Constant;
2779     break;
2780   case lltok::kw_false:
2781     ID.ConstantVal = ConstantInt::getFalse(Context);
2782     ID.Kind = ValID::t_Constant;
2783     break;
2784   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2785   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2786   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2787   case lltok::kw_none: ID.Kind = ValID::t_None; break;
2788 
2789   case lltok::lbrace: {
2790     // ValID ::= '{' ConstVector '}'
2791     Lex.Lex();
2792     SmallVector<Constant*, 16> Elts;
2793     if (ParseGlobalValueVector(Elts) ||
2794         ParseToken(lltok::rbrace, "expected end of struct constant"))
2795       return true;
2796 
2797     ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2798     ID.UIntVal = Elts.size();
2799     memcpy(ID.ConstantStructElts.get(), Elts.data(),
2800            Elts.size() * sizeof(Elts[0]));
2801     ID.Kind = ValID::t_ConstantStruct;
2802     return false;
2803   }
2804   case lltok::less: {
2805     // ValID ::= '<' ConstVector '>'         --> Vector.
2806     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2807     Lex.Lex();
2808     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2809 
2810     SmallVector<Constant*, 16> Elts;
2811     LocTy FirstEltLoc = Lex.getLoc();
2812     if (ParseGlobalValueVector(Elts) ||
2813         (isPackedStruct &&
2814          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2815         ParseToken(lltok::greater, "expected end of constant"))
2816       return true;
2817 
2818     if (isPackedStruct) {
2819       ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2820       memcpy(ID.ConstantStructElts.get(), Elts.data(),
2821              Elts.size() * sizeof(Elts[0]));
2822       ID.UIntVal = Elts.size();
2823       ID.Kind = ValID::t_PackedConstantStruct;
2824       return false;
2825     }
2826 
2827     if (Elts.empty())
2828       return Error(ID.Loc, "constant vector must not be empty");
2829 
2830     if (!Elts[0]->getType()->isIntegerTy() &&
2831         !Elts[0]->getType()->isFloatingPointTy() &&
2832         !Elts[0]->getType()->isPointerTy())
2833       return Error(FirstEltLoc,
2834             "vector elements must have integer, pointer or floating point type");
2835 
2836     // Verify that all the vector elements have the same type.
2837     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2838       if (Elts[i]->getType() != Elts[0]->getType())
2839         return Error(FirstEltLoc,
2840                      "vector element #" + Twine(i) +
2841                     " is not of type '" + getTypeString(Elts[0]->getType()));
2842 
2843     ID.ConstantVal = ConstantVector::get(Elts);
2844     ID.Kind = ValID::t_Constant;
2845     return false;
2846   }
2847   case lltok::lsquare: {   // Array Constant
2848     Lex.Lex();
2849     SmallVector<Constant*, 16> Elts;
2850     LocTy FirstEltLoc = Lex.getLoc();
2851     if (ParseGlobalValueVector(Elts) ||
2852         ParseToken(lltok::rsquare, "expected end of array constant"))
2853       return true;
2854 
2855     // Handle empty element.
2856     if (Elts.empty()) {
2857       // Use undef instead of an array because it's inconvenient to determine
2858       // the element type at this point, there being no elements to examine.
2859       ID.Kind = ValID::t_EmptyArray;
2860       return false;
2861     }
2862 
2863     if (!Elts[0]->getType()->isFirstClassType())
2864       return Error(FirstEltLoc, "invalid array element type: " +
2865                    getTypeString(Elts[0]->getType()));
2866 
2867     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2868 
2869     // Verify all elements are correct type!
2870     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2871       if (Elts[i]->getType() != Elts[0]->getType())
2872         return Error(FirstEltLoc,
2873                      "array element #" + Twine(i) +
2874                      " is not of type '" + getTypeString(Elts[0]->getType()));
2875     }
2876 
2877     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2878     ID.Kind = ValID::t_Constant;
2879     return false;
2880   }
2881   case lltok::kw_c:  // c "foo"
2882     Lex.Lex();
2883     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2884                                                   false);
2885     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2886     ID.Kind = ValID::t_Constant;
2887     return false;
2888 
2889   case lltok::kw_asm: {
2890     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2891     //             STRINGCONSTANT
2892     bool HasSideEffect, AlignStack, AsmDialect;
2893     Lex.Lex();
2894     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2895         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2896         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2897         ParseStringConstant(ID.StrVal) ||
2898         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2899         ParseToken(lltok::StringConstant, "expected constraint string"))
2900       return true;
2901     ID.StrVal2 = Lex.getStrVal();
2902     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2903       (unsigned(AsmDialect)<<2);
2904     ID.Kind = ValID::t_InlineAsm;
2905     return false;
2906   }
2907 
2908   case lltok::kw_blockaddress: {
2909     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2910     Lex.Lex();
2911 
2912     ValID Fn, Label;
2913 
2914     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2915         ParseValID(Fn) ||
2916         ParseToken(lltok::comma, "expected comma in block address expression")||
2917         ParseValID(Label) ||
2918         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2919       return true;
2920 
2921     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2922       return Error(Fn.Loc, "expected function name in blockaddress");
2923     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2924       return Error(Label.Loc, "expected basic block name in blockaddress");
2925 
2926     // Try to find the function (but skip it if it's forward-referenced).
2927     GlobalValue *GV = nullptr;
2928     if (Fn.Kind == ValID::t_GlobalID) {
2929       if (Fn.UIntVal < NumberedVals.size())
2930         GV = NumberedVals[Fn.UIntVal];
2931     } else if (!ForwardRefVals.count(Fn.StrVal)) {
2932       GV = M->getNamedValue(Fn.StrVal);
2933     }
2934     Function *F = nullptr;
2935     if (GV) {
2936       // Confirm that it's actually a function with a definition.
2937       if (!isa<Function>(GV))
2938         return Error(Fn.Loc, "expected function name in blockaddress");
2939       F = cast<Function>(GV);
2940       if (F->isDeclaration())
2941         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2942     }
2943 
2944     if (!F) {
2945       // Make a global variable as a placeholder for this reference.
2946       GlobalValue *&FwdRef =
2947           ForwardRefBlockAddresses.insert(std::make_pair(
2948                                               std::move(Fn),
2949                                               std::map<ValID, GlobalValue *>()))
2950               .first->second.insert(std::make_pair(std::move(Label), nullptr))
2951               .first->second;
2952       if (!FwdRef)
2953         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2954                                     GlobalValue::InternalLinkage, nullptr, "");
2955       ID.ConstantVal = FwdRef;
2956       ID.Kind = ValID::t_Constant;
2957       return false;
2958     }
2959 
2960     // We found the function; now find the basic block.  Don't use PFS, since we
2961     // might be inside a constant expression.
2962     BasicBlock *BB;
2963     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2964       if (Label.Kind == ValID::t_LocalID)
2965         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2966       else
2967         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2968       if (!BB)
2969         return Error(Label.Loc, "referenced value is not a basic block");
2970     } else {
2971       if (Label.Kind == ValID::t_LocalID)
2972         return Error(Label.Loc, "cannot take address of numeric label after "
2973                                 "the function is defined");
2974       BB = dyn_cast_or_null<BasicBlock>(
2975           F->getValueSymbolTable()->lookup(Label.StrVal));
2976       if (!BB)
2977         return Error(Label.Loc, "referenced value is not a basic block");
2978     }
2979 
2980     ID.ConstantVal = BlockAddress::get(F, BB);
2981     ID.Kind = ValID::t_Constant;
2982     return false;
2983   }
2984 
2985   case lltok::kw_trunc:
2986   case lltok::kw_zext:
2987   case lltok::kw_sext:
2988   case lltok::kw_fptrunc:
2989   case lltok::kw_fpext:
2990   case lltok::kw_bitcast:
2991   case lltok::kw_addrspacecast:
2992   case lltok::kw_uitofp:
2993   case lltok::kw_sitofp:
2994   case lltok::kw_fptoui:
2995   case lltok::kw_fptosi:
2996   case lltok::kw_inttoptr:
2997   case lltok::kw_ptrtoint: {
2998     unsigned Opc = Lex.getUIntVal();
2999     Type *DestTy = nullptr;
3000     Constant *SrcVal;
3001     Lex.Lex();
3002     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3003         ParseGlobalTypeAndValue(SrcVal) ||
3004         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3005         ParseType(DestTy) ||
3006         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3007       return true;
3008     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3009       return Error(ID.Loc, "invalid cast opcode for cast from '" +
3010                    getTypeString(SrcVal->getType()) + "' to '" +
3011                    getTypeString(DestTy) + "'");
3012     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3013                                                  SrcVal, DestTy);
3014     ID.Kind = ValID::t_Constant;
3015     return false;
3016   }
3017   case lltok::kw_extractvalue: {
3018     Lex.Lex();
3019     Constant *Val;
3020     SmallVector<unsigned, 4> Indices;
3021     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3022         ParseGlobalTypeAndValue(Val) ||
3023         ParseIndexList(Indices) ||
3024         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3025       return true;
3026 
3027     if (!Val->getType()->isAggregateType())
3028       return Error(ID.Loc, "extractvalue operand must be aggregate type");
3029     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3030       return Error(ID.Loc, "invalid indices for extractvalue");
3031     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3032     ID.Kind = ValID::t_Constant;
3033     return false;
3034   }
3035   case lltok::kw_insertvalue: {
3036     Lex.Lex();
3037     Constant *Val0, *Val1;
3038     SmallVector<unsigned, 4> Indices;
3039     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3040         ParseGlobalTypeAndValue(Val0) ||
3041         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3042         ParseGlobalTypeAndValue(Val1) ||
3043         ParseIndexList(Indices) ||
3044         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3045       return true;
3046     if (!Val0->getType()->isAggregateType())
3047       return Error(ID.Loc, "insertvalue operand must be aggregate type");
3048     Type *IndexedType =
3049         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3050     if (!IndexedType)
3051       return Error(ID.Loc, "invalid indices for insertvalue");
3052     if (IndexedType != Val1->getType())
3053       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3054                                getTypeString(Val1->getType()) +
3055                                "' instead of '" + getTypeString(IndexedType) +
3056                                "'");
3057     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3058     ID.Kind = ValID::t_Constant;
3059     return false;
3060   }
3061   case lltok::kw_icmp:
3062   case lltok::kw_fcmp: {
3063     unsigned PredVal, Opc = Lex.getUIntVal();
3064     Constant *Val0, *Val1;
3065     Lex.Lex();
3066     if (ParseCmpPredicate(PredVal, Opc) ||
3067         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3068         ParseGlobalTypeAndValue(Val0) ||
3069         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3070         ParseGlobalTypeAndValue(Val1) ||
3071         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3072       return true;
3073 
3074     if (Val0->getType() != Val1->getType())
3075       return Error(ID.Loc, "compare operands must have the same type");
3076 
3077     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3078 
3079     if (Opc == Instruction::FCmp) {
3080       if (!Val0->getType()->isFPOrFPVectorTy())
3081         return Error(ID.Loc, "fcmp requires floating point operands");
3082       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3083     } else {
3084       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3085       if (!Val0->getType()->isIntOrIntVectorTy() &&
3086           !Val0->getType()->isPtrOrPtrVectorTy())
3087         return Error(ID.Loc, "icmp requires pointer or integer operands");
3088       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3089     }
3090     ID.Kind = ValID::t_Constant;
3091     return false;
3092   }
3093 
3094   // Binary Operators.
3095   case lltok::kw_add:
3096   case lltok::kw_fadd:
3097   case lltok::kw_sub:
3098   case lltok::kw_fsub:
3099   case lltok::kw_mul:
3100   case lltok::kw_fmul:
3101   case lltok::kw_udiv:
3102   case lltok::kw_sdiv:
3103   case lltok::kw_fdiv:
3104   case lltok::kw_urem:
3105   case lltok::kw_srem:
3106   case lltok::kw_frem:
3107   case lltok::kw_shl:
3108   case lltok::kw_lshr:
3109   case lltok::kw_ashr: {
3110     bool NUW = false;
3111     bool NSW = false;
3112     bool Exact = false;
3113     unsigned Opc = Lex.getUIntVal();
3114     Constant *Val0, *Val1;
3115     Lex.Lex();
3116     LocTy ModifierLoc = Lex.getLoc();
3117     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3118         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3119       if (EatIfPresent(lltok::kw_nuw))
3120         NUW = true;
3121       if (EatIfPresent(lltok::kw_nsw)) {
3122         NSW = true;
3123         if (EatIfPresent(lltok::kw_nuw))
3124           NUW = true;
3125       }
3126     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3127                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3128       if (EatIfPresent(lltok::kw_exact))
3129         Exact = true;
3130     }
3131     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3132         ParseGlobalTypeAndValue(Val0) ||
3133         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3134         ParseGlobalTypeAndValue(Val1) ||
3135         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3136       return true;
3137     if (Val0->getType() != Val1->getType())
3138       return Error(ID.Loc, "operands of constexpr must have same type");
3139     if (!Val0->getType()->isIntOrIntVectorTy()) {
3140       if (NUW)
3141         return Error(ModifierLoc, "nuw only applies to integer operations");
3142       if (NSW)
3143         return Error(ModifierLoc, "nsw only applies to integer operations");
3144     }
3145     // Check that the type is valid for the operator.
3146     switch (Opc) {
3147     case Instruction::Add:
3148     case Instruction::Sub:
3149     case Instruction::Mul:
3150     case Instruction::UDiv:
3151     case Instruction::SDiv:
3152     case Instruction::URem:
3153     case Instruction::SRem:
3154     case Instruction::Shl:
3155     case Instruction::AShr:
3156     case Instruction::LShr:
3157       if (!Val0->getType()->isIntOrIntVectorTy())
3158         return Error(ID.Loc, "constexpr requires integer operands");
3159       break;
3160     case Instruction::FAdd:
3161     case Instruction::FSub:
3162     case Instruction::FMul:
3163     case Instruction::FDiv:
3164     case Instruction::FRem:
3165       if (!Val0->getType()->isFPOrFPVectorTy())
3166         return Error(ID.Loc, "constexpr requires fp operands");
3167       break;
3168     default: llvm_unreachable("Unknown binary operator!");
3169     }
3170     unsigned Flags = 0;
3171     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3172     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3173     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3174     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3175     ID.ConstantVal = C;
3176     ID.Kind = ValID::t_Constant;
3177     return false;
3178   }
3179 
3180   // Logical Operations
3181   case lltok::kw_and:
3182   case lltok::kw_or:
3183   case lltok::kw_xor: {
3184     unsigned Opc = Lex.getUIntVal();
3185     Constant *Val0, *Val1;
3186     Lex.Lex();
3187     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3188         ParseGlobalTypeAndValue(Val0) ||
3189         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3190         ParseGlobalTypeAndValue(Val1) ||
3191         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3192       return true;
3193     if (Val0->getType() != Val1->getType())
3194       return Error(ID.Loc, "operands of constexpr must have same type");
3195     if (!Val0->getType()->isIntOrIntVectorTy())
3196       return Error(ID.Loc,
3197                    "constexpr requires integer or integer vector operands");
3198     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3199     ID.Kind = ValID::t_Constant;
3200     return false;
3201   }
3202 
3203   case lltok::kw_getelementptr:
3204   case lltok::kw_shufflevector:
3205   case lltok::kw_insertelement:
3206   case lltok::kw_extractelement:
3207   case lltok::kw_select: {
3208     unsigned Opc = Lex.getUIntVal();
3209     SmallVector<Constant*, 16> Elts;
3210     bool InBounds = false;
3211     Type *Ty;
3212     Lex.Lex();
3213 
3214     if (Opc == Instruction::GetElementPtr)
3215       InBounds = EatIfPresent(lltok::kw_inbounds);
3216 
3217     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3218       return true;
3219 
3220     LocTy ExplicitTypeLoc = Lex.getLoc();
3221     if (Opc == Instruction::GetElementPtr) {
3222       if (ParseType(Ty) ||
3223           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3224         return true;
3225     }
3226 
3227     Optional<unsigned> InRangeOp;
3228     if (ParseGlobalValueVector(
3229             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3230         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3231       return true;
3232 
3233     if (Opc == Instruction::GetElementPtr) {
3234       if (Elts.size() == 0 ||
3235           !Elts[0]->getType()->isPtrOrPtrVectorTy())
3236         return Error(ID.Loc, "base of getelementptr must be a pointer");
3237 
3238       Type *BaseType = Elts[0]->getType();
3239       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3240       if (Ty != BasePointerType->getElementType())
3241         return Error(
3242             ExplicitTypeLoc,
3243             "explicit pointee type doesn't match operand's pointee type");
3244 
3245       unsigned GEPWidth =
3246           BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3247 
3248       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3249       for (Constant *Val : Indices) {
3250         Type *ValTy = Val->getType();
3251         if (!ValTy->isIntOrIntVectorTy())
3252           return Error(ID.Loc, "getelementptr index must be an integer");
3253         if (ValTy->isVectorTy()) {
3254           unsigned ValNumEl = ValTy->getVectorNumElements();
3255           if (GEPWidth && (ValNumEl != GEPWidth))
3256             return Error(
3257                 ID.Loc,
3258                 "getelementptr vector index has a wrong number of elements");
3259           // GEPWidth may have been unknown because the base is a scalar,
3260           // but it is known now.
3261           GEPWidth = ValNumEl;
3262         }
3263       }
3264 
3265       SmallPtrSet<Type*, 4> Visited;
3266       if (!Indices.empty() && !Ty->isSized(&Visited))
3267         return Error(ID.Loc, "base element of getelementptr must be sized");
3268 
3269       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3270         return Error(ID.Loc, "invalid getelementptr indices");
3271 
3272       if (InRangeOp) {
3273         if (*InRangeOp == 0)
3274           return Error(ID.Loc,
3275                        "inrange keyword may not appear on pointer operand");
3276         --*InRangeOp;
3277       }
3278 
3279       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3280                                                       InBounds, InRangeOp);
3281     } else if (Opc == Instruction::Select) {
3282       if (Elts.size() != 3)
3283         return Error(ID.Loc, "expected three operands to select");
3284       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3285                                                               Elts[2]))
3286         return Error(ID.Loc, Reason);
3287       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3288     } else if (Opc == Instruction::ShuffleVector) {
3289       if (Elts.size() != 3)
3290         return Error(ID.Loc, "expected three operands to shufflevector");
3291       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3292         return Error(ID.Loc, "invalid operands to shufflevector");
3293       ID.ConstantVal =
3294                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3295     } else if (Opc == Instruction::ExtractElement) {
3296       if (Elts.size() != 2)
3297         return Error(ID.Loc, "expected two operands to extractelement");
3298       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3299         return Error(ID.Loc, "invalid extractelement operands");
3300       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3301     } else {
3302       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3303       if (Elts.size() != 3)
3304       return Error(ID.Loc, "expected three operands to insertelement");
3305       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3306         return Error(ID.Loc, "invalid insertelement operands");
3307       ID.ConstantVal =
3308                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3309     }
3310 
3311     ID.Kind = ValID::t_Constant;
3312     return false;
3313   }
3314   }
3315 
3316   Lex.Lex();
3317   return false;
3318 }
3319 
3320 /// ParseGlobalValue - Parse a global value with the specified type.
3321 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3322   C = nullptr;
3323   ValID ID;
3324   Value *V = nullptr;
3325   bool Parsed = ParseValID(ID) ||
3326                 ConvertValIDToValue(Ty, ID, V, nullptr);
3327   if (V && !(C = dyn_cast<Constant>(V)))
3328     return Error(ID.Loc, "global values must be constants");
3329   return Parsed;
3330 }
3331 
3332 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3333   Type *Ty = nullptr;
3334   return ParseType(Ty) ||
3335          ParseGlobalValue(Ty, V);
3336 }
3337 
3338 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3339   C = nullptr;
3340 
3341   LocTy KwLoc = Lex.getLoc();
3342   if (!EatIfPresent(lltok::kw_comdat))
3343     return false;
3344 
3345   if (EatIfPresent(lltok::lparen)) {
3346     if (Lex.getKind() != lltok::ComdatVar)
3347       return TokError("expected comdat variable");
3348     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3349     Lex.Lex();
3350     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3351       return true;
3352   } else {
3353     if (GlobalName.empty())
3354       return TokError("comdat cannot be unnamed");
3355     C = getComdat(GlobalName, KwLoc);
3356   }
3357 
3358   return false;
3359 }
3360 
3361 /// ParseGlobalValueVector
3362 ///   ::= /*empty*/
3363 ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3364 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3365                                       Optional<unsigned> *InRangeOp) {
3366   // Empty list.
3367   if (Lex.getKind() == lltok::rbrace ||
3368       Lex.getKind() == lltok::rsquare ||
3369       Lex.getKind() == lltok::greater ||
3370       Lex.getKind() == lltok::rparen)
3371     return false;
3372 
3373   do {
3374     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3375       *InRangeOp = Elts.size();
3376 
3377     Constant *C;
3378     if (ParseGlobalTypeAndValue(C)) return true;
3379     Elts.push_back(C);
3380   } while (EatIfPresent(lltok::comma));
3381 
3382   return false;
3383 }
3384 
3385 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3386   SmallVector<Metadata *, 16> Elts;
3387   if (ParseMDNodeVector(Elts))
3388     return true;
3389 
3390   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3391   return false;
3392 }
3393 
3394 /// MDNode:
3395 ///  ::= !{ ... }
3396 ///  ::= !7
3397 ///  ::= !DILocation(...)
3398 bool LLParser::ParseMDNode(MDNode *&N) {
3399   if (Lex.getKind() == lltok::MetadataVar)
3400     return ParseSpecializedMDNode(N);
3401 
3402   return ParseToken(lltok::exclaim, "expected '!' here") ||
3403          ParseMDNodeTail(N);
3404 }
3405 
3406 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3407   // !{ ... }
3408   if (Lex.getKind() == lltok::lbrace)
3409     return ParseMDTuple(N);
3410 
3411   // !42
3412   return ParseMDNodeID(N);
3413 }
3414 
3415 namespace {
3416 
3417 /// Structure to represent an optional metadata field.
3418 template <class FieldTy> struct MDFieldImpl {
3419   typedef MDFieldImpl ImplTy;
3420   FieldTy Val;
3421   bool Seen;
3422 
3423   void assign(FieldTy Val) {
3424     Seen = true;
3425     this->Val = std::move(Val);
3426   }
3427 
3428   explicit MDFieldImpl(FieldTy Default)
3429       : Val(std::move(Default)), Seen(false) {}
3430 };
3431 
3432 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3433   uint64_t Max;
3434 
3435   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3436       : ImplTy(Default), Max(Max) {}
3437 };
3438 
3439 struct LineField : public MDUnsignedField {
3440   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3441 };
3442 
3443 struct ColumnField : public MDUnsignedField {
3444   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3445 };
3446 
3447 struct DwarfTagField : public MDUnsignedField {
3448   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3449   DwarfTagField(dwarf::Tag DefaultTag)
3450       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3451 };
3452 
3453 struct DwarfMacinfoTypeField : public MDUnsignedField {
3454   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3455   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3456     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3457 };
3458 
3459 struct DwarfAttEncodingField : public MDUnsignedField {
3460   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3461 };
3462 
3463 struct DwarfVirtualityField : public MDUnsignedField {
3464   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3465 };
3466 
3467 struct DwarfLangField : public MDUnsignedField {
3468   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3469 };
3470 
3471 struct DwarfCCField : public MDUnsignedField {
3472   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3473 };
3474 
3475 struct EmissionKindField : public MDUnsignedField {
3476   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3477 };
3478 
3479 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3480   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3481 };
3482 
3483 struct MDSignedField : public MDFieldImpl<int64_t> {
3484   int64_t Min;
3485   int64_t Max;
3486 
3487   MDSignedField(int64_t Default = 0)
3488       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3489   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3490       : ImplTy(Default), Min(Min), Max(Max) {}
3491 };
3492 
3493 struct MDBoolField : public MDFieldImpl<bool> {
3494   MDBoolField(bool Default = false) : ImplTy(Default) {}
3495 };
3496 
3497 struct MDField : public MDFieldImpl<Metadata *> {
3498   bool AllowNull;
3499 
3500   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3501 };
3502 
3503 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3504   MDConstant() : ImplTy(nullptr) {}
3505 };
3506 
3507 struct MDStringField : public MDFieldImpl<MDString *> {
3508   bool AllowEmpty;
3509   MDStringField(bool AllowEmpty = true)
3510       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3511 };
3512 
3513 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3514   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3515 };
3516 
3517 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3518   ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3519   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3520 };
3521 
3522 } // end anonymous namespace
3523 
3524 namespace llvm {
3525 
3526 template <>
3527 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3528                             MDUnsignedField &Result) {
3529   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3530     return TokError("expected unsigned integer");
3531 
3532   auto &U = Lex.getAPSIntVal();
3533   if (U.ugt(Result.Max))
3534     return TokError("value for '" + Name + "' too large, limit is " +
3535                     Twine(Result.Max));
3536   Result.assign(U.getZExtValue());
3537   assert(Result.Val <= Result.Max && "Expected value in range");
3538   Lex.Lex();
3539   return false;
3540 }
3541 
3542 template <>
3543 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3544   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3545 }
3546 template <>
3547 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3548   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3549 }
3550 
3551 template <>
3552 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3553   if (Lex.getKind() == lltok::APSInt)
3554     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3555 
3556   if (Lex.getKind() != lltok::DwarfTag)
3557     return TokError("expected DWARF tag");
3558 
3559   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3560   if (Tag == dwarf::DW_TAG_invalid)
3561     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3562   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3563 
3564   Result.assign(Tag);
3565   Lex.Lex();
3566   return false;
3567 }
3568 
3569 template <>
3570 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3571                             DwarfMacinfoTypeField &Result) {
3572   if (Lex.getKind() == lltok::APSInt)
3573     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3574 
3575   if (Lex.getKind() != lltok::DwarfMacinfo)
3576     return TokError("expected DWARF macinfo type");
3577 
3578   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3579   if (Macinfo == dwarf::DW_MACINFO_invalid)
3580     return TokError(
3581         "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3582   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3583 
3584   Result.assign(Macinfo);
3585   Lex.Lex();
3586   return false;
3587 }
3588 
3589 template <>
3590 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3591                             DwarfVirtualityField &Result) {
3592   if (Lex.getKind() == lltok::APSInt)
3593     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3594 
3595   if (Lex.getKind() != lltok::DwarfVirtuality)
3596     return TokError("expected DWARF virtuality code");
3597 
3598   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3599   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3600     return TokError("invalid DWARF virtuality code" + Twine(" '") +
3601                     Lex.getStrVal() + "'");
3602   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3603   Result.assign(Virtuality);
3604   Lex.Lex();
3605   return false;
3606 }
3607 
3608 template <>
3609 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3610   if (Lex.getKind() == lltok::APSInt)
3611     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3612 
3613   if (Lex.getKind() != lltok::DwarfLang)
3614     return TokError("expected DWARF language");
3615 
3616   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3617   if (!Lang)
3618     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3619                     "'");
3620   assert(Lang <= Result.Max && "Expected valid DWARF language");
3621   Result.assign(Lang);
3622   Lex.Lex();
3623   return false;
3624 }
3625 
3626 template <>
3627 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3628   if (Lex.getKind() == lltok::APSInt)
3629     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3630 
3631   if (Lex.getKind() != lltok::DwarfCC)
3632     return TokError("expected DWARF calling convention");
3633 
3634   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3635   if (!CC)
3636     return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3637                     "'");
3638   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3639   Result.assign(CC);
3640   Lex.Lex();
3641   return false;
3642 }
3643 
3644 template <>
3645 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3646   if (Lex.getKind() == lltok::APSInt)
3647     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3648 
3649   if (Lex.getKind() != lltok::EmissionKind)
3650     return TokError("expected emission kind");
3651 
3652   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3653   if (!Kind)
3654     return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3655                     "'");
3656   assert(*Kind <= Result.Max && "Expected valid emission kind");
3657   Result.assign(*Kind);
3658   Lex.Lex();
3659   return false;
3660 }
3661 
3662 template <>
3663 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3664                             DwarfAttEncodingField &Result) {
3665   if (Lex.getKind() == lltok::APSInt)
3666     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3667 
3668   if (Lex.getKind() != lltok::DwarfAttEncoding)
3669     return TokError("expected DWARF type attribute encoding");
3670 
3671   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3672   if (!Encoding)
3673     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3674                     Lex.getStrVal() + "'");
3675   assert(Encoding <= Result.Max && "Expected valid DWARF language");
3676   Result.assign(Encoding);
3677   Lex.Lex();
3678   return false;
3679 }
3680 
3681 /// DIFlagField
3682 ///  ::= uint32
3683 ///  ::= DIFlagVector
3684 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3685 template <>
3686 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3687 
3688   // Parser for a single flag.
3689   auto parseFlag = [&](DINode::DIFlags &Val) {
3690     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3691       uint32_t TempVal = static_cast<uint32_t>(Val);
3692       bool Res = ParseUInt32(TempVal);
3693       Val = static_cast<DINode::DIFlags>(TempVal);
3694       return Res;
3695     }
3696 
3697     if (Lex.getKind() != lltok::DIFlag)
3698       return TokError("expected debug info flag");
3699 
3700     Val = DINode::getFlag(Lex.getStrVal());
3701     if (!Val)
3702       return TokError(Twine("invalid debug info flag flag '") +
3703                       Lex.getStrVal() + "'");
3704     Lex.Lex();
3705     return false;
3706   };
3707 
3708   // Parse the flags and combine them together.
3709   DINode::DIFlags Combined = DINode::FlagZero;
3710   do {
3711     DINode::DIFlags Val;
3712     if (parseFlag(Val))
3713       return true;
3714     Combined |= Val;
3715   } while (EatIfPresent(lltok::bar));
3716 
3717   Result.assign(Combined);
3718   return false;
3719 }
3720 
3721 template <>
3722 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3723                             MDSignedField &Result) {
3724   if (Lex.getKind() != lltok::APSInt)
3725     return TokError("expected signed integer");
3726 
3727   auto &S = Lex.getAPSIntVal();
3728   if (S < Result.Min)
3729     return TokError("value for '" + Name + "' too small, limit is " +
3730                     Twine(Result.Min));
3731   if (S > Result.Max)
3732     return TokError("value for '" + Name + "' too large, limit is " +
3733                     Twine(Result.Max));
3734   Result.assign(S.getExtValue());
3735   assert(Result.Val >= Result.Min && "Expected value in range");
3736   assert(Result.Val <= Result.Max && "Expected value in range");
3737   Lex.Lex();
3738   return false;
3739 }
3740 
3741 template <>
3742 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3743   switch (Lex.getKind()) {
3744   default:
3745     return TokError("expected 'true' or 'false'");
3746   case lltok::kw_true:
3747     Result.assign(true);
3748     break;
3749   case lltok::kw_false:
3750     Result.assign(false);
3751     break;
3752   }
3753   Lex.Lex();
3754   return false;
3755 }
3756 
3757 template <>
3758 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3759   if (Lex.getKind() == lltok::kw_null) {
3760     if (!Result.AllowNull)
3761       return TokError("'" + Name + "' cannot be null");
3762     Lex.Lex();
3763     Result.assign(nullptr);
3764     return false;
3765   }
3766 
3767   Metadata *MD;
3768   if (ParseMetadata(MD, nullptr))
3769     return true;
3770 
3771   Result.assign(MD);
3772   return false;
3773 }
3774 
3775 template <>
3776 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3777   LocTy ValueLoc = Lex.getLoc();
3778   std::string S;
3779   if (ParseStringConstant(S))
3780     return true;
3781 
3782   if (!Result.AllowEmpty && S.empty())
3783     return Error(ValueLoc, "'" + Name + "' cannot be empty");
3784 
3785   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3786   return false;
3787 }
3788 
3789 template <>
3790 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3791   SmallVector<Metadata *, 4> MDs;
3792   if (ParseMDNodeVector(MDs))
3793     return true;
3794 
3795   Result.assign(std::move(MDs));
3796   return false;
3797 }
3798 
3799 template <>
3800 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3801                             ChecksumKindField &Result) {
3802   if (Lex.getKind() != lltok::ChecksumKind)
3803     return TokError(
3804         "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3805 
3806   DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3807 
3808   Result.assign(CSKind);
3809   Lex.Lex();
3810   return false;
3811 }
3812 
3813 } // end namespace llvm
3814 
3815 template <class ParserTy>
3816 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3817   do {
3818     if (Lex.getKind() != lltok::LabelStr)
3819       return TokError("expected field label here");
3820 
3821     if (parseField())
3822       return true;
3823   } while (EatIfPresent(lltok::comma));
3824 
3825   return false;
3826 }
3827 
3828 template <class ParserTy>
3829 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3830   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3831   Lex.Lex();
3832 
3833   if (ParseToken(lltok::lparen, "expected '(' here"))
3834     return true;
3835   if (Lex.getKind() != lltok::rparen)
3836     if (ParseMDFieldsImplBody(parseField))
3837       return true;
3838 
3839   ClosingLoc = Lex.getLoc();
3840   return ParseToken(lltok::rparen, "expected ')' here");
3841 }
3842 
3843 template <class FieldTy>
3844 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3845   if (Result.Seen)
3846     return TokError("field '" + Name + "' cannot be specified more than once");
3847 
3848   LocTy Loc = Lex.getLoc();
3849   Lex.Lex();
3850   return ParseMDField(Loc, Name, Result);
3851 }
3852 
3853 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3854   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3855 
3856 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
3857   if (Lex.getStrVal() == #CLASS)                                               \
3858     return Parse##CLASS(N, IsDistinct);
3859 #include "llvm/IR/Metadata.def"
3860 
3861   return TokError("expected metadata type");
3862 }
3863 
3864 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3865 #define NOP_FIELD(NAME, TYPE, INIT)
3866 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
3867   if (!NAME.Seen)                                                              \
3868     return Error(ClosingLoc, "missing required field '" #NAME "'");
3869 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
3870   if (Lex.getStrVal() == #NAME)                                                \
3871     return ParseMDField(#NAME, NAME);
3872 #define PARSE_MD_FIELDS()                                                      \
3873   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
3874   do {                                                                         \
3875     LocTy ClosingLoc;                                                          \
3876     if (ParseMDFieldsImpl([&]() -> bool {                                      \
3877       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
3878       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
3879     }, ClosingLoc))                                                            \
3880       return true;                                                             \
3881     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
3882   } while (false)
3883 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
3884   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3885 
3886 /// ParseDILocationFields:
3887 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3888 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3889 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3890   OPTIONAL(line, LineField, );                                                 \
3891   OPTIONAL(column, ColumnField, );                                             \
3892   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3893   OPTIONAL(inlinedAt, MDField, );
3894   PARSE_MD_FIELDS();
3895 #undef VISIT_MD_FIELDS
3896 
3897   Result = GET_OR_DISTINCT(
3898       DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3899   return false;
3900 }
3901 
3902 /// ParseGenericDINode:
3903 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3904 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3905 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3906   REQUIRED(tag, DwarfTagField, );                                              \
3907   OPTIONAL(header, MDStringField, );                                           \
3908   OPTIONAL(operands, MDFieldList, );
3909   PARSE_MD_FIELDS();
3910 #undef VISIT_MD_FIELDS
3911 
3912   Result = GET_OR_DISTINCT(GenericDINode,
3913                            (Context, tag.Val, header.Val, operands.Val));
3914   return false;
3915 }
3916 
3917 /// ParseDISubrange:
3918 ///   ::= !DISubrange(count: 30, lowerBound: 2)
3919 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3920 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3921   REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX));                         \
3922   OPTIONAL(lowerBound, MDSignedField, );
3923   PARSE_MD_FIELDS();
3924 #undef VISIT_MD_FIELDS
3925 
3926   Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3927   return false;
3928 }
3929 
3930 /// ParseDIEnumerator:
3931 ///   ::= !DIEnumerator(value: 30, name: "SomeKind")
3932 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3933 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3934   REQUIRED(name, MDStringField, );                                             \
3935   REQUIRED(value, MDSignedField, );
3936   PARSE_MD_FIELDS();
3937 #undef VISIT_MD_FIELDS
3938 
3939   Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3940   return false;
3941 }
3942 
3943 /// ParseDIBasicType:
3944 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3945 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3946 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3947   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
3948   OPTIONAL(name, MDStringField, );                                             \
3949   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3950   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
3951   OPTIONAL(encoding, DwarfAttEncodingField, );
3952   PARSE_MD_FIELDS();
3953 #undef VISIT_MD_FIELDS
3954 
3955   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3956                                          align.Val, encoding.Val));
3957   return false;
3958 }
3959 
3960 /// ParseDIDerivedType:
3961 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3962 ///                      line: 7, scope: !1, baseType: !2, size: 32,
3963 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
3964 ///                      dwarfAddressSpace: 3)
3965 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3966 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3967   REQUIRED(tag, DwarfTagField, );                                              \
3968   OPTIONAL(name, MDStringField, );                                             \
3969   OPTIONAL(file, MDField, );                                                   \
3970   OPTIONAL(line, LineField, );                                                 \
3971   OPTIONAL(scope, MDField, );                                                  \
3972   REQUIRED(baseType, MDField, );                                               \
3973   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3974   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
3975   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3976   OPTIONAL(flags, DIFlagField, );                                              \
3977   OPTIONAL(extraData, MDField, );                                              \
3978   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
3979   PARSE_MD_FIELDS();
3980 #undef VISIT_MD_FIELDS
3981 
3982   Optional<unsigned> DWARFAddressSpace;
3983   if (dwarfAddressSpace.Val != UINT32_MAX)
3984     DWARFAddressSpace = dwarfAddressSpace.Val;
3985 
3986   Result = GET_OR_DISTINCT(DIDerivedType,
3987                            (Context, tag.Val, name.Val, file.Val, line.Val,
3988                             scope.Val, baseType.Val, size.Val, align.Val,
3989                             offset.Val, DWARFAddressSpace, flags.Val,
3990                             extraData.Val));
3991   return false;
3992 }
3993 
3994 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3995 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3996   REQUIRED(tag, DwarfTagField, );                                              \
3997   OPTIONAL(name, MDStringField, );                                             \
3998   OPTIONAL(file, MDField, );                                                   \
3999   OPTIONAL(line, LineField, );                                                 \
4000   OPTIONAL(scope, MDField, );                                                  \
4001   OPTIONAL(baseType, MDField, );                                               \
4002   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4003   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4004   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4005   OPTIONAL(flags, DIFlagField, );                                              \
4006   OPTIONAL(elements, MDField, );                                               \
4007   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
4008   OPTIONAL(vtableHolder, MDField, );                                           \
4009   OPTIONAL(templateParams, MDField, );                                         \
4010   OPTIONAL(identifier, MDStringField, );
4011   PARSE_MD_FIELDS();
4012 #undef VISIT_MD_FIELDS
4013 
4014   // If this has an identifier try to build an ODR type.
4015   if (identifier.Val)
4016     if (auto *CT = DICompositeType::buildODRType(
4017             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4018             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4019             elements.Val, runtimeLang.Val, vtableHolder.Val,
4020             templateParams.Val)) {
4021       Result = CT;
4022       return false;
4023     }
4024 
4025   // Create a new node, and save it in the context if it belongs in the type
4026   // map.
4027   Result = GET_OR_DISTINCT(
4028       DICompositeType,
4029       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4030        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4031        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4032   return false;
4033 }
4034 
4035 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4036 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4037   OPTIONAL(flags, DIFlagField, );                                              \
4038   OPTIONAL(cc, DwarfCCField, );                                                \
4039   REQUIRED(types, MDField, );
4040   PARSE_MD_FIELDS();
4041 #undef VISIT_MD_FIELDS
4042 
4043   Result = GET_OR_DISTINCT(DISubroutineType,
4044                            (Context, flags.Val, cc.Val, types.Val));
4045   return false;
4046 }
4047 
4048 /// ParseDIFileType:
4049 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4050 ///                   checksumkind: CSK_MD5,
4051 ///                   checksum: "000102030405060708090a0b0c0d0e0f")
4052 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4053 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4054   REQUIRED(filename, MDStringField, );                                         \
4055   REQUIRED(directory, MDStringField, );                                        \
4056   OPTIONAL(checksumkind, ChecksumKindField, );                                 \
4057   OPTIONAL(checksum, MDStringField, );
4058   PARSE_MD_FIELDS();
4059 #undef VISIT_MD_FIELDS
4060 
4061   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4062                                     checksumkind.Val, checksum.Val));
4063   return false;
4064 }
4065 
4066 /// ParseDICompileUnit:
4067 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4068 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
4069 ///                      splitDebugFilename: "abc.debug",
4070 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4071 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4072 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4073   if (!IsDistinct)
4074     return Lex.Error("missing 'distinct', required for !DICompileUnit");
4075 
4076 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4077   REQUIRED(language, DwarfLangField, );                                        \
4078   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
4079   OPTIONAL(producer, MDStringField, );                                         \
4080   OPTIONAL(isOptimized, MDBoolField, );                                        \
4081   OPTIONAL(flags, MDStringField, );                                            \
4082   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
4083   OPTIONAL(splitDebugFilename, MDStringField, );                               \
4084   OPTIONAL(emissionKind, EmissionKindField, );                                 \
4085   OPTIONAL(enums, MDField, );                                                  \
4086   OPTIONAL(retainedTypes, MDField, );                                          \
4087   OPTIONAL(globals, MDField, );                                                \
4088   OPTIONAL(imports, MDField, );                                                \
4089   OPTIONAL(macros, MDField, );                                                 \
4090   OPTIONAL(dwoId, MDUnsignedField, );                                          \
4091   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
4092   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
4093   PARSE_MD_FIELDS();
4094 #undef VISIT_MD_FIELDS
4095 
4096   Result = DICompileUnit::getDistinct(
4097       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4098       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4099       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4100       splitDebugInlining.Val, debugInfoForProfiling.Val);
4101   return false;
4102 }
4103 
4104 /// ParseDISubprogram:
4105 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4106 ///                     file: !1, line: 7, type: !2, isLocal: false,
4107 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
4108 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
4109 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
4110 ///                     isOptimized: false, templateParams: !4, declaration: !5,
4111 ///                     variables: !6, thrownTypes: !7)
4112 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4113   auto Loc = Lex.getLoc();
4114 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4115   OPTIONAL(scope, MDField, );                                                  \
4116   OPTIONAL(name, MDStringField, );                                             \
4117   OPTIONAL(linkageName, MDStringField, );                                      \
4118   OPTIONAL(file, MDField, );                                                   \
4119   OPTIONAL(line, LineField, );                                                 \
4120   OPTIONAL(type, MDField, );                                                   \
4121   OPTIONAL(isLocal, MDBoolField, );                                            \
4122   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4123   OPTIONAL(scopeLine, LineField, );                                            \
4124   OPTIONAL(containingType, MDField, );                                         \
4125   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
4126   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
4127   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
4128   OPTIONAL(flags, DIFlagField, );                                              \
4129   OPTIONAL(isOptimized, MDBoolField, );                                        \
4130   OPTIONAL(unit, MDField, );                                                   \
4131   OPTIONAL(templateParams, MDField, );                                         \
4132   OPTIONAL(declaration, MDField, );                                            \
4133   OPTIONAL(variables, MDField, );                                              \
4134   OPTIONAL(thrownTypes, MDField, );
4135   PARSE_MD_FIELDS();
4136 #undef VISIT_MD_FIELDS
4137 
4138   if (isDefinition.Val && !IsDistinct)
4139     return Lex.Error(
4140         Loc,
4141         "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4142 
4143   Result = GET_OR_DISTINCT(
4144       DISubprogram,
4145       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4146        type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4147        containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4148        flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4149        declaration.Val, variables.Val, thrownTypes.Val));
4150   return false;
4151 }
4152 
4153 /// ParseDILexicalBlock:
4154 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4155 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4156 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4157   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4158   OPTIONAL(file, MDField, );                                                   \
4159   OPTIONAL(line, LineField, );                                                 \
4160   OPTIONAL(column, ColumnField, );
4161   PARSE_MD_FIELDS();
4162 #undef VISIT_MD_FIELDS
4163 
4164   Result = GET_OR_DISTINCT(
4165       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4166   return false;
4167 }
4168 
4169 /// ParseDILexicalBlockFile:
4170 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4171 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4172 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4173   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4174   OPTIONAL(file, MDField, );                                                   \
4175   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4176   PARSE_MD_FIELDS();
4177 #undef VISIT_MD_FIELDS
4178 
4179   Result = GET_OR_DISTINCT(DILexicalBlockFile,
4180                            (Context, scope.Val, file.Val, discriminator.Val));
4181   return false;
4182 }
4183 
4184 /// ParseDINamespace:
4185 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4186 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4187 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4188   REQUIRED(scope, MDField, );                                                  \
4189   OPTIONAL(name, MDStringField, );                                             \
4190   OPTIONAL(exportSymbols, MDBoolField, );
4191   PARSE_MD_FIELDS();
4192 #undef VISIT_MD_FIELDS
4193 
4194   Result = GET_OR_DISTINCT(DINamespace,
4195                            (Context, scope.Val, name.Val, exportSymbols.Val));
4196   return false;
4197 }
4198 
4199 /// ParseDIMacro:
4200 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4201 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4202 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4203   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
4204   OPTIONAL(line, LineField, );                                                 \
4205   REQUIRED(name, MDStringField, );                                             \
4206   OPTIONAL(value, MDStringField, );
4207   PARSE_MD_FIELDS();
4208 #undef VISIT_MD_FIELDS
4209 
4210   Result = GET_OR_DISTINCT(DIMacro,
4211                            (Context, type.Val, line.Val, name.Val, value.Val));
4212   return false;
4213 }
4214 
4215 /// ParseDIMacroFile:
4216 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4217 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4218 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4219   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
4220   OPTIONAL(line, LineField, );                                                 \
4221   REQUIRED(file, MDField, );                                                   \
4222   OPTIONAL(nodes, MDField, );
4223   PARSE_MD_FIELDS();
4224 #undef VISIT_MD_FIELDS
4225 
4226   Result = GET_OR_DISTINCT(DIMacroFile,
4227                            (Context, type.Val, line.Val, file.Val, nodes.Val));
4228   return false;
4229 }
4230 
4231 /// ParseDIModule:
4232 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4233 ///                 includePath: "/usr/include", isysroot: "/")
4234 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4235 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4236   REQUIRED(scope, MDField, );                                                  \
4237   REQUIRED(name, MDStringField, );                                             \
4238   OPTIONAL(configMacros, MDStringField, );                                     \
4239   OPTIONAL(includePath, MDStringField, );                                      \
4240   OPTIONAL(isysroot, MDStringField, );
4241   PARSE_MD_FIELDS();
4242 #undef VISIT_MD_FIELDS
4243 
4244   Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4245                            configMacros.Val, includePath.Val, isysroot.Val));
4246   return false;
4247 }
4248 
4249 /// ParseDITemplateTypeParameter:
4250 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4251 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4252 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4253   OPTIONAL(name, MDStringField, );                                             \
4254   REQUIRED(type, MDField, );
4255   PARSE_MD_FIELDS();
4256 #undef VISIT_MD_FIELDS
4257 
4258   Result =
4259       GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4260   return false;
4261 }
4262 
4263 /// ParseDITemplateValueParameter:
4264 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4265 ///                                 name: "V", type: !1, value: i32 7)
4266 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4267 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4268   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
4269   OPTIONAL(name, MDStringField, );                                             \
4270   OPTIONAL(type, MDField, );                                                   \
4271   REQUIRED(value, MDField, );
4272   PARSE_MD_FIELDS();
4273 #undef VISIT_MD_FIELDS
4274 
4275   Result = GET_OR_DISTINCT(DITemplateValueParameter,
4276                            (Context, tag.Val, name.Val, type.Val, value.Val));
4277   return false;
4278 }
4279 
4280 /// ParseDIGlobalVariable:
4281 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4282 ///                         file: !1, line: 7, type: !2, isLocal: false,
4283 ///                         isDefinition: true, declaration: !3, align: 8)
4284 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4285 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4286   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
4287   OPTIONAL(scope, MDField, );                                                  \
4288   OPTIONAL(linkageName, MDStringField, );                                      \
4289   OPTIONAL(file, MDField, );                                                   \
4290   OPTIONAL(line, LineField, );                                                 \
4291   OPTIONAL(type, MDField, );                                                   \
4292   OPTIONAL(isLocal, MDBoolField, );                                            \
4293   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4294   OPTIONAL(declaration, MDField, );                                            \
4295   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4296   PARSE_MD_FIELDS();
4297 #undef VISIT_MD_FIELDS
4298 
4299   Result = GET_OR_DISTINCT(DIGlobalVariable,
4300                            (Context, scope.Val, name.Val, linkageName.Val,
4301                             file.Val, line.Val, type.Val, isLocal.Val,
4302                             isDefinition.Val, declaration.Val, align.Val));
4303   return false;
4304 }
4305 
4306 /// ParseDILocalVariable:
4307 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4308 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
4309 ///                        align: 8)
4310 ///   ::= !DILocalVariable(scope: !0, name: "foo",
4311 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
4312 ///                        align: 8)
4313 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4314 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4315   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4316   OPTIONAL(name, MDStringField, );                                             \
4317   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
4318   OPTIONAL(file, MDField, );                                                   \
4319   OPTIONAL(line, LineField, );                                                 \
4320   OPTIONAL(type, MDField, );                                                   \
4321   OPTIONAL(flags, DIFlagField, );                                              \
4322   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4323   PARSE_MD_FIELDS();
4324 #undef VISIT_MD_FIELDS
4325 
4326   Result = GET_OR_DISTINCT(DILocalVariable,
4327                            (Context, scope.Val, name.Val, file.Val, line.Val,
4328                             type.Val, arg.Val, flags.Val, align.Val));
4329   return false;
4330 }
4331 
4332 /// ParseDIExpression:
4333 ///   ::= !DIExpression(0, 7, -1)
4334 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4335   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4336   Lex.Lex();
4337 
4338   if (ParseToken(lltok::lparen, "expected '(' here"))
4339     return true;
4340 
4341   SmallVector<uint64_t, 8> Elements;
4342   if (Lex.getKind() != lltok::rparen)
4343     do {
4344       if (Lex.getKind() == lltok::DwarfOp) {
4345         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4346           Lex.Lex();
4347           Elements.push_back(Op);
4348           continue;
4349         }
4350         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4351       }
4352 
4353       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4354         return TokError("expected unsigned integer");
4355 
4356       auto &U = Lex.getAPSIntVal();
4357       if (U.ugt(UINT64_MAX))
4358         return TokError("element too large, limit is " + Twine(UINT64_MAX));
4359       Elements.push_back(U.getZExtValue());
4360       Lex.Lex();
4361     } while (EatIfPresent(lltok::comma));
4362 
4363   if (ParseToken(lltok::rparen, "expected ')' here"))
4364     return true;
4365 
4366   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4367   return false;
4368 }
4369 
4370 /// ParseDIGlobalVariableExpression:
4371 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4372 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4373                                                bool IsDistinct) {
4374 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4375   REQUIRED(var, MDField, );                                                    \
4376   OPTIONAL(expr, MDField, );
4377   PARSE_MD_FIELDS();
4378 #undef VISIT_MD_FIELDS
4379 
4380   Result =
4381       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4382   return false;
4383 }
4384 
4385 /// ParseDIObjCProperty:
4386 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4387 ///                       getter: "getFoo", attributes: 7, type: !2)
4388 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4389 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4390   OPTIONAL(name, MDStringField, );                                             \
4391   OPTIONAL(file, MDField, );                                                   \
4392   OPTIONAL(line, LineField, );                                                 \
4393   OPTIONAL(setter, MDStringField, );                                           \
4394   OPTIONAL(getter, MDStringField, );                                           \
4395   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
4396   OPTIONAL(type, MDField, );
4397   PARSE_MD_FIELDS();
4398 #undef VISIT_MD_FIELDS
4399 
4400   Result = GET_OR_DISTINCT(DIObjCProperty,
4401                            (Context, name.Val, file.Val, line.Val, setter.Val,
4402                             getter.Val, attributes.Val, type.Val));
4403   return false;
4404 }
4405 
4406 /// ParseDIImportedEntity:
4407 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4408 ///                         line: 7, name: "foo")
4409 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4410 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4411   REQUIRED(tag, DwarfTagField, );                                              \
4412   REQUIRED(scope, MDField, );                                                  \
4413   OPTIONAL(entity, MDField, );                                                 \
4414   OPTIONAL(line, LineField, );                                                 \
4415   OPTIONAL(name, MDStringField, );
4416   PARSE_MD_FIELDS();
4417 #undef VISIT_MD_FIELDS
4418 
4419   Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4420                                               entity.Val, line.Val, name.Val));
4421   return false;
4422 }
4423 
4424 #undef PARSE_MD_FIELD
4425 #undef NOP_FIELD
4426 #undef REQUIRE_FIELD
4427 #undef DECLARE_FIELD
4428 
4429 /// ParseMetadataAsValue
4430 ///  ::= metadata i32 %local
4431 ///  ::= metadata i32 @global
4432 ///  ::= metadata i32 7
4433 ///  ::= metadata !0
4434 ///  ::= metadata !{...}
4435 ///  ::= metadata !"string"
4436 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4437   // Note: the type 'metadata' has already been parsed.
4438   Metadata *MD;
4439   if (ParseMetadata(MD, &PFS))
4440     return true;
4441 
4442   V = MetadataAsValue::get(Context, MD);
4443   return false;
4444 }
4445 
4446 /// ParseValueAsMetadata
4447 ///  ::= i32 %local
4448 ///  ::= i32 @global
4449 ///  ::= i32 7
4450 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4451                                     PerFunctionState *PFS) {
4452   Type *Ty;
4453   LocTy Loc;
4454   if (ParseType(Ty, TypeMsg, Loc))
4455     return true;
4456   if (Ty->isMetadataTy())
4457     return Error(Loc, "invalid metadata-value-metadata roundtrip");
4458 
4459   Value *V;
4460   if (ParseValue(Ty, V, PFS))
4461     return true;
4462 
4463   MD = ValueAsMetadata::get(V);
4464   return false;
4465 }
4466 
4467 /// ParseMetadata
4468 ///  ::= i32 %local
4469 ///  ::= i32 @global
4470 ///  ::= i32 7
4471 ///  ::= !42
4472 ///  ::= !{...}
4473 ///  ::= !"string"
4474 ///  ::= !DILocation(...)
4475 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4476   if (Lex.getKind() == lltok::MetadataVar) {
4477     MDNode *N;
4478     if (ParseSpecializedMDNode(N))
4479       return true;
4480     MD = N;
4481     return false;
4482   }
4483 
4484   // ValueAsMetadata:
4485   // <type> <value>
4486   if (Lex.getKind() != lltok::exclaim)
4487     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4488 
4489   // '!'.
4490   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4491   Lex.Lex();
4492 
4493   // MDString:
4494   //   ::= '!' STRINGCONSTANT
4495   if (Lex.getKind() == lltok::StringConstant) {
4496     MDString *S;
4497     if (ParseMDString(S))
4498       return true;
4499     MD = S;
4500     return false;
4501   }
4502 
4503   // MDNode:
4504   // !{ ... }
4505   // !7
4506   MDNode *N;
4507   if (ParseMDNodeTail(N))
4508     return true;
4509   MD = N;
4510   return false;
4511 }
4512 
4513 //===----------------------------------------------------------------------===//
4514 // Function Parsing.
4515 //===----------------------------------------------------------------------===//
4516 
4517 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4518                                    PerFunctionState *PFS) {
4519   if (Ty->isFunctionTy())
4520     return Error(ID.Loc, "functions are not values, refer to them as pointers");
4521 
4522   switch (ID.Kind) {
4523   case ValID::t_LocalID:
4524     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4525     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4526     return V == nullptr;
4527   case ValID::t_LocalName:
4528     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4529     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4530     return V == nullptr;
4531   case ValID::t_InlineAsm: {
4532     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4533       return Error(ID.Loc, "invalid type for inline asm constraint string");
4534     V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4535                        (ID.UIntVal >> 1) & 1,
4536                        (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4537     return false;
4538   }
4539   case ValID::t_GlobalName:
4540     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4541     return V == nullptr;
4542   case ValID::t_GlobalID:
4543     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4544     return V == nullptr;
4545   case ValID::t_APSInt:
4546     if (!Ty->isIntegerTy())
4547       return Error(ID.Loc, "integer constant must have integer type");
4548     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4549     V = ConstantInt::get(Context, ID.APSIntVal);
4550     return false;
4551   case ValID::t_APFloat:
4552     if (!Ty->isFloatingPointTy() ||
4553         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4554       return Error(ID.Loc, "floating point constant invalid for type");
4555 
4556     // The lexer has no type info, so builds all half, float, and double FP
4557     // constants as double.  Fix this here.  Long double does not need this.
4558     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
4559       bool Ignored;
4560       if (Ty->isHalfTy())
4561         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
4562                               &Ignored);
4563       else if (Ty->isFloatTy())
4564         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
4565                               &Ignored);
4566     }
4567     V = ConstantFP::get(Context, ID.APFloatVal);
4568 
4569     if (V->getType() != Ty)
4570       return Error(ID.Loc, "floating point constant does not have type '" +
4571                    getTypeString(Ty) + "'");
4572 
4573     return false;
4574   case ValID::t_Null:
4575     if (!Ty->isPointerTy())
4576       return Error(ID.Loc, "null must be a pointer type");
4577     V = ConstantPointerNull::get(cast<PointerType>(Ty));
4578     return false;
4579   case ValID::t_Undef:
4580     // FIXME: LabelTy should not be a first-class type.
4581     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4582       return Error(ID.Loc, "invalid type for undef constant");
4583     V = UndefValue::get(Ty);
4584     return false;
4585   case ValID::t_EmptyArray:
4586     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4587       return Error(ID.Loc, "invalid empty array initializer");
4588     V = UndefValue::get(Ty);
4589     return false;
4590   case ValID::t_Zero:
4591     // FIXME: LabelTy should not be a first-class type.
4592     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4593       return Error(ID.Loc, "invalid type for null constant");
4594     V = Constant::getNullValue(Ty);
4595     return false;
4596   case ValID::t_None:
4597     if (!Ty->isTokenTy())
4598       return Error(ID.Loc, "invalid type for none constant");
4599     V = Constant::getNullValue(Ty);
4600     return false;
4601   case ValID::t_Constant:
4602     if (ID.ConstantVal->getType() != Ty)
4603       return Error(ID.Loc, "constant expression type mismatch");
4604 
4605     V = ID.ConstantVal;
4606     return false;
4607   case ValID::t_ConstantStruct:
4608   case ValID::t_PackedConstantStruct:
4609     if (StructType *ST = dyn_cast<StructType>(Ty)) {
4610       if (ST->getNumElements() != ID.UIntVal)
4611         return Error(ID.Loc,
4612                      "initializer with struct type has wrong # elements");
4613       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4614         return Error(ID.Loc, "packed'ness of initializer and type don't match");
4615 
4616       // Verify that the elements are compatible with the structtype.
4617       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4618         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4619           return Error(ID.Loc, "element " + Twine(i) +
4620                     " of struct initializer doesn't match struct element type");
4621 
4622       V = ConstantStruct::get(
4623           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4624     } else
4625       return Error(ID.Loc, "constant expression type mismatch");
4626     return false;
4627   }
4628   llvm_unreachable("Invalid ValID");
4629 }
4630 
4631 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4632   C = nullptr;
4633   ValID ID;
4634   auto Loc = Lex.getLoc();
4635   if (ParseValID(ID, /*PFS=*/nullptr))
4636     return true;
4637   switch (ID.Kind) {
4638   case ValID::t_APSInt:
4639   case ValID::t_APFloat:
4640   case ValID::t_Undef:
4641   case ValID::t_Constant:
4642   case ValID::t_ConstantStruct:
4643   case ValID::t_PackedConstantStruct: {
4644     Value *V;
4645     if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4646       return true;
4647     assert(isa<Constant>(V) && "Expected a constant value");
4648     C = cast<Constant>(V);
4649     return false;
4650   }
4651   case ValID::t_Null:
4652     C = Constant::getNullValue(Ty);
4653     return false;
4654   default:
4655     return Error(Loc, "expected a constant value");
4656   }
4657 }
4658 
4659 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4660   V = nullptr;
4661   ValID ID;
4662   return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4663 }
4664 
4665 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4666   Type *Ty = nullptr;
4667   return ParseType(Ty) ||
4668          ParseValue(Ty, V, PFS);
4669 }
4670 
4671 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4672                                       PerFunctionState &PFS) {
4673   Value *V;
4674   Loc = Lex.getLoc();
4675   if (ParseTypeAndValue(V, PFS)) return true;
4676   if (!isa<BasicBlock>(V))
4677     return Error(Loc, "expected a basic block");
4678   BB = cast<BasicBlock>(V);
4679   return false;
4680 }
4681 
4682 /// FunctionHeader
4683 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4684 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4685 ///       OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4686 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4687   // Parse the linkage.
4688   LocTy LinkageLoc = Lex.getLoc();
4689   unsigned Linkage;
4690 
4691   unsigned Visibility;
4692   unsigned DLLStorageClass;
4693   AttrBuilder RetAttrs;
4694   unsigned CC;
4695   bool HasLinkage;
4696   Type *RetType = nullptr;
4697   LocTy RetTypeLoc = Lex.getLoc();
4698   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4699       ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4700       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4701     return true;
4702 
4703   // Verify that the linkage is ok.
4704   switch ((GlobalValue::LinkageTypes)Linkage) {
4705   case GlobalValue::ExternalLinkage:
4706     break; // always ok.
4707   case GlobalValue::ExternalWeakLinkage:
4708     if (isDefine)
4709       return Error(LinkageLoc, "invalid linkage for function definition");
4710     break;
4711   case GlobalValue::PrivateLinkage:
4712   case GlobalValue::InternalLinkage:
4713   case GlobalValue::AvailableExternallyLinkage:
4714   case GlobalValue::LinkOnceAnyLinkage:
4715   case GlobalValue::LinkOnceODRLinkage:
4716   case GlobalValue::WeakAnyLinkage:
4717   case GlobalValue::WeakODRLinkage:
4718     if (!isDefine)
4719       return Error(LinkageLoc, "invalid linkage for function declaration");
4720     break;
4721   case GlobalValue::AppendingLinkage:
4722   case GlobalValue::CommonLinkage:
4723     return Error(LinkageLoc, "invalid function linkage type");
4724   }
4725 
4726   if (!isValidVisibilityForLinkage(Visibility, Linkage))
4727     return Error(LinkageLoc,
4728                  "symbol with local linkage must have default visibility");
4729 
4730   if (!FunctionType::isValidReturnType(RetType))
4731     return Error(RetTypeLoc, "invalid function return type");
4732 
4733   LocTy NameLoc = Lex.getLoc();
4734 
4735   std::string FunctionName;
4736   if (Lex.getKind() == lltok::GlobalVar) {
4737     FunctionName = Lex.getStrVal();
4738   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
4739     unsigned NameID = Lex.getUIntVal();
4740 
4741     if (NameID != NumberedVals.size())
4742       return TokError("function expected to be numbered '%" +
4743                       Twine(NumberedVals.size()) + "'");
4744   } else {
4745     return TokError("expected function name");
4746   }
4747 
4748   Lex.Lex();
4749 
4750   if (Lex.getKind() != lltok::lparen)
4751     return TokError("expected '(' in function argument list");
4752 
4753   SmallVector<ArgInfo, 8> ArgList;
4754   bool isVarArg;
4755   AttrBuilder FuncAttrs;
4756   std::vector<unsigned> FwdRefAttrGrps;
4757   LocTy BuiltinLoc;
4758   std::string Section;
4759   unsigned Alignment;
4760   std::string GC;
4761   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4762   LocTy UnnamedAddrLoc;
4763   Constant *Prefix = nullptr;
4764   Constant *Prologue = nullptr;
4765   Constant *PersonalityFn = nullptr;
4766   Comdat *C;
4767 
4768   if (ParseArgumentList(ArgList, isVarArg) ||
4769       ParseOptionalUnnamedAddr(UnnamedAddr) ||
4770       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4771                                  BuiltinLoc) ||
4772       (EatIfPresent(lltok::kw_section) &&
4773        ParseStringConstant(Section)) ||
4774       parseOptionalComdat(FunctionName, C) ||
4775       ParseOptionalAlignment(Alignment) ||
4776       (EatIfPresent(lltok::kw_gc) &&
4777        ParseStringConstant(GC)) ||
4778       (EatIfPresent(lltok::kw_prefix) &&
4779        ParseGlobalTypeAndValue(Prefix)) ||
4780       (EatIfPresent(lltok::kw_prologue) &&
4781        ParseGlobalTypeAndValue(Prologue)) ||
4782       (EatIfPresent(lltok::kw_personality) &&
4783        ParseGlobalTypeAndValue(PersonalityFn)))
4784     return true;
4785 
4786   if (FuncAttrs.contains(Attribute::Builtin))
4787     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4788 
4789   // If the alignment was parsed as an attribute, move to the alignment field.
4790   if (FuncAttrs.hasAlignmentAttr()) {
4791     Alignment = FuncAttrs.getAlignment();
4792     FuncAttrs.removeAttribute(Attribute::Alignment);
4793   }
4794 
4795   // Okay, if we got here, the function is syntactically valid.  Convert types
4796   // and do semantic checks.
4797   std::vector<Type*> ParamTypeList;
4798   SmallVector<AttributeSet, 8> Attrs;
4799 
4800   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4801     ParamTypeList.push_back(ArgList[i].Ty);
4802     Attrs.push_back(ArgList[i].Attrs);
4803   }
4804 
4805   AttributeList PAL =
4806       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4807                          AttributeSet::get(Context, RetAttrs), Attrs);
4808 
4809   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4810     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4811 
4812   FunctionType *FT =
4813     FunctionType::get(RetType, ParamTypeList, isVarArg);
4814   PointerType *PFT = PointerType::getUnqual(FT);
4815 
4816   Fn = nullptr;
4817   if (!FunctionName.empty()) {
4818     // If this was a definition of a forward reference, remove the definition
4819     // from the forward reference table and fill in the forward ref.
4820     auto FRVI = ForwardRefVals.find(FunctionName);
4821     if (FRVI != ForwardRefVals.end()) {
4822       Fn = M->getFunction(FunctionName);
4823       if (!Fn)
4824         return Error(FRVI->second.second, "invalid forward reference to "
4825                      "function as global value!");
4826       if (Fn->getType() != PFT)
4827         return Error(FRVI->second.second, "invalid forward reference to "
4828                      "function '" + FunctionName + "' with wrong type!");
4829 
4830       ForwardRefVals.erase(FRVI);
4831     } else if ((Fn = M->getFunction(FunctionName))) {
4832       // Reject redefinitions.
4833       return Error(NameLoc, "invalid redefinition of function '" +
4834                    FunctionName + "'");
4835     } else if (M->getNamedValue(FunctionName)) {
4836       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4837     }
4838 
4839   } else {
4840     // If this is a definition of a forward referenced function, make sure the
4841     // types agree.
4842     auto I = ForwardRefValIDs.find(NumberedVals.size());
4843     if (I != ForwardRefValIDs.end()) {
4844       Fn = cast<Function>(I->second.first);
4845       if (Fn->getType() != PFT)
4846         return Error(NameLoc, "type of definition and forward reference of '@" +
4847                      Twine(NumberedVals.size()) + "' disagree");
4848       ForwardRefValIDs.erase(I);
4849     }
4850   }
4851 
4852   if (!Fn)
4853     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4854   else // Move the forward-reference to the correct spot in the module.
4855     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4856 
4857   if (FunctionName.empty())
4858     NumberedVals.push_back(Fn);
4859 
4860   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4861   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4862   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4863   Fn->setCallingConv(CC);
4864   Fn->setAttributes(PAL);
4865   Fn->setUnnamedAddr(UnnamedAddr);
4866   Fn->setAlignment(Alignment);
4867   Fn->setSection(Section);
4868   Fn->setComdat(C);
4869   Fn->setPersonalityFn(PersonalityFn);
4870   if (!GC.empty()) Fn->setGC(GC);
4871   Fn->setPrefixData(Prefix);
4872   Fn->setPrologueData(Prologue);
4873   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4874 
4875   // Add all of the arguments we parsed to the function.
4876   Function::arg_iterator ArgIt = Fn->arg_begin();
4877   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4878     // If the argument has a name, insert it into the argument symbol table.
4879     if (ArgList[i].Name.empty()) continue;
4880 
4881     // Set the name, if it conflicted, it will be auto-renamed.
4882     ArgIt->setName(ArgList[i].Name);
4883 
4884     if (ArgIt->getName() != ArgList[i].Name)
4885       return Error(ArgList[i].Loc, "redefinition of argument '%" +
4886                    ArgList[i].Name + "'");
4887   }
4888 
4889   if (isDefine)
4890     return false;
4891 
4892   // Check the declaration has no block address forward references.
4893   ValID ID;
4894   if (FunctionName.empty()) {
4895     ID.Kind = ValID::t_GlobalID;
4896     ID.UIntVal = NumberedVals.size() - 1;
4897   } else {
4898     ID.Kind = ValID::t_GlobalName;
4899     ID.StrVal = FunctionName;
4900   }
4901   auto Blocks = ForwardRefBlockAddresses.find(ID);
4902   if (Blocks != ForwardRefBlockAddresses.end())
4903     return Error(Blocks->first.Loc,
4904                  "cannot take blockaddress inside a declaration");
4905   return false;
4906 }
4907 
4908 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4909   ValID ID;
4910   if (FunctionNumber == -1) {
4911     ID.Kind = ValID::t_GlobalName;
4912     ID.StrVal = F.getName();
4913   } else {
4914     ID.Kind = ValID::t_GlobalID;
4915     ID.UIntVal = FunctionNumber;
4916   }
4917 
4918   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4919   if (Blocks == P.ForwardRefBlockAddresses.end())
4920     return false;
4921 
4922   for (const auto &I : Blocks->second) {
4923     const ValID &BBID = I.first;
4924     GlobalValue *GV = I.second;
4925 
4926     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4927            "Expected local id or name");
4928     BasicBlock *BB;
4929     if (BBID.Kind == ValID::t_LocalName)
4930       BB = GetBB(BBID.StrVal, BBID.Loc);
4931     else
4932       BB = GetBB(BBID.UIntVal, BBID.Loc);
4933     if (!BB)
4934       return P.Error(BBID.Loc, "referenced value is not a basic block");
4935 
4936     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4937     GV->eraseFromParent();
4938   }
4939 
4940   P.ForwardRefBlockAddresses.erase(Blocks);
4941   return false;
4942 }
4943 
4944 /// ParseFunctionBody
4945 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
4946 bool LLParser::ParseFunctionBody(Function &Fn) {
4947   if (Lex.getKind() != lltok::lbrace)
4948     return TokError("expected '{' in function body");
4949   Lex.Lex();  // eat the {.
4950 
4951   int FunctionNumber = -1;
4952   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4953 
4954   PerFunctionState PFS(*this, Fn, FunctionNumber);
4955 
4956   // Resolve block addresses and allow basic blocks to be forward-declared
4957   // within this function.
4958   if (PFS.resolveForwardRefBlockAddresses())
4959     return true;
4960   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4961 
4962   // We need at least one basic block.
4963   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4964     return TokError("function body requires at least one basic block");
4965 
4966   while (Lex.getKind() != lltok::rbrace &&
4967          Lex.getKind() != lltok::kw_uselistorder)
4968     if (ParseBasicBlock(PFS)) return true;
4969 
4970   while (Lex.getKind() != lltok::rbrace)
4971     if (ParseUseListOrder(&PFS))
4972       return true;
4973 
4974   // Eat the }.
4975   Lex.Lex();
4976 
4977   // Verify function is ok.
4978   return PFS.FinishFunction();
4979 }
4980 
4981 /// ParseBasicBlock
4982 ///   ::= LabelStr? Instruction*
4983 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4984   // If this basic block starts out with a name, remember it.
4985   std::string Name;
4986   LocTy NameLoc = Lex.getLoc();
4987   if (Lex.getKind() == lltok::LabelStr) {
4988     Name = Lex.getStrVal();
4989     Lex.Lex();
4990   }
4991 
4992   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4993   if (!BB)
4994     return Error(NameLoc,
4995                  "unable to create block named '" + Name + "'");
4996 
4997   std::string NameStr;
4998 
4999   // Parse the instructions in this block until we get a terminator.
5000   Instruction *Inst;
5001   do {
5002     // This instruction may have three possibilities for a name: a) none
5003     // specified, b) name specified "%foo =", c) number specified: "%4 =".
5004     LocTy NameLoc = Lex.getLoc();
5005     int NameID = -1;
5006     NameStr = "";
5007 
5008     if (Lex.getKind() == lltok::LocalVarID) {
5009       NameID = Lex.getUIntVal();
5010       Lex.Lex();
5011       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5012         return true;
5013     } else if (Lex.getKind() == lltok::LocalVar) {
5014       NameStr = Lex.getStrVal();
5015       Lex.Lex();
5016       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5017         return true;
5018     }
5019 
5020     switch (ParseInstruction(Inst, BB, PFS)) {
5021     default: llvm_unreachable("Unknown ParseInstruction result!");
5022     case InstError: return true;
5023     case InstNormal:
5024       BB->getInstList().push_back(Inst);
5025 
5026       // With a normal result, we check to see if the instruction is followed by
5027       // a comma and metadata.
5028       if (EatIfPresent(lltok::comma))
5029         if (ParseInstructionMetadata(*Inst))
5030           return true;
5031       break;
5032     case InstExtraComma:
5033       BB->getInstList().push_back(Inst);
5034 
5035       // If the instruction parser ate an extra comma at the end of it, it
5036       // *must* be followed by metadata.
5037       if (ParseInstructionMetadata(*Inst))
5038         return true;
5039       break;
5040     }
5041 
5042     // Set the name on the instruction.
5043     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5044   } while (!isa<TerminatorInst>(Inst));
5045 
5046   return false;
5047 }
5048 
5049 //===----------------------------------------------------------------------===//
5050 // Instruction Parsing.
5051 //===----------------------------------------------------------------------===//
5052 
5053 /// ParseInstruction - Parse one of the many different instructions.
5054 ///
5055 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5056                                PerFunctionState &PFS) {
5057   lltok::Kind Token = Lex.getKind();
5058   if (Token == lltok::Eof)
5059     return TokError("found end of file when expecting more instructions");
5060   LocTy Loc = Lex.getLoc();
5061   unsigned KeywordVal = Lex.getUIntVal();
5062   Lex.Lex();  // Eat the keyword.
5063 
5064   switch (Token) {
5065   default:                    return Error(Loc, "expected instruction opcode");
5066   // Terminator Instructions.
5067   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5068   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
5069   case lltok::kw_br:          return ParseBr(Inst, PFS);
5070   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
5071   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
5072   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
5073   case lltok::kw_resume:      return ParseResume(Inst, PFS);
5074   case lltok::kw_cleanupret:  return ParseCleanupRet(Inst, PFS);
5075   case lltok::kw_catchret:    return ParseCatchRet(Inst, PFS);
5076   case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5077   case lltok::kw_catchpad:    return ParseCatchPad(Inst, PFS);
5078   case lltok::kw_cleanuppad:  return ParseCleanupPad(Inst, PFS);
5079   // Binary Operators.
5080   case lltok::kw_add:
5081   case lltok::kw_sub:
5082   case lltok::kw_mul:
5083   case lltok::kw_shl: {
5084     bool NUW = EatIfPresent(lltok::kw_nuw);
5085     bool NSW = EatIfPresent(lltok::kw_nsw);
5086     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5087 
5088     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5089 
5090     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5091     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5092     return false;
5093   }
5094   case lltok::kw_fadd:
5095   case lltok::kw_fsub:
5096   case lltok::kw_fmul:
5097   case lltok::kw_fdiv:
5098   case lltok::kw_frem: {
5099     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5100     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5101     if (Res != 0)
5102       return Res;
5103     if (FMF.any())
5104       Inst->setFastMathFlags(FMF);
5105     return 0;
5106   }
5107 
5108   case lltok::kw_sdiv:
5109   case lltok::kw_udiv:
5110   case lltok::kw_lshr:
5111   case lltok::kw_ashr: {
5112     bool Exact = EatIfPresent(lltok::kw_exact);
5113 
5114     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5115     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5116     return false;
5117   }
5118 
5119   case lltok::kw_urem:
5120   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5121   case lltok::kw_and:
5122   case lltok::kw_or:
5123   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
5124   case lltok::kw_icmp:   return ParseCompare(Inst, PFS, KeywordVal);
5125   case lltok::kw_fcmp: {
5126     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5127     int Res = ParseCompare(Inst, PFS, KeywordVal);
5128     if (Res != 0)
5129       return Res;
5130     if (FMF.any())
5131       Inst->setFastMathFlags(FMF);
5132     return 0;
5133   }
5134 
5135   // Casts.
5136   case lltok::kw_trunc:
5137   case lltok::kw_zext:
5138   case lltok::kw_sext:
5139   case lltok::kw_fptrunc:
5140   case lltok::kw_fpext:
5141   case lltok::kw_bitcast:
5142   case lltok::kw_addrspacecast:
5143   case lltok::kw_uitofp:
5144   case lltok::kw_sitofp:
5145   case lltok::kw_fptoui:
5146   case lltok::kw_fptosi:
5147   case lltok::kw_inttoptr:
5148   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
5149   // Other.
5150   case lltok::kw_select:         return ParseSelect(Inst, PFS);
5151   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
5152   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5153   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
5154   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
5155   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
5156   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
5157   // Call.
5158   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
5159   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5160   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5161   case lltok::kw_notail:   return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5162   // Memory.
5163   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
5164   case lltok::kw_load:           return ParseLoad(Inst, PFS);
5165   case lltok::kw_store:          return ParseStore(Inst, PFS);
5166   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
5167   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
5168   case lltok::kw_fence:          return ParseFence(Inst, PFS);
5169   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5170   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
5171   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
5172   }
5173 }
5174 
5175 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5176 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5177   if (Opc == Instruction::FCmp) {
5178     switch (Lex.getKind()) {
5179     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5180     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5181     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5182     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5183     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5184     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5185     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5186     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5187     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5188     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5189     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5190     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5191     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5192     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5193     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5194     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5195     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5196     }
5197   } else {
5198     switch (Lex.getKind()) {
5199     default: return TokError("expected icmp predicate (e.g. 'eq')");
5200     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
5201     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
5202     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5203     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5204     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5205     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5206     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5207     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5208     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5209     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5210     }
5211   }
5212   Lex.Lex();
5213   return false;
5214 }
5215 
5216 //===----------------------------------------------------------------------===//
5217 // Terminator Instructions.
5218 //===----------------------------------------------------------------------===//
5219 
5220 /// ParseRet - Parse a return instruction.
5221 ///   ::= 'ret' void (',' !dbg, !1)*
5222 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
5223 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5224                         PerFunctionState &PFS) {
5225   SMLoc TypeLoc = Lex.getLoc();
5226   Type *Ty = nullptr;
5227   if (ParseType(Ty, true /*void allowed*/)) return true;
5228 
5229   Type *ResType = PFS.getFunction().getReturnType();
5230 
5231   if (Ty->isVoidTy()) {
5232     if (!ResType->isVoidTy())
5233       return Error(TypeLoc, "value doesn't match function result type '" +
5234                    getTypeString(ResType) + "'");
5235 
5236     Inst = ReturnInst::Create(Context);
5237     return false;
5238   }
5239 
5240   Value *RV;
5241   if (ParseValue(Ty, RV, PFS)) return true;
5242 
5243   if (ResType != RV->getType())
5244     return Error(TypeLoc, "value doesn't match function result type '" +
5245                  getTypeString(ResType) + "'");
5246 
5247   Inst = ReturnInst::Create(Context, RV);
5248   return false;
5249 }
5250 
5251 /// ParseBr
5252 ///   ::= 'br' TypeAndValue
5253 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5254 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5255   LocTy Loc, Loc2;
5256   Value *Op0;
5257   BasicBlock *Op1, *Op2;
5258   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5259 
5260   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5261     Inst = BranchInst::Create(BB);
5262     return false;
5263   }
5264 
5265   if (Op0->getType() != Type::getInt1Ty(Context))
5266     return Error(Loc, "branch condition must have 'i1' type");
5267 
5268   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5269       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5270       ParseToken(lltok::comma, "expected ',' after true destination") ||
5271       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5272     return true;
5273 
5274   Inst = BranchInst::Create(Op1, Op2, Op0);
5275   return false;
5276 }
5277 
5278 /// ParseSwitch
5279 ///  Instruction
5280 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5281 ///  JumpTable
5282 ///    ::= (TypeAndValue ',' TypeAndValue)*
5283 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5284   LocTy CondLoc, BBLoc;
5285   Value *Cond;
5286   BasicBlock *DefaultBB;
5287   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5288       ParseToken(lltok::comma, "expected ',' after switch condition") ||
5289       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5290       ParseToken(lltok::lsquare, "expected '[' with switch table"))
5291     return true;
5292 
5293   if (!Cond->getType()->isIntegerTy())
5294     return Error(CondLoc, "switch condition must have integer type");
5295 
5296   // Parse the jump table pairs.
5297   SmallPtrSet<Value*, 32> SeenCases;
5298   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5299   while (Lex.getKind() != lltok::rsquare) {
5300     Value *Constant;
5301     BasicBlock *DestBB;
5302 
5303     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5304         ParseToken(lltok::comma, "expected ',' after case value") ||
5305         ParseTypeAndBasicBlock(DestBB, PFS))
5306       return true;
5307 
5308     if (!SeenCases.insert(Constant).second)
5309       return Error(CondLoc, "duplicate case value in switch");
5310     if (!isa<ConstantInt>(Constant))
5311       return Error(CondLoc, "case value is not a constant integer");
5312 
5313     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5314   }
5315 
5316   Lex.Lex();  // Eat the ']'.
5317 
5318   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5319   for (unsigned i = 0, e = Table.size(); i != e; ++i)
5320     SI->addCase(Table[i].first, Table[i].second);
5321   Inst = SI;
5322   return false;
5323 }
5324 
5325 /// ParseIndirectBr
5326 ///  Instruction
5327 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5328 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5329   LocTy AddrLoc;
5330   Value *Address;
5331   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5332       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5333       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5334     return true;
5335 
5336   if (!Address->getType()->isPointerTy())
5337     return Error(AddrLoc, "indirectbr address must have pointer type");
5338 
5339   // Parse the destination list.
5340   SmallVector<BasicBlock*, 16> DestList;
5341 
5342   if (Lex.getKind() != lltok::rsquare) {
5343     BasicBlock *DestBB;
5344     if (ParseTypeAndBasicBlock(DestBB, PFS))
5345       return true;
5346     DestList.push_back(DestBB);
5347 
5348     while (EatIfPresent(lltok::comma)) {
5349       if (ParseTypeAndBasicBlock(DestBB, PFS))
5350         return true;
5351       DestList.push_back(DestBB);
5352     }
5353   }
5354 
5355   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5356     return true;
5357 
5358   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5359   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5360     IBI->addDestination(DestList[i]);
5361   Inst = IBI;
5362   return false;
5363 }
5364 
5365 /// ParseInvoke
5366 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5367 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5368 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5369   LocTy CallLoc = Lex.getLoc();
5370   AttrBuilder RetAttrs, FnAttrs;
5371   std::vector<unsigned> FwdRefAttrGrps;
5372   LocTy NoBuiltinLoc;
5373   unsigned CC;
5374   Type *RetType = nullptr;
5375   LocTy RetTypeLoc;
5376   ValID CalleeID;
5377   SmallVector<ParamInfo, 16> ArgList;
5378   SmallVector<OperandBundleDef, 2> BundleList;
5379 
5380   BasicBlock *NormalBB, *UnwindBB;
5381   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5382       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5383       ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5384       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5385                                  NoBuiltinLoc) ||
5386       ParseOptionalOperandBundles(BundleList, PFS) ||
5387       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5388       ParseTypeAndBasicBlock(NormalBB, PFS) ||
5389       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5390       ParseTypeAndBasicBlock(UnwindBB, PFS))
5391     return true;
5392 
5393   // If RetType is a non-function pointer type, then this is the short syntax
5394   // for the call, which means that RetType is just the return type.  Infer the
5395   // rest of the function argument types from the arguments that are present.
5396   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5397   if (!Ty) {
5398     // Pull out the types of all of the arguments...
5399     std::vector<Type*> ParamTypes;
5400     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5401       ParamTypes.push_back(ArgList[i].V->getType());
5402 
5403     if (!FunctionType::isValidReturnType(RetType))
5404       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5405 
5406     Ty = FunctionType::get(RetType, ParamTypes, false);
5407   }
5408 
5409   CalleeID.FTy = Ty;
5410 
5411   // Look up the callee.
5412   Value *Callee;
5413   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5414     return true;
5415 
5416   // Set up the Attribute for the function.
5417   SmallVector<Value *, 8> Args;
5418   SmallVector<AttributeSet, 8> ArgAttrs;
5419 
5420   // Loop through FunctionType's arguments and ensure they are specified
5421   // correctly.  Also, gather any parameter attributes.
5422   FunctionType::param_iterator I = Ty->param_begin();
5423   FunctionType::param_iterator E = Ty->param_end();
5424   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5425     Type *ExpectedTy = nullptr;
5426     if (I != E) {
5427       ExpectedTy = *I++;
5428     } else if (!Ty->isVarArg()) {
5429       return Error(ArgList[i].Loc, "too many arguments specified");
5430     }
5431 
5432     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5433       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5434                    getTypeString(ExpectedTy) + "'");
5435     Args.push_back(ArgList[i].V);
5436     ArgAttrs.push_back(ArgList[i].Attrs);
5437   }
5438 
5439   if (I != E)
5440     return Error(CallLoc, "not enough parameters specified for call");
5441 
5442   if (FnAttrs.hasAlignmentAttr())
5443     return Error(CallLoc, "invoke instructions may not have an alignment");
5444 
5445   // Finish off the Attribute and check them
5446   AttributeList PAL =
5447       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5448                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
5449 
5450   InvokeInst *II =
5451       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5452   II->setCallingConv(CC);
5453   II->setAttributes(PAL);
5454   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5455   Inst = II;
5456   return false;
5457 }
5458 
5459 /// ParseResume
5460 ///   ::= 'resume' TypeAndValue
5461 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5462   Value *Exn; LocTy ExnLoc;
5463   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5464     return true;
5465 
5466   ResumeInst *RI = ResumeInst::Create(Exn);
5467   Inst = RI;
5468   return false;
5469 }
5470 
5471 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5472                                   PerFunctionState &PFS) {
5473   if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5474     return true;
5475 
5476   while (Lex.getKind() != lltok::rsquare) {
5477     // If this isn't the first argument, we need a comma.
5478     if (!Args.empty() &&
5479         ParseToken(lltok::comma, "expected ',' in argument list"))
5480       return true;
5481 
5482     // Parse the argument.
5483     LocTy ArgLoc;
5484     Type *ArgTy = nullptr;
5485     if (ParseType(ArgTy, ArgLoc))
5486       return true;
5487 
5488     Value *V;
5489     if (ArgTy->isMetadataTy()) {
5490       if (ParseMetadataAsValue(V, PFS))
5491         return true;
5492     } else {
5493       if (ParseValue(ArgTy, V, PFS))
5494         return true;
5495     }
5496     Args.push_back(V);
5497   }
5498 
5499   Lex.Lex();  // Lex the ']'.
5500   return false;
5501 }
5502 
5503 /// ParseCleanupRet
5504 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5505 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5506   Value *CleanupPad = nullptr;
5507 
5508   if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5509     return true;
5510 
5511   if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5512     return true;
5513 
5514   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5515     return true;
5516 
5517   BasicBlock *UnwindBB = nullptr;
5518   if (Lex.getKind() == lltok::kw_to) {
5519     Lex.Lex();
5520     if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5521       return true;
5522   } else {
5523     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5524       return true;
5525     }
5526   }
5527 
5528   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5529   return false;
5530 }
5531 
5532 /// ParseCatchRet
5533 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
5534 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5535   Value *CatchPad = nullptr;
5536 
5537   if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5538     return true;
5539 
5540   if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5541     return true;
5542 
5543   BasicBlock *BB;
5544   if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5545       ParseTypeAndBasicBlock(BB, PFS))
5546       return true;
5547 
5548   Inst = CatchReturnInst::Create(CatchPad, BB);
5549   return false;
5550 }
5551 
5552 /// ParseCatchSwitch
5553 ///   ::= 'catchswitch' within Parent
5554 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5555   Value *ParentPad;
5556   LocTy BBLoc;
5557 
5558   if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5559     return true;
5560 
5561   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5562       Lex.getKind() != lltok::LocalVarID)
5563     return TokError("expected scope value for catchswitch");
5564 
5565   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5566     return true;
5567 
5568   if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5569     return true;
5570 
5571   SmallVector<BasicBlock *, 32> Table;
5572   do {
5573     BasicBlock *DestBB;
5574     if (ParseTypeAndBasicBlock(DestBB, PFS))
5575       return true;
5576     Table.push_back(DestBB);
5577   } while (EatIfPresent(lltok::comma));
5578 
5579   if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5580     return true;
5581 
5582   if (ParseToken(lltok::kw_unwind,
5583                  "expected 'unwind' after catchswitch scope"))
5584     return true;
5585 
5586   BasicBlock *UnwindBB = nullptr;
5587   if (EatIfPresent(lltok::kw_to)) {
5588     if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5589       return true;
5590   } else {
5591     if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5592       return true;
5593   }
5594 
5595   auto *CatchSwitch =
5596       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5597   for (BasicBlock *DestBB : Table)
5598     CatchSwitch->addHandler(DestBB);
5599   Inst = CatchSwitch;
5600   return false;
5601 }
5602 
5603 /// ParseCatchPad
5604 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5605 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5606   Value *CatchSwitch = nullptr;
5607 
5608   if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5609     return true;
5610 
5611   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5612     return TokError("expected scope value for catchpad");
5613 
5614   if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5615     return true;
5616 
5617   SmallVector<Value *, 8> Args;
5618   if (ParseExceptionArgs(Args, PFS))
5619     return true;
5620 
5621   Inst = CatchPadInst::Create(CatchSwitch, Args);
5622   return false;
5623 }
5624 
5625 /// ParseCleanupPad
5626 ///   ::= 'cleanuppad' within Parent ParamList
5627 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5628   Value *ParentPad = nullptr;
5629 
5630   if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5631     return true;
5632 
5633   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5634       Lex.getKind() != lltok::LocalVarID)
5635     return TokError("expected scope value for cleanuppad");
5636 
5637   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5638     return true;
5639 
5640   SmallVector<Value *, 8> Args;
5641   if (ParseExceptionArgs(Args, PFS))
5642     return true;
5643 
5644   Inst = CleanupPadInst::Create(ParentPad, Args);
5645   return false;
5646 }
5647 
5648 //===----------------------------------------------------------------------===//
5649 // Binary Operators.
5650 //===----------------------------------------------------------------------===//
5651 
5652 /// ParseArithmetic
5653 ///  ::= ArithmeticOps TypeAndValue ',' Value
5654 ///
5655 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
5656 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5657 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5658                                unsigned Opc, unsigned OperandType) {
5659   LocTy Loc; Value *LHS, *RHS;
5660   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5661       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5662       ParseValue(LHS->getType(), RHS, PFS))
5663     return true;
5664 
5665   bool Valid;
5666   switch (OperandType) {
5667   default: llvm_unreachable("Unknown operand type!");
5668   case 0: // int or FP.
5669     Valid = LHS->getType()->isIntOrIntVectorTy() ||
5670             LHS->getType()->isFPOrFPVectorTy();
5671     break;
5672   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5673   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5674   }
5675 
5676   if (!Valid)
5677     return Error(Loc, "invalid operand type for instruction");
5678 
5679   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5680   return false;
5681 }
5682 
5683 /// ParseLogical
5684 ///  ::= ArithmeticOps TypeAndValue ',' Value {
5685 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5686                             unsigned Opc) {
5687   LocTy Loc; Value *LHS, *RHS;
5688   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5689       ParseToken(lltok::comma, "expected ',' in logical operation") ||
5690       ParseValue(LHS->getType(), RHS, PFS))
5691     return true;
5692 
5693   if (!LHS->getType()->isIntOrIntVectorTy())
5694     return Error(Loc,"instruction requires integer or integer vector operands");
5695 
5696   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5697   return false;
5698 }
5699 
5700 /// ParseCompare
5701 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
5702 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
5703 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5704                             unsigned Opc) {
5705   // Parse the integer/fp comparison predicate.
5706   LocTy Loc;
5707   unsigned Pred;
5708   Value *LHS, *RHS;
5709   if (ParseCmpPredicate(Pred, Opc) ||
5710       ParseTypeAndValue(LHS, Loc, PFS) ||
5711       ParseToken(lltok::comma, "expected ',' after compare value") ||
5712       ParseValue(LHS->getType(), RHS, PFS))
5713     return true;
5714 
5715   if (Opc == Instruction::FCmp) {
5716     if (!LHS->getType()->isFPOrFPVectorTy())
5717       return Error(Loc, "fcmp requires floating point operands");
5718     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5719   } else {
5720     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5721     if (!LHS->getType()->isIntOrIntVectorTy() &&
5722         !LHS->getType()->isPtrOrPtrVectorTy())
5723       return Error(Loc, "icmp requires integer operands");
5724     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5725   }
5726   return false;
5727 }
5728 
5729 //===----------------------------------------------------------------------===//
5730 // Other Instructions.
5731 //===----------------------------------------------------------------------===//
5732 
5733 
5734 /// ParseCast
5735 ///   ::= CastOpc TypeAndValue 'to' Type
5736 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5737                          unsigned Opc) {
5738   LocTy Loc;
5739   Value *Op;
5740   Type *DestTy = nullptr;
5741   if (ParseTypeAndValue(Op, Loc, PFS) ||
5742       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5743       ParseType(DestTy))
5744     return true;
5745 
5746   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5747     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5748     return Error(Loc, "invalid cast opcode for cast from '" +
5749                  getTypeString(Op->getType()) + "' to '" +
5750                  getTypeString(DestTy) + "'");
5751   }
5752   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5753   return false;
5754 }
5755 
5756 /// ParseSelect
5757 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5758 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5759   LocTy Loc;
5760   Value *Op0, *Op1, *Op2;
5761   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5762       ParseToken(lltok::comma, "expected ',' after select condition") ||
5763       ParseTypeAndValue(Op1, PFS) ||
5764       ParseToken(lltok::comma, "expected ',' after select value") ||
5765       ParseTypeAndValue(Op2, PFS))
5766     return true;
5767 
5768   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5769     return Error(Loc, Reason);
5770 
5771   Inst = SelectInst::Create(Op0, Op1, Op2);
5772   return false;
5773 }
5774 
5775 /// ParseVA_Arg
5776 ///   ::= 'va_arg' TypeAndValue ',' Type
5777 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5778   Value *Op;
5779   Type *EltTy = nullptr;
5780   LocTy TypeLoc;
5781   if (ParseTypeAndValue(Op, PFS) ||
5782       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5783       ParseType(EltTy, TypeLoc))
5784     return true;
5785 
5786   if (!EltTy->isFirstClassType())
5787     return Error(TypeLoc, "va_arg requires operand with first class type");
5788 
5789   Inst = new VAArgInst(Op, EltTy);
5790   return false;
5791 }
5792 
5793 /// ParseExtractElement
5794 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
5795 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5796   LocTy Loc;
5797   Value *Op0, *Op1;
5798   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5799       ParseToken(lltok::comma, "expected ',' after extract value") ||
5800       ParseTypeAndValue(Op1, PFS))
5801     return true;
5802 
5803   if (!ExtractElementInst::isValidOperands(Op0, Op1))
5804     return Error(Loc, "invalid extractelement operands");
5805 
5806   Inst = ExtractElementInst::Create(Op0, Op1);
5807   return false;
5808 }
5809 
5810 /// ParseInsertElement
5811 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5812 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5813   LocTy Loc;
5814   Value *Op0, *Op1, *Op2;
5815   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5816       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5817       ParseTypeAndValue(Op1, PFS) ||
5818       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5819       ParseTypeAndValue(Op2, PFS))
5820     return true;
5821 
5822   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5823     return Error(Loc, "invalid insertelement operands");
5824 
5825   Inst = InsertElementInst::Create(Op0, Op1, Op2);
5826   return false;
5827 }
5828 
5829 /// ParseShuffleVector
5830 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5831 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5832   LocTy Loc;
5833   Value *Op0, *Op1, *Op2;
5834   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5835       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5836       ParseTypeAndValue(Op1, PFS) ||
5837       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5838       ParseTypeAndValue(Op2, PFS))
5839     return true;
5840 
5841   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5842     return Error(Loc, "invalid shufflevector operands");
5843 
5844   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5845   return false;
5846 }
5847 
5848 /// ParsePHI
5849 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5850 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5851   Type *Ty = nullptr;  LocTy TypeLoc;
5852   Value *Op0, *Op1;
5853 
5854   if (ParseType(Ty, TypeLoc) ||
5855       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5856       ParseValue(Ty, Op0, PFS) ||
5857       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5858       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5859       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5860     return true;
5861 
5862   bool AteExtraComma = false;
5863   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5864 
5865   while (true) {
5866     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5867 
5868     if (!EatIfPresent(lltok::comma))
5869       break;
5870 
5871     if (Lex.getKind() == lltok::MetadataVar) {
5872       AteExtraComma = true;
5873       break;
5874     }
5875 
5876     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5877         ParseValue(Ty, Op0, PFS) ||
5878         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5879         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5880         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5881       return true;
5882   }
5883 
5884   if (!Ty->isFirstClassType())
5885     return Error(TypeLoc, "phi node must have first class type");
5886 
5887   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5888   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5889     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5890   Inst = PN;
5891   return AteExtraComma ? InstExtraComma : InstNormal;
5892 }
5893 
5894 /// ParseLandingPad
5895 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5896 /// Clause
5897 ///   ::= 'catch' TypeAndValue
5898 ///   ::= 'filter'
5899 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5900 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5901   Type *Ty = nullptr; LocTy TyLoc;
5902 
5903   if (ParseType(Ty, TyLoc))
5904     return true;
5905 
5906   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5907   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5908 
5909   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5910     LandingPadInst::ClauseType CT;
5911     if (EatIfPresent(lltok::kw_catch))
5912       CT = LandingPadInst::Catch;
5913     else if (EatIfPresent(lltok::kw_filter))
5914       CT = LandingPadInst::Filter;
5915     else
5916       return TokError("expected 'catch' or 'filter' clause type");
5917 
5918     Value *V;
5919     LocTy VLoc;
5920     if (ParseTypeAndValue(V, VLoc, PFS))
5921       return true;
5922 
5923     // A 'catch' type expects a non-array constant. A filter clause expects an
5924     // array constant.
5925     if (CT == LandingPadInst::Catch) {
5926       if (isa<ArrayType>(V->getType()))
5927         Error(VLoc, "'catch' clause has an invalid type");
5928     } else {
5929       if (!isa<ArrayType>(V->getType()))
5930         Error(VLoc, "'filter' clause has an invalid type");
5931     }
5932 
5933     Constant *CV = dyn_cast<Constant>(V);
5934     if (!CV)
5935       return Error(VLoc, "clause argument must be a constant");
5936     LP->addClause(CV);
5937   }
5938 
5939   Inst = LP.release();
5940   return false;
5941 }
5942 
5943 /// ParseCall
5944 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
5945 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5946 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5947 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5948 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5949 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5950 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
5951 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5952 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5953                          CallInst::TailCallKind TCK) {
5954   AttrBuilder RetAttrs, FnAttrs;
5955   std::vector<unsigned> FwdRefAttrGrps;
5956   LocTy BuiltinLoc;
5957   unsigned CC;
5958   Type *RetType = nullptr;
5959   LocTy RetTypeLoc;
5960   ValID CalleeID;
5961   SmallVector<ParamInfo, 16> ArgList;
5962   SmallVector<OperandBundleDef, 2> BundleList;
5963   LocTy CallLoc = Lex.getLoc();
5964 
5965   if (TCK != CallInst::TCK_None &&
5966       ParseToken(lltok::kw_call,
5967                  "expected 'tail call', 'musttail call', or 'notail call'"))
5968     return true;
5969 
5970   FastMathFlags FMF = EatFastMathFlagsIfPresent();
5971 
5972   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5973       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5974       ParseValID(CalleeID) ||
5975       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5976                          PFS.getFunction().isVarArg()) ||
5977       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5978       ParseOptionalOperandBundles(BundleList, PFS))
5979     return true;
5980 
5981   if (FMF.any() && !RetType->isFPOrFPVectorTy())
5982     return Error(CallLoc, "fast-math-flags specified for call without "
5983                           "floating-point scalar or vector return type");
5984 
5985   // If RetType is a non-function pointer type, then this is the short syntax
5986   // for the call, which means that RetType is just the return type.  Infer the
5987   // rest of the function argument types from the arguments that are present.
5988   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5989   if (!Ty) {
5990     // Pull out the types of all of the arguments...
5991     std::vector<Type*> ParamTypes;
5992     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5993       ParamTypes.push_back(ArgList[i].V->getType());
5994 
5995     if (!FunctionType::isValidReturnType(RetType))
5996       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5997 
5998     Ty = FunctionType::get(RetType, ParamTypes, false);
5999   }
6000 
6001   CalleeID.FTy = Ty;
6002 
6003   // Look up the callee.
6004   Value *Callee;
6005   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6006     return true;
6007 
6008   // Set up the Attribute for the function.
6009   SmallVector<AttributeSet, 8> Attrs;
6010 
6011   SmallVector<Value*, 8> Args;
6012 
6013   // Loop through FunctionType's arguments and ensure they are specified
6014   // correctly.  Also, gather any parameter attributes.
6015   FunctionType::param_iterator I = Ty->param_begin();
6016   FunctionType::param_iterator E = Ty->param_end();
6017   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6018     Type *ExpectedTy = nullptr;
6019     if (I != E) {
6020       ExpectedTy = *I++;
6021     } else if (!Ty->isVarArg()) {
6022       return Error(ArgList[i].Loc, "too many arguments specified");
6023     }
6024 
6025     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6026       return Error(ArgList[i].Loc, "argument is not of expected type '" +
6027                    getTypeString(ExpectedTy) + "'");
6028     Args.push_back(ArgList[i].V);
6029     Attrs.push_back(ArgList[i].Attrs);
6030   }
6031 
6032   if (I != E)
6033     return Error(CallLoc, "not enough parameters specified for call");
6034 
6035   if (FnAttrs.hasAlignmentAttr())
6036     return Error(CallLoc, "call instructions may not have an alignment");
6037 
6038   // Finish off the Attribute and check them
6039   AttributeList PAL =
6040       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6041                          AttributeSet::get(Context, RetAttrs), Attrs);
6042 
6043   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6044   CI->setTailCallKind(TCK);
6045   CI->setCallingConv(CC);
6046   if (FMF.any())
6047     CI->setFastMathFlags(FMF);
6048   CI->setAttributes(PAL);
6049   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6050   Inst = CI;
6051   return false;
6052 }
6053 
6054 //===----------------------------------------------------------------------===//
6055 // Memory Instructions.
6056 //===----------------------------------------------------------------------===//
6057 
6058 /// ParseAlloc
6059 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6060 ///       (',' 'align' i32)?
6061 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6062   Value *Size = nullptr;
6063   LocTy SizeLoc, TyLoc, ASLoc;
6064   unsigned Alignment = 0;
6065   unsigned AddrSpace = 0;
6066   Type *Ty = nullptr;
6067 
6068   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6069   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6070 
6071   if (ParseType(Ty, TyLoc)) return true;
6072 
6073   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6074     return Error(TyLoc, "invalid type for alloca");
6075 
6076   bool AteExtraComma = false;
6077   if (EatIfPresent(lltok::comma)) {
6078     if (Lex.getKind() == lltok::kw_align) {
6079       if (ParseOptionalAlignment(Alignment))
6080         return true;
6081       if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6082         return true;
6083     } else if (Lex.getKind() == lltok::kw_addrspace) {
6084       ASLoc = Lex.getLoc();
6085       if (ParseOptionalAddrSpace(AddrSpace))
6086         return true;
6087     } else if (Lex.getKind() == lltok::MetadataVar) {
6088       AteExtraComma = true;
6089     } else {
6090       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6091           ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6092           (!AteExtraComma &&
6093            ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
6094         return true;
6095     }
6096   }
6097 
6098   if (Size && !Size->getType()->isIntegerTy())
6099     return Error(SizeLoc, "element count must have integer type");
6100 
6101   const DataLayout &DL = M->getDataLayout();
6102   unsigned AS = DL.getAllocaAddrSpace();
6103   if (AS != AddrSpace) {
6104     // TODO: In the future it should be possible to specify addrspace per-alloca.
6105     return Error(ASLoc, "address space must match datalayout");
6106   }
6107 
6108   AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
6109   AI->setUsedWithInAlloca(IsInAlloca);
6110   AI->setSwiftError(IsSwiftError);
6111   Inst = AI;
6112   return AteExtraComma ? InstExtraComma : InstNormal;
6113 }
6114 
6115 /// ParseLoad
6116 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6117 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
6118 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
6119 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6120   Value *Val; LocTy Loc;
6121   unsigned Alignment = 0;
6122   bool AteExtraComma = false;
6123   bool isAtomic = false;
6124   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6125   SyncScope::ID SSID = SyncScope::System;
6126 
6127   if (Lex.getKind() == lltok::kw_atomic) {
6128     isAtomic = true;
6129     Lex.Lex();
6130   }
6131 
6132   bool isVolatile = false;
6133   if (Lex.getKind() == lltok::kw_volatile) {
6134     isVolatile = true;
6135     Lex.Lex();
6136   }
6137 
6138   Type *Ty;
6139   LocTy ExplicitTypeLoc = Lex.getLoc();
6140   if (ParseType(Ty) ||
6141       ParseToken(lltok::comma, "expected comma after load's type") ||
6142       ParseTypeAndValue(Val, Loc, PFS) ||
6143       ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6144       ParseOptionalCommaAlign(Alignment, AteExtraComma))
6145     return true;
6146 
6147   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6148     return Error(Loc, "load operand must be a pointer to a first class type");
6149   if (isAtomic && !Alignment)
6150     return Error(Loc, "atomic load must have explicit non-zero alignment");
6151   if (Ordering == AtomicOrdering::Release ||
6152       Ordering == AtomicOrdering::AcquireRelease)
6153     return Error(Loc, "atomic load cannot use Release ordering");
6154 
6155   if (Ty != cast<PointerType>(Val->getType())->getElementType())
6156     return Error(ExplicitTypeLoc,
6157                  "explicit pointee type doesn't match operand's pointee type");
6158 
6159   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6160   return AteExtraComma ? InstExtraComma : InstNormal;
6161 }
6162 
6163 /// ParseStore
6164 
6165 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6166 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6167 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
6168 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6169   Value *Val, *Ptr; LocTy Loc, PtrLoc;
6170   unsigned Alignment = 0;
6171   bool AteExtraComma = false;
6172   bool isAtomic = false;
6173   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6174   SyncScope::ID SSID = SyncScope::System;
6175 
6176   if (Lex.getKind() == lltok::kw_atomic) {
6177     isAtomic = true;
6178     Lex.Lex();
6179   }
6180 
6181   bool isVolatile = false;
6182   if (Lex.getKind() == lltok::kw_volatile) {
6183     isVolatile = true;
6184     Lex.Lex();
6185   }
6186 
6187   if (ParseTypeAndValue(Val, Loc, PFS) ||
6188       ParseToken(lltok::comma, "expected ',' after store operand") ||
6189       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6190       ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6191       ParseOptionalCommaAlign(Alignment, AteExtraComma))
6192     return true;
6193 
6194   if (!Ptr->getType()->isPointerTy())
6195     return Error(PtrLoc, "store operand must be a pointer");
6196   if (!Val->getType()->isFirstClassType())
6197     return Error(Loc, "store operand must be a first class value");
6198   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6199     return Error(Loc, "stored value and pointer type do not match");
6200   if (isAtomic && !Alignment)
6201     return Error(Loc, "atomic store must have explicit non-zero alignment");
6202   if (Ordering == AtomicOrdering::Acquire ||
6203       Ordering == AtomicOrdering::AcquireRelease)
6204     return Error(Loc, "atomic store cannot use Acquire ordering");
6205 
6206   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
6207   return AteExtraComma ? InstExtraComma : InstNormal;
6208 }
6209 
6210 /// ParseCmpXchg
6211 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6212 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6213 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6214   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6215   bool AteExtraComma = false;
6216   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6217   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6218   SyncScope::ID SSID = SyncScope::System;
6219   bool isVolatile = false;
6220   bool isWeak = false;
6221 
6222   if (EatIfPresent(lltok::kw_weak))
6223     isWeak = true;
6224 
6225   if (EatIfPresent(lltok::kw_volatile))
6226     isVolatile = true;
6227 
6228   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6229       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6230       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6231       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6232       ParseTypeAndValue(New, NewLoc, PFS) ||
6233       ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
6234       ParseOrdering(FailureOrdering))
6235     return true;
6236 
6237   if (SuccessOrdering == AtomicOrdering::Unordered ||
6238       FailureOrdering == AtomicOrdering::Unordered)
6239     return TokError("cmpxchg cannot be unordered");
6240   if (isStrongerThan(FailureOrdering, SuccessOrdering))
6241     return TokError("cmpxchg failure argument shall be no stronger than the "
6242                     "success argument");
6243   if (FailureOrdering == AtomicOrdering::Release ||
6244       FailureOrdering == AtomicOrdering::AcquireRelease)
6245     return TokError(
6246         "cmpxchg failure ordering cannot include release semantics");
6247   if (!Ptr->getType()->isPointerTy())
6248     return Error(PtrLoc, "cmpxchg operand must be a pointer");
6249   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6250     return Error(CmpLoc, "compare value and pointer type do not match");
6251   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6252     return Error(NewLoc, "new value and pointer type do not match");
6253   if (!New->getType()->isFirstClassType())
6254     return Error(NewLoc, "cmpxchg operand must be a first class value");
6255   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6256       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
6257   CXI->setVolatile(isVolatile);
6258   CXI->setWeak(isWeak);
6259   Inst = CXI;
6260   return AteExtraComma ? InstExtraComma : InstNormal;
6261 }
6262 
6263 /// ParseAtomicRMW
6264 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6265 ///       'singlethread'? AtomicOrdering
6266 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6267   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6268   bool AteExtraComma = false;
6269   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6270   SyncScope::ID SSID = SyncScope::System;
6271   bool isVolatile = false;
6272   AtomicRMWInst::BinOp Operation;
6273 
6274   if (EatIfPresent(lltok::kw_volatile))
6275     isVolatile = true;
6276 
6277   switch (Lex.getKind()) {
6278   default: return TokError("expected binary operation in atomicrmw");
6279   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6280   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6281   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6282   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6283   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6284   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6285   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6286   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6287   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6288   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6289   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6290   }
6291   Lex.Lex();  // Eat the operation.
6292 
6293   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6294       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6295       ParseTypeAndValue(Val, ValLoc, PFS) ||
6296       ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6297     return true;
6298 
6299   if (Ordering == AtomicOrdering::Unordered)
6300     return TokError("atomicrmw cannot be unordered");
6301   if (!Ptr->getType()->isPointerTy())
6302     return Error(PtrLoc, "atomicrmw operand must be a pointer");
6303   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6304     return Error(ValLoc, "atomicrmw value and pointer type do not match");
6305   if (!Val->getType()->isIntegerTy())
6306     return Error(ValLoc, "atomicrmw operand must be an integer");
6307   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6308   if (Size < 8 || (Size & (Size - 1)))
6309     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6310                          " integer");
6311 
6312   AtomicRMWInst *RMWI =
6313     new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
6314   RMWI->setVolatile(isVolatile);
6315   Inst = RMWI;
6316   return AteExtraComma ? InstExtraComma : InstNormal;
6317 }
6318 
6319 /// ParseFence
6320 ///   ::= 'fence' 'singlethread'? AtomicOrdering
6321 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6322   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6323   SyncScope::ID SSID = SyncScope::System;
6324   if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6325     return true;
6326 
6327   if (Ordering == AtomicOrdering::Unordered)
6328     return TokError("fence cannot be unordered");
6329   if (Ordering == AtomicOrdering::Monotonic)
6330     return TokError("fence cannot be monotonic");
6331 
6332   Inst = new FenceInst(Context, Ordering, SSID);
6333   return InstNormal;
6334 }
6335 
6336 /// ParseGetElementPtr
6337 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6338 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6339   Value *Ptr = nullptr;
6340   Value *Val = nullptr;
6341   LocTy Loc, EltLoc;
6342 
6343   bool InBounds = EatIfPresent(lltok::kw_inbounds);
6344 
6345   Type *Ty = nullptr;
6346   LocTy ExplicitTypeLoc = Lex.getLoc();
6347   if (ParseType(Ty) ||
6348       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6349       ParseTypeAndValue(Ptr, Loc, PFS))
6350     return true;
6351 
6352   Type *BaseType = Ptr->getType();
6353   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6354   if (!BasePointerType)
6355     return Error(Loc, "base of getelementptr must be a pointer");
6356 
6357   if (Ty != BasePointerType->getElementType())
6358     return Error(ExplicitTypeLoc,
6359                  "explicit pointee type doesn't match operand's pointee type");
6360 
6361   SmallVector<Value*, 16> Indices;
6362   bool AteExtraComma = false;
6363   // GEP returns a vector of pointers if at least one of parameters is a vector.
6364   // All vector parameters should have the same vector width.
6365   unsigned GEPWidth = BaseType->isVectorTy() ?
6366     BaseType->getVectorNumElements() : 0;
6367 
6368   while (EatIfPresent(lltok::comma)) {
6369     if (Lex.getKind() == lltok::MetadataVar) {
6370       AteExtraComma = true;
6371       break;
6372     }
6373     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6374     if (!Val->getType()->isIntOrIntVectorTy())
6375       return Error(EltLoc, "getelementptr index must be an integer");
6376 
6377     if (Val->getType()->isVectorTy()) {
6378       unsigned ValNumEl = Val->getType()->getVectorNumElements();
6379       if (GEPWidth && GEPWidth != ValNumEl)
6380         return Error(EltLoc,
6381           "getelementptr vector index has a wrong number of elements");
6382       GEPWidth = ValNumEl;
6383     }
6384     Indices.push_back(Val);
6385   }
6386 
6387   SmallPtrSet<Type*, 4> Visited;
6388   if (!Indices.empty() && !Ty->isSized(&Visited))
6389     return Error(Loc, "base element of getelementptr must be sized");
6390 
6391   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6392     return Error(Loc, "invalid getelementptr indices");
6393   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6394   if (InBounds)
6395     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6396   return AteExtraComma ? InstExtraComma : InstNormal;
6397 }
6398 
6399 /// ParseExtractValue
6400 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
6401 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6402   Value *Val; LocTy Loc;
6403   SmallVector<unsigned, 4> Indices;
6404   bool AteExtraComma;
6405   if (ParseTypeAndValue(Val, Loc, PFS) ||
6406       ParseIndexList(Indices, AteExtraComma))
6407     return true;
6408 
6409   if (!Val->getType()->isAggregateType())
6410     return Error(Loc, "extractvalue operand must be aggregate type");
6411 
6412   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6413     return Error(Loc, "invalid indices for extractvalue");
6414   Inst = ExtractValueInst::Create(Val, Indices);
6415   return AteExtraComma ? InstExtraComma : InstNormal;
6416 }
6417 
6418 /// ParseInsertValue
6419 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6420 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6421   Value *Val0, *Val1; LocTy Loc0, Loc1;
6422   SmallVector<unsigned, 4> Indices;
6423   bool AteExtraComma;
6424   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6425       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6426       ParseTypeAndValue(Val1, Loc1, PFS) ||
6427       ParseIndexList(Indices, AteExtraComma))
6428     return true;
6429 
6430   if (!Val0->getType()->isAggregateType())
6431     return Error(Loc0, "insertvalue operand must be aggregate type");
6432 
6433   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6434   if (!IndexedType)
6435     return Error(Loc0, "invalid indices for insertvalue");
6436   if (IndexedType != Val1->getType())
6437     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6438                            getTypeString(Val1->getType()) + "' instead of '" +
6439                            getTypeString(IndexedType) + "'");
6440   Inst = InsertValueInst::Create(Val0, Val1, Indices);
6441   return AteExtraComma ? InstExtraComma : InstNormal;
6442 }
6443 
6444 //===----------------------------------------------------------------------===//
6445 // Embedded metadata.
6446 //===----------------------------------------------------------------------===//
6447 
6448 /// ParseMDNodeVector
6449 ///   ::= { Element (',' Element)* }
6450 /// Element
6451 ///   ::= 'null' | TypeAndValue
6452 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6453   if (ParseToken(lltok::lbrace, "expected '{' here"))
6454     return true;
6455 
6456   // Check for an empty list.
6457   if (EatIfPresent(lltok::rbrace))
6458     return false;
6459 
6460   do {
6461     // Null is a special case since it is typeless.
6462     if (EatIfPresent(lltok::kw_null)) {
6463       Elts.push_back(nullptr);
6464       continue;
6465     }
6466 
6467     Metadata *MD;
6468     if (ParseMetadata(MD, nullptr))
6469       return true;
6470     Elts.push_back(MD);
6471   } while (EatIfPresent(lltok::comma));
6472 
6473   return ParseToken(lltok::rbrace, "expected end of metadata node");
6474 }
6475 
6476 //===----------------------------------------------------------------------===//
6477 // Use-list order directives.
6478 //===----------------------------------------------------------------------===//
6479 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6480                                 SMLoc Loc) {
6481   if (V->use_empty())
6482     return Error(Loc, "value has no uses");
6483 
6484   unsigned NumUses = 0;
6485   SmallDenseMap<const Use *, unsigned, 16> Order;
6486   for (const Use &U : V->uses()) {
6487     if (++NumUses > Indexes.size())
6488       break;
6489     Order[&U] = Indexes[NumUses - 1];
6490   }
6491   if (NumUses < 2)
6492     return Error(Loc, "value only has one use");
6493   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6494     return Error(Loc, "wrong number of indexes, expected " +
6495                           Twine(std::distance(V->use_begin(), V->use_end())));
6496 
6497   V->sortUseList([&](const Use &L, const Use &R) {
6498     return Order.lookup(&L) < Order.lookup(&R);
6499   });
6500   return false;
6501 }
6502 
6503 /// ParseUseListOrderIndexes
6504 ///   ::= '{' uint32 (',' uint32)+ '}'
6505 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6506   SMLoc Loc = Lex.getLoc();
6507   if (ParseToken(lltok::lbrace, "expected '{' here"))
6508     return true;
6509   if (Lex.getKind() == lltok::rbrace)
6510     return Lex.Error("expected non-empty list of uselistorder indexes");
6511 
6512   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
6513   // indexes should be distinct numbers in the range [0, size-1], and should
6514   // not be in order.
6515   unsigned Offset = 0;
6516   unsigned Max = 0;
6517   bool IsOrdered = true;
6518   assert(Indexes.empty() && "Expected empty order vector");
6519   do {
6520     unsigned Index;
6521     if (ParseUInt32(Index))
6522       return true;
6523 
6524     // Update consistency checks.
6525     Offset += Index - Indexes.size();
6526     Max = std::max(Max, Index);
6527     IsOrdered &= Index == Indexes.size();
6528 
6529     Indexes.push_back(Index);
6530   } while (EatIfPresent(lltok::comma));
6531 
6532   if (ParseToken(lltok::rbrace, "expected '}' here"))
6533     return true;
6534 
6535   if (Indexes.size() < 2)
6536     return Error(Loc, "expected >= 2 uselistorder indexes");
6537   if (Offset != 0 || Max >= Indexes.size())
6538     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6539   if (IsOrdered)
6540     return Error(Loc, "expected uselistorder indexes to change the order");
6541 
6542   return false;
6543 }
6544 
6545 /// ParseUseListOrder
6546 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6547 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6548   SMLoc Loc = Lex.getLoc();
6549   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6550     return true;
6551 
6552   Value *V;
6553   SmallVector<unsigned, 16> Indexes;
6554   if (ParseTypeAndValue(V, PFS) ||
6555       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6556       ParseUseListOrderIndexes(Indexes))
6557     return true;
6558 
6559   return sortUseListOrder(V, Indexes, Loc);
6560 }
6561 
6562 /// ParseUseListOrderBB
6563 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6564 bool LLParser::ParseUseListOrderBB() {
6565   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6566   SMLoc Loc = Lex.getLoc();
6567   Lex.Lex();
6568 
6569   ValID Fn, Label;
6570   SmallVector<unsigned, 16> Indexes;
6571   if (ParseValID(Fn) ||
6572       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6573       ParseValID(Label) ||
6574       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6575       ParseUseListOrderIndexes(Indexes))
6576     return true;
6577 
6578   // Check the function.
6579   GlobalValue *GV;
6580   if (Fn.Kind == ValID::t_GlobalName)
6581     GV = M->getNamedValue(Fn.StrVal);
6582   else if (Fn.Kind == ValID::t_GlobalID)
6583     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6584   else
6585     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6586   if (!GV)
6587     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6588   auto *F = dyn_cast<Function>(GV);
6589   if (!F)
6590     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6591   if (F->isDeclaration())
6592     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6593 
6594   // Check the basic block.
6595   if (Label.Kind == ValID::t_LocalID)
6596     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6597   if (Label.Kind != ValID::t_LocalName)
6598     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6599   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
6600   if (!V)
6601     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6602   if (!isa<BasicBlock>(V))
6603     return Error(Label.Loc, "expected basic block in uselistorder_bb");
6604 
6605   return sortUseListOrder(V, Indexes, Loc);
6606 }
6607