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