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