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