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