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