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