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