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