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