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