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