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