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