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