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