LLParser.cpp revision dcb40a3c1c747c88c4e634e34d1b4d7533a86ada
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/LLVMContext.h"
22#include "llvm/Metadata.h"
23#include "llvm/Module.h"
24#include "llvm/Operator.h"
25#include "llvm/ValueSymbolTable.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
32namespace llvm {
33  /// ValID - Represents a reference of a definition of some sort with no type.
34  /// There are several cases where we have to parse the value but where the
35  /// type can depend on later context.  This may either be a numeric reference
36  /// or a symbolic (%var) reference.  This is just a discriminated union.
37  struct ValID {
38    enum {
39      t_LocalID, t_GlobalID,      // ID in UIntVal.
40      t_LocalName, t_GlobalName,  // Name in StrVal.
41      t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
42      t_Null, t_Undef, t_Zero,    // No value.
43      t_EmptyArray,               // No value:  []
44      t_Constant,                 // Value in ConstantVal.
45      t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
46      t_Metadata                  // Value in MetadataVal.
47    } Kind;
48
49    LLParser::LocTy Loc;
50    unsigned UIntVal;
51    std::string StrVal, StrVal2;
52    APSInt APSIntVal;
53    APFloat APFloatVal;
54    Constant *ConstantVal;
55    MetadataBase *MetadataVal;
56    ValID() : APFloatVal(0.0) {}
57  };
58}
59
60/// Run: module ::= toplevelentity*
61bool LLParser::Run() {
62  // Prime the lexer.
63  Lex.Lex();
64
65  return ParseTopLevelEntities() ||
66         ValidateEndOfModule();
67}
68
69/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
70/// module.
71bool LLParser::ValidateEndOfModule() {
72  if (!ForwardRefTypes.empty())
73    return Error(ForwardRefTypes.begin()->second.second,
74                 "use of undefined type named '" +
75                 ForwardRefTypes.begin()->first + "'");
76  if (!ForwardRefTypeIDs.empty())
77    return Error(ForwardRefTypeIDs.begin()->second.second,
78                 "use of undefined type '%" +
79                 utostr(ForwardRefTypeIDs.begin()->first) + "'");
80
81  if (!ForwardRefVals.empty())
82    return Error(ForwardRefVals.begin()->second.second,
83                 "use of undefined value '@" + ForwardRefVals.begin()->first +
84                 "'");
85
86  if (!ForwardRefValIDs.empty())
87    return Error(ForwardRefValIDs.begin()->second.second,
88                 "use of undefined value '@" +
89                 utostr(ForwardRefValIDs.begin()->first) + "'");
90
91  if (!ForwardRefMDNodes.empty())
92    return Error(ForwardRefMDNodes.begin()->second.second,
93                 "use of undefined metadata '!" +
94                 utostr(ForwardRefMDNodes.begin()->first) + "'");
95
96
97  // Look for intrinsic functions and CallInst that need to be upgraded
98  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99    UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
100
101  return false;
102}
103
104//===----------------------------------------------------------------------===//
105// Top-Level Entities
106//===----------------------------------------------------------------------===//
107
108bool LLParser::ParseTopLevelEntities() {
109  while (1) {
110    switch (Lex.getKind()) {
111    default:         return TokError("expected top-level entity");
112    case lltok::Eof: return false;
113    //case lltok::kw_define:
114    case lltok::kw_declare: if (ParseDeclare()) return true; break;
115    case lltok::kw_define:  if (ParseDefine()) return true; break;
116    case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
117    case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
118    case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
119    case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
120    case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
121    case lltok::LocalVar:   if (ParseNamedType()) return true; break;
122    case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
123    case lltok::Metadata:   if (ParseStandaloneMetadata()) return true; break;
124    case lltok::NamedMD:    if (ParseNamedMetadata()) return true; break;
125
126    // The Global variable production with no name can have many different
127    // optional leading prefixes, the production is:
128    // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
129    //               OptionalAddrSpace ('constant'|'global') ...
130    case lltok::kw_private :       // OptionalLinkage
131    case lltok::kw_linker_private: // OptionalLinkage
132    case lltok::kw_internal:       // OptionalLinkage
133    case lltok::kw_weak:           // OptionalLinkage
134    case lltok::kw_weak_odr:       // OptionalLinkage
135    case lltok::kw_linkonce:       // OptionalLinkage
136    case lltok::kw_linkonce_odr:   // OptionalLinkage
137    case lltok::kw_appending:      // OptionalLinkage
138    case lltok::kw_dllexport:      // OptionalLinkage
139    case lltok::kw_common:         // OptionalLinkage
140    case lltok::kw_dllimport:      // OptionalLinkage
141    case lltok::kw_extern_weak:    // OptionalLinkage
142    case lltok::kw_external: {     // OptionalLinkage
143      unsigned Linkage, Visibility;
144      if (ParseOptionalLinkage(Linkage) ||
145          ParseOptionalVisibility(Visibility) ||
146          ParseGlobal("", SMLoc(), Linkage, true, Visibility))
147        return true;
148      break;
149    }
150    case lltok::kw_default:       // OptionalVisibility
151    case lltok::kw_hidden:        // OptionalVisibility
152    case lltok::kw_protected: {   // OptionalVisibility
153      unsigned Visibility;
154      if (ParseOptionalVisibility(Visibility) ||
155          ParseGlobal("", SMLoc(), 0, false, Visibility))
156        return true;
157      break;
158    }
159
160    case lltok::kw_thread_local:  // OptionalThreadLocal
161    case lltok::kw_addrspace:     // OptionalAddrSpace
162    case lltok::kw_constant:      // GlobalType
163    case lltok::kw_global:        // GlobalType
164      if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
165      break;
166    }
167  }
168}
169
170
171/// toplevelentity
172///   ::= 'module' 'asm' STRINGCONSTANT
173bool LLParser::ParseModuleAsm() {
174  assert(Lex.getKind() == lltok::kw_module);
175  Lex.Lex();
176
177  std::string AsmStr;
178  if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
179      ParseStringConstant(AsmStr)) return true;
180
181  const std::string &AsmSoFar = M->getModuleInlineAsm();
182  if (AsmSoFar.empty())
183    M->setModuleInlineAsm(AsmStr);
184  else
185    M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
186  return false;
187}
188
189/// toplevelentity
190///   ::= 'target' 'triple' '=' STRINGCONSTANT
191///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
192bool LLParser::ParseTargetDefinition() {
193  assert(Lex.getKind() == lltok::kw_target);
194  std::string Str;
195  switch (Lex.Lex()) {
196  default: return TokError("unknown target property");
197  case lltok::kw_triple:
198    Lex.Lex();
199    if (ParseToken(lltok::equal, "expected '=' after target triple") ||
200        ParseStringConstant(Str))
201      return true;
202    M->setTargetTriple(Str);
203    return false;
204  case lltok::kw_datalayout:
205    Lex.Lex();
206    if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
207        ParseStringConstant(Str))
208      return true;
209    M->setDataLayout(Str);
210    return false;
211  }
212}
213
214/// toplevelentity
215///   ::= 'deplibs' '=' '[' ']'
216///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
217bool LLParser::ParseDepLibs() {
218  assert(Lex.getKind() == lltok::kw_deplibs);
219  Lex.Lex();
220  if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
221      ParseToken(lltok::lsquare, "expected '=' after deplibs"))
222    return true;
223
224  if (EatIfPresent(lltok::rsquare))
225    return false;
226
227  std::string Str;
228  if (ParseStringConstant(Str)) return true;
229  M->addLibrary(Str);
230
231  while (EatIfPresent(lltok::comma)) {
232    if (ParseStringConstant(Str)) return true;
233    M->addLibrary(Str);
234  }
235
236  return ParseToken(lltok::rsquare, "expected ']' at end of list");
237}
238
239/// toplevelentity
240///   ::= 'type' type
241bool LLParser::ParseUnnamedType() {
242  assert(Lex.getKind() == lltok::kw_type);
243  LocTy TypeLoc = Lex.getLoc();
244  Lex.Lex(); // eat kw_type
245
246  PATypeHolder Ty(Type::VoidTy);
247  if (ParseType(Ty)) return true;
248
249  unsigned TypeID = NumberedTypes.size();
250
251  // See if this type was previously referenced.
252  std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
253    FI = ForwardRefTypeIDs.find(TypeID);
254  if (FI != ForwardRefTypeIDs.end()) {
255    if (FI->second.first.get() == Ty)
256      return Error(TypeLoc, "self referential type is invalid");
257
258    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
259    Ty = FI->second.first.get();
260    ForwardRefTypeIDs.erase(FI);
261  }
262
263  NumberedTypes.push_back(Ty);
264
265  return false;
266}
267
268/// toplevelentity
269///   ::= LocalVar '=' 'type' type
270bool LLParser::ParseNamedType() {
271  std::string Name = Lex.getStrVal();
272  LocTy NameLoc = Lex.getLoc();
273  Lex.Lex();  // eat LocalVar.
274
275  PATypeHolder Ty(Type::VoidTy);
276
277  if (ParseToken(lltok::equal, "expected '=' after name") ||
278      ParseToken(lltok::kw_type, "expected 'type' after name") ||
279      ParseType(Ty))
280    return true;
281
282  // Set the type name, checking for conflicts as we do so.
283  bool AlreadyExists = M->addTypeName(Name, Ty);
284  if (!AlreadyExists) return false;
285
286  // See if this type is a forward reference.  We need to eagerly resolve
287  // types to allow recursive type redefinitions below.
288  std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
289  FI = ForwardRefTypes.find(Name);
290  if (FI != ForwardRefTypes.end()) {
291    if (FI->second.first.get() == Ty)
292      return Error(NameLoc, "self referential type is invalid");
293
294    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
295    Ty = FI->second.first.get();
296    ForwardRefTypes.erase(FI);
297  }
298
299  // Inserting a name that is already defined, get the existing name.
300  const Type *Existing = M->getTypeByName(Name);
301  assert(Existing && "Conflict but no matching type?!");
302
303  // Otherwise, this is an attempt to redefine a type. That's okay if
304  // the redefinition is identical to the original.
305  // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
306  if (Existing == Ty) return false;
307
308  // Any other kind of (non-equivalent) redefinition is an error.
309  return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
310               Ty->getDescription() + "'");
311}
312
313
314/// toplevelentity
315///   ::= 'declare' FunctionHeader
316bool LLParser::ParseDeclare() {
317  assert(Lex.getKind() == lltok::kw_declare);
318  Lex.Lex();
319
320  Function *F;
321  return ParseFunctionHeader(F, false);
322}
323
324/// toplevelentity
325///   ::= 'define' FunctionHeader '{' ...
326bool LLParser::ParseDefine() {
327  assert(Lex.getKind() == lltok::kw_define);
328  Lex.Lex();
329
330  Function *F;
331  return ParseFunctionHeader(F, true) ||
332         ParseFunctionBody(*F);
333}
334
335/// ParseGlobalType
336///   ::= 'constant'
337///   ::= 'global'
338bool LLParser::ParseGlobalType(bool &IsConstant) {
339  if (Lex.getKind() == lltok::kw_constant)
340    IsConstant = true;
341  else if (Lex.getKind() == lltok::kw_global)
342    IsConstant = false;
343  else {
344    IsConstant = false;
345    return TokError("expected 'global' or 'constant'");
346  }
347  Lex.Lex();
348  return false;
349}
350
351/// ParseNamedGlobal:
352///   GlobalVar '=' OptionalVisibility ALIAS ...
353///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
354bool LLParser::ParseNamedGlobal() {
355  assert(Lex.getKind() == lltok::GlobalVar);
356  LocTy NameLoc = Lex.getLoc();
357  std::string Name = Lex.getStrVal();
358  Lex.Lex();
359
360  bool HasLinkage;
361  unsigned Linkage, Visibility;
362  if (ParseToken(lltok::equal, "expected '=' in global variable") ||
363      ParseOptionalLinkage(Linkage, HasLinkage) ||
364      ParseOptionalVisibility(Visibility))
365    return true;
366
367  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
368    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
369  return ParseAlias(Name, NameLoc, Visibility);
370}
371
372// MDString:
373//   ::= '!' STRINGCONSTANT
374bool LLParser::ParseMDString(MetadataBase *&MDS) {
375  std::string Str;
376  if (ParseStringConstant(Str)) return true;
377  MDS = Context.getMDString(Str);
378  return false;
379}
380
381// MDNode:
382//   ::= '!' MDNodeNumber
383bool LLParser::ParseMDNode(MetadataBase *&Node) {
384  // !{ ..., !42, ... }
385  unsigned MID = 0;
386  if (ParseUInt32(MID))  return true;
387
388  // Check existing MDNode.
389  std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
390  if (I != MetadataCache.end()) {
391    Node = I->second;
392    return false;
393  }
394
395  // Check known forward references.
396  std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
397    FI = ForwardRefMDNodes.find(MID);
398  if (FI != ForwardRefMDNodes.end()) {
399    Node = FI->second.first;
400    return false;
401  }
402
403  // Create MDNode forward reference
404  SmallVector<Value *, 1> Elts;
405  std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
406  Elts.push_back(Context.getMDString(FwdRefName));
407  MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
408  ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
409  Node = FwdNode;
410  return false;
411}
412
413///ParseNamedMetadata:
414///   !foo = !{ !1, !2 }
415bool LLParser::ParseNamedMetadata() {
416  assert(Lex.getKind() == lltok::NamedMD);
417  Lex.Lex();
418  std::string Name = Lex.getStrVal();
419
420  if (ParseToken(lltok::equal, "expected '=' here"))
421    return true;
422
423  if (Lex.getKind() != lltok::Metadata)
424    return TokError("Expected '!' here");
425  Lex.Lex();
426
427  if (Lex.getKind() != lltok::lbrace)
428    return TokError("Expected '{' here");
429  Lex.Lex();
430  SmallVector<MetadataBase *, 8> Elts;
431  do {
432    if (Lex.getKind() != lltok::Metadata)
433      return TokError("Expected '!' here");
434    Lex.Lex();
435    MetadataBase *N = 0;
436    if (ParseMDNode(N)) return true;
437    Elts.push_back(N);
438  } while (EatIfPresent(lltok::comma));
439
440  if (ParseToken(lltok::rbrace, "expected end of metadata node"))
441    return true;
442
443  NamedMDNode::Create(Name.c_str(), Name.length(),
444                      Elts.data(), Elts.size(), M);
445  return false;
446}
447
448/// ParseStandaloneMetadata:
449///   !42 = !{...}
450bool LLParser::ParseStandaloneMetadata() {
451  assert(Lex.getKind() == lltok::Metadata);
452  Lex.Lex();
453  unsigned MetadataID = 0;
454  if (ParseUInt32(MetadataID))
455    return true;
456  if (MetadataCache.find(MetadataID) != MetadataCache.end())
457    return TokError("Metadata id is already used");
458  if (ParseToken(lltok::equal, "expected '=' here"))
459    return true;
460
461  LocTy TyLoc;
462  PATypeHolder Ty(Type::VoidTy);
463  if (ParseType(Ty, TyLoc))
464    return true;
465
466  if (Lex.getKind() != lltok::Metadata)
467    return TokError("Expected metadata here");
468
469  Lex.Lex();
470  if (Lex.getKind() != lltok::lbrace)
471    return TokError("Expected '{' here");
472
473  SmallVector<Value *, 16> Elts;
474  if (ParseMDNodeVector(Elts)
475      || ParseToken(lltok::rbrace, "expected end of metadata node"))
476    return true;
477
478  MDNode *Init = Context.getMDNode(Elts.data(), Elts.size());
479  MetadataCache[MetadataID] = Init;
480  std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
481    FI = ForwardRefMDNodes.find(MetadataID);
482  if (FI != ForwardRefMDNodes.end()) {
483    MDNode *FwdNode = cast<MDNode>(FI->second.first);
484    FwdNode->replaceAllUsesWith(Init);
485    ForwardRefMDNodes.erase(FI);
486  }
487
488  return false;
489}
490
491/// ParseAlias:
492///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
493/// Aliasee
494///   ::= TypeAndValue
495///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
496///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
497///
498/// Everything through visibility has already been parsed.
499///
500bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
501                          unsigned Visibility) {
502  assert(Lex.getKind() == lltok::kw_alias);
503  Lex.Lex();
504  unsigned Linkage;
505  LocTy LinkageLoc = Lex.getLoc();
506  if (ParseOptionalLinkage(Linkage))
507    return true;
508
509  if (Linkage != GlobalValue::ExternalLinkage &&
510      Linkage != GlobalValue::WeakAnyLinkage &&
511      Linkage != GlobalValue::WeakODRLinkage &&
512      Linkage != GlobalValue::InternalLinkage &&
513      Linkage != GlobalValue::PrivateLinkage &&
514      Linkage != GlobalValue::LinkerPrivateLinkage)
515    return Error(LinkageLoc, "invalid linkage type for alias");
516
517  Constant *Aliasee;
518  LocTy AliaseeLoc = Lex.getLoc();
519  if (Lex.getKind() != lltok::kw_bitcast &&
520      Lex.getKind() != lltok::kw_getelementptr) {
521    if (ParseGlobalTypeAndValue(Aliasee)) return true;
522  } else {
523    // The bitcast dest type is not present, it is implied by the dest type.
524    ValID ID;
525    if (ParseValID(ID)) return true;
526    if (ID.Kind != ValID::t_Constant)
527      return Error(AliaseeLoc, "invalid aliasee");
528    Aliasee = ID.ConstantVal;
529  }
530
531  if (!isa<PointerType>(Aliasee->getType()))
532    return Error(AliaseeLoc, "alias must have pointer type");
533
534  // Okay, create the alias but do not insert it into the module yet.
535  GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
536                                    (GlobalValue::LinkageTypes)Linkage, Name,
537                                    Aliasee);
538  GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
539
540  // See if this value already exists in the symbol table.  If so, it is either
541  // a redefinition or a definition of a forward reference.
542  if (GlobalValue *Val =
543        cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
544    // See if this was a redefinition.  If so, there is no entry in
545    // ForwardRefVals.
546    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
547      I = ForwardRefVals.find(Name);
548    if (I == ForwardRefVals.end())
549      return Error(NameLoc, "redefinition of global named '@" + Name + "'");
550
551    // Otherwise, this was a definition of forward ref.  Verify that types
552    // agree.
553    if (Val->getType() != GA->getType())
554      return Error(NameLoc,
555              "forward reference and definition of alias have different types");
556
557    // If they agree, just RAUW the old value with the alias and remove the
558    // forward ref info.
559    Val->replaceAllUsesWith(GA);
560    Val->eraseFromParent();
561    ForwardRefVals.erase(I);
562  }
563
564  // Insert into the module, we know its name won't collide now.
565  M->getAliasList().push_back(GA);
566  assert(GA->getNameStr() == Name && "Should not be a name conflict!");
567
568  return false;
569}
570
571/// ParseGlobal
572///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
573///       OptionalAddrSpace GlobalType Type Const
574///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
575///       OptionalAddrSpace GlobalType Type Const
576///
577/// Everything through visibility has been parsed already.
578///
579bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
580                           unsigned Linkage, bool HasLinkage,
581                           unsigned Visibility) {
582  unsigned AddrSpace;
583  bool ThreadLocal, IsConstant;
584  LocTy TyLoc;
585
586  PATypeHolder Ty(Type::VoidTy);
587  if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
588      ParseOptionalAddrSpace(AddrSpace) ||
589      ParseGlobalType(IsConstant) ||
590      ParseType(Ty, TyLoc))
591    return true;
592
593  // If the linkage is specified and is external, then no initializer is
594  // present.
595  Constant *Init = 0;
596  if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
597                      Linkage != GlobalValue::ExternalWeakLinkage &&
598                      Linkage != GlobalValue::ExternalLinkage)) {
599    if (ParseGlobalValue(Ty, Init))
600      return true;
601  }
602
603  if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
604    return Error(TyLoc, "invalid type for global variable");
605
606  GlobalVariable *GV = 0;
607
608  // See if the global was forward referenced, if so, use the global.
609  if (!Name.empty()) {
610    if ((GV = M->getGlobalVariable(Name, true)) &&
611        !ForwardRefVals.erase(Name))
612      return Error(NameLoc, "redefinition of global '@" + Name + "'");
613  } else {
614    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
615      I = ForwardRefValIDs.find(NumberedVals.size());
616    if (I != ForwardRefValIDs.end()) {
617      GV = cast<GlobalVariable>(I->second.first);
618      ForwardRefValIDs.erase(I);
619    }
620  }
621
622  if (GV == 0) {
623    GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
624                            Name, 0, false, AddrSpace);
625  } else {
626    if (GV->getType()->getElementType() != Ty)
627      return Error(TyLoc,
628            "forward reference and definition of global have different types");
629
630    // Move the forward-reference to the correct spot in the module.
631    M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
632  }
633
634  if (Name.empty())
635    NumberedVals.push_back(GV);
636
637  // Set the parsed properties on the global.
638  if (Init)
639    GV->setInitializer(Init);
640  GV->setConstant(IsConstant);
641  GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
642  GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
643  GV->setThreadLocal(ThreadLocal);
644
645  // Parse attributes on the global.
646  while (Lex.getKind() == lltok::comma) {
647    Lex.Lex();
648
649    if (Lex.getKind() == lltok::kw_section) {
650      Lex.Lex();
651      GV->setSection(Lex.getStrVal());
652      if (ParseToken(lltok::StringConstant, "expected global section string"))
653        return true;
654    } else if (Lex.getKind() == lltok::kw_align) {
655      unsigned Alignment;
656      if (ParseOptionalAlignment(Alignment)) return true;
657      GV->setAlignment(Alignment);
658    } else {
659      TokError("unknown global variable property!");
660    }
661  }
662
663  return false;
664}
665
666
667//===----------------------------------------------------------------------===//
668// GlobalValue Reference/Resolution Routines.
669//===----------------------------------------------------------------------===//
670
671/// GetGlobalVal - Get a value with the specified name or ID, creating a
672/// forward reference record if needed.  This can return null if the value
673/// exists but does not have the right type.
674GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
675                                    LocTy Loc) {
676  const PointerType *PTy = dyn_cast<PointerType>(Ty);
677  if (PTy == 0) {
678    Error(Loc, "global variable reference must have pointer type");
679    return 0;
680  }
681
682  // Look this name up in the normal function symbol table.
683  GlobalValue *Val =
684    cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
685
686  // If this is a forward reference for the value, see if we already created a
687  // forward ref record.
688  if (Val == 0) {
689    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
690      I = ForwardRefVals.find(Name);
691    if (I != ForwardRefVals.end())
692      Val = I->second.first;
693  }
694
695  // If we have the value in the symbol table or fwd-ref table, return it.
696  if (Val) {
697    if (Val->getType() == Ty) return Val;
698    Error(Loc, "'@" + Name + "' defined with type '" +
699          Val->getType()->getDescription() + "'");
700    return 0;
701  }
702
703  // Otherwise, create a new forward reference for this value and remember it.
704  GlobalValue *FwdVal;
705  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
706    // Function types can return opaque but functions can't.
707    if (isa<OpaqueType>(FT->getReturnType())) {
708      Error(Loc, "function may not return opaque type");
709      return 0;
710    }
711
712    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
713  } else {
714    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
715                                GlobalValue::ExternalWeakLinkage, 0, Name);
716  }
717
718  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
719  return FwdVal;
720}
721
722GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
723  const 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  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
730
731  // If this is a forward reference for the value, see if we already created a
732  // forward ref record.
733  if (Val == 0) {
734    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
735      I = ForwardRefValIDs.find(ID);
736    if (I != ForwardRefValIDs.end())
737      Val = I->second.first;
738  }
739
740  // If we have the value in the symbol table or fwd-ref table, return it.
741  if (Val) {
742    if (Val->getType() == Ty) return Val;
743    Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
744          Val->getType()->getDescription() + "'");
745    return 0;
746  }
747
748  // Otherwise, create a new forward reference for this value and remember it.
749  GlobalValue *FwdVal;
750  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
751    // Function types can return opaque but functions can't.
752    if (isa<OpaqueType>(FT->getReturnType())) {
753      Error(Loc, "function may not return opaque type");
754      return 0;
755    }
756    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
757  } else {
758    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
759                                GlobalValue::ExternalWeakLinkage, 0, "");
760  }
761
762  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
763  return FwdVal;
764}
765
766
767//===----------------------------------------------------------------------===//
768// Helper Routines.
769//===----------------------------------------------------------------------===//
770
771/// ParseToken - If the current token has the specified kind, eat it and return
772/// success.  Otherwise, emit the specified error and return failure.
773bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
774  if (Lex.getKind() != T)
775    return TokError(ErrMsg);
776  Lex.Lex();
777  return false;
778}
779
780/// ParseStringConstant
781///   ::= StringConstant
782bool LLParser::ParseStringConstant(std::string &Result) {
783  if (Lex.getKind() != lltok::StringConstant)
784    return TokError("expected string constant");
785  Result = Lex.getStrVal();
786  Lex.Lex();
787  return false;
788}
789
790/// ParseUInt32
791///   ::= uint32
792bool LLParser::ParseUInt32(unsigned &Val) {
793  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
794    return TokError("expected integer");
795  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
796  if (Val64 != unsigned(Val64))
797    return TokError("expected 32-bit integer (too large)");
798  Val = Val64;
799  Lex.Lex();
800  return false;
801}
802
803
804/// ParseOptionalAddrSpace
805///   := /*empty*/
806///   := 'addrspace' '(' uint32 ')'
807bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
808  AddrSpace = 0;
809  if (!EatIfPresent(lltok::kw_addrspace))
810    return false;
811  return ParseToken(lltok::lparen, "expected '(' in address space") ||
812         ParseUInt32(AddrSpace) ||
813         ParseToken(lltok::rparen, "expected ')' in address space");
814}
815
816/// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
817/// indicates what kind of attribute list this is: 0: function arg, 1: result,
818/// 2: function attr.
819/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
820bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
821  Attrs = Attribute::None;
822  LocTy AttrLoc = Lex.getLoc();
823
824  while (1) {
825    switch (Lex.getKind()) {
826    case lltok::kw_sext:
827    case lltok::kw_zext:
828      // Treat these as signext/zeroext if they occur in the argument list after
829      // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
830      // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
831      // expr.
832      // FIXME: REMOVE THIS IN LLVM 3.0
833      if (AttrKind == 3) {
834        if (Lex.getKind() == lltok::kw_sext)
835          Attrs |= Attribute::SExt;
836        else
837          Attrs |= Attribute::ZExt;
838        break;
839      }
840      // FALL THROUGH.
841    default:  // End of attributes.
842      if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
843        return Error(AttrLoc, "invalid use of function-only attribute");
844
845      if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
846        return Error(AttrLoc, "invalid use of parameter-only attribute");
847
848      return false;
849    case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
850    case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
851    case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
852    case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
853    case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
854    case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
855    case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
856    case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
857
858    case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
859    case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
860    case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
861    case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
862    case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
863    case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
864    case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
865    case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
866    case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
867    case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
868    case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
869    case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
870
871    case lltok::kw_align: {
872      unsigned Alignment;
873      if (ParseOptionalAlignment(Alignment))
874        return true;
875      Attrs |= Attribute::constructAlignmentFromInt(Alignment);
876      continue;
877    }
878    }
879    Lex.Lex();
880  }
881}
882
883/// ParseOptionalLinkage
884///   ::= /*empty*/
885///   ::= 'private'
886///   ::= 'linker_private'
887///   ::= 'internal'
888///   ::= 'weak'
889///   ::= 'weak_odr'
890///   ::= 'linkonce'
891///   ::= 'linkonce_odr'
892///   ::= 'appending'
893///   ::= 'dllexport'
894///   ::= 'common'
895///   ::= 'dllimport'
896///   ::= 'extern_weak'
897///   ::= 'external'
898bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
899  HasLinkage = false;
900  switch (Lex.getKind()) {
901  default:                       Res=GlobalValue::ExternalLinkage; return false;
902  case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
903  case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
904  case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
905  case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
906  case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
907  case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
908  case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
909  case lltok::kw_available_externally:
910    Res = GlobalValue::AvailableExternallyLinkage;
911    break;
912  case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
913  case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
914  case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
915  case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
916  case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
917  case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
918  }
919  Lex.Lex();
920  HasLinkage = true;
921  return false;
922}
923
924/// ParseOptionalVisibility
925///   ::= /*empty*/
926///   ::= 'default'
927///   ::= 'hidden'
928///   ::= 'protected'
929///
930bool LLParser::ParseOptionalVisibility(unsigned &Res) {
931  switch (Lex.getKind()) {
932  default:                  Res = GlobalValue::DefaultVisibility; return false;
933  case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
934  case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
935  case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
936  }
937  Lex.Lex();
938  return false;
939}
940
941/// ParseOptionalCallingConv
942///   ::= /*empty*/
943///   ::= 'ccc'
944///   ::= 'fastcc'
945///   ::= 'coldcc'
946///   ::= 'x86_stdcallcc'
947///   ::= 'x86_fastcallcc'
948///   ::= 'arm_apcscc'
949///   ::= 'arm_aapcscc'
950///   ::= 'arm_aapcs_vfpcc'
951///   ::= 'cc' UINT
952///
953bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
954  switch (Lex.getKind()) {
955  default:                       CC = CallingConv::C; return false;
956  case lltok::kw_ccc:            CC = CallingConv::C; break;
957  case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
958  case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
959  case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
960  case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
961  case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
962  case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
963  case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
964  case lltok::kw_cc:             Lex.Lex(); return ParseUInt32(CC);
965  }
966  Lex.Lex();
967  return false;
968}
969
970/// ParseOptionalAlignment
971///   ::= /* empty */
972///   ::= 'align' 4
973bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
974  Alignment = 0;
975  if (!EatIfPresent(lltok::kw_align))
976    return false;
977  LocTy AlignLoc = Lex.getLoc();
978  if (ParseUInt32(Alignment)) return true;
979  if (!isPowerOf2_32(Alignment))
980    return Error(AlignLoc, "alignment is not a power of two");
981  return false;
982}
983
984/// ParseOptionalCommaAlignment
985///   ::= /* empty */
986///   ::= ',' 'align' 4
987bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
988  Alignment = 0;
989  if (!EatIfPresent(lltok::comma))
990    return false;
991  return ParseToken(lltok::kw_align, "expected 'align'") ||
992         ParseUInt32(Alignment);
993}
994
995/// ParseIndexList
996///    ::=  (',' uint32)+
997bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
998  if (Lex.getKind() != lltok::comma)
999    return TokError("expected ',' as start of index list");
1000
1001  while (EatIfPresent(lltok::comma)) {
1002    unsigned Idx;
1003    if (ParseUInt32(Idx)) return true;
1004    Indices.push_back(Idx);
1005  }
1006
1007  return false;
1008}
1009
1010//===----------------------------------------------------------------------===//
1011// Type Parsing.
1012//===----------------------------------------------------------------------===//
1013
1014/// ParseType - Parse and resolve a full type.
1015bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1016  LocTy TypeLoc = Lex.getLoc();
1017  if (ParseTypeRec(Result)) return true;
1018
1019  // Verify no unresolved uprefs.
1020  if (!UpRefs.empty())
1021    return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1022
1023  if (!AllowVoid && Result.get() == Type::VoidTy)
1024    return Error(TypeLoc, "void type only allowed for function results");
1025
1026  return false;
1027}
1028
1029/// HandleUpRefs - Every time we finish a new layer of types, this function is
1030/// called.  It loops through the UpRefs vector, which is a list of the
1031/// currently active types.  For each type, if the up-reference is contained in
1032/// the newly completed type, we decrement the level count.  When the level
1033/// count reaches zero, the up-referenced type is the type that is passed in:
1034/// thus we can complete the cycle.
1035///
1036PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1037  // If Ty isn't abstract, or if there are no up-references in it, then there is
1038  // nothing to resolve here.
1039  if (!ty->isAbstract() || UpRefs.empty()) return ty;
1040
1041  PATypeHolder Ty(ty);
1042#if 0
1043  errs() << "Type '" << Ty->getDescription()
1044         << "' newly formed.  Resolving upreferences.\n"
1045         << UpRefs.size() << " upreferences active!\n";
1046#endif
1047
1048  // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1049  // to zero), we resolve them all together before we resolve them to Ty.  At
1050  // the end of the loop, if there is anything to resolve to Ty, it will be in
1051  // this variable.
1052  OpaqueType *TypeToResolve = 0;
1053
1054  for (unsigned i = 0; i != UpRefs.size(); ++i) {
1055    // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1056    bool ContainsType =
1057      std::find(Ty->subtype_begin(), Ty->subtype_end(),
1058                UpRefs[i].LastContainedTy) != Ty->subtype_end();
1059
1060#if 0
1061    errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1062           << UpRefs[i].LastContainedTy->getDescription() << ") = "
1063           << (ContainsType ? "true" : "false")
1064           << " level=" << UpRefs[i].NestingLevel << "\n";
1065#endif
1066    if (!ContainsType)
1067      continue;
1068
1069    // Decrement level of upreference
1070    unsigned Level = --UpRefs[i].NestingLevel;
1071    UpRefs[i].LastContainedTy = Ty;
1072
1073    // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1074    if (Level != 0)
1075      continue;
1076
1077#if 0
1078    errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1079#endif
1080    if (!TypeToResolve)
1081      TypeToResolve = UpRefs[i].UpRefTy;
1082    else
1083      UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1084    UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1085    --i;                                // Do not skip the next element.
1086  }
1087
1088  if (TypeToResolve)
1089    TypeToResolve->refineAbstractTypeTo(Ty);
1090
1091  return Ty;
1092}
1093
1094
1095/// ParseTypeRec - The recursive function used to process the internal
1096/// implementation details of types.
1097bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1098  switch (Lex.getKind()) {
1099  default:
1100    return TokError("expected type");
1101  case lltok::Type:
1102    // TypeRec ::= 'float' | 'void' (etc)
1103    Result = Lex.getTyVal();
1104    Lex.Lex();
1105    break;
1106  case lltok::kw_opaque:
1107    // TypeRec ::= 'opaque'
1108    Result = Context.getOpaqueType();
1109    Lex.Lex();
1110    break;
1111  case lltok::lbrace:
1112    // TypeRec ::= '{' ... '}'
1113    if (ParseStructType(Result, false))
1114      return true;
1115    break;
1116  case lltok::lsquare:
1117    // TypeRec ::= '[' ... ']'
1118    Lex.Lex(); // eat the lsquare.
1119    if (ParseArrayVectorType(Result, false))
1120      return true;
1121    break;
1122  case lltok::less: // Either vector or packed struct.
1123    // TypeRec ::= '<' ... '>'
1124    Lex.Lex();
1125    if (Lex.getKind() == lltok::lbrace) {
1126      if (ParseStructType(Result, true) ||
1127          ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1128        return true;
1129    } else if (ParseArrayVectorType(Result, true))
1130      return true;
1131    break;
1132  case lltok::LocalVar:
1133  case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1134    // TypeRec ::= %foo
1135    if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1136      Result = T;
1137    } else {
1138      Result = Context.getOpaqueType();
1139      ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1140                                            std::make_pair(Result,
1141                                                           Lex.getLoc())));
1142      M->addTypeName(Lex.getStrVal(), Result.get());
1143    }
1144    Lex.Lex();
1145    break;
1146
1147  case lltok::LocalVarID:
1148    // TypeRec ::= %4
1149    if (Lex.getUIntVal() < NumberedTypes.size())
1150      Result = NumberedTypes[Lex.getUIntVal()];
1151    else {
1152      std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1153        I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1154      if (I != ForwardRefTypeIDs.end())
1155        Result = I->second.first;
1156      else {
1157        Result = Context.getOpaqueType();
1158        ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1159                                                std::make_pair(Result,
1160                                                               Lex.getLoc())));
1161      }
1162    }
1163    Lex.Lex();
1164    break;
1165  case lltok::backslash: {
1166    // TypeRec ::= '\' 4
1167    Lex.Lex();
1168    unsigned Val;
1169    if (ParseUInt32(Val)) return true;
1170    OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1171    UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1172    Result = OT;
1173    break;
1174  }
1175  }
1176
1177  // Parse the type suffixes.
1178  while (1) {
1179    switch (Lex.getKind()) {
1180    // End of type.
1181    default: return false;
1182
1183    // TypeRec ::= TypeRec '*'
1184    case lltok::star:
1185      if (Result.get() == Type::LabelTy)
1186        return TokError("basic block pointers are invalid");
1187      if (Result.get() == Type::VoidTy)
1188        return TokError("pointers to void are invalid; use i8* instead");
1189      if (!PointerType::isValidElementType(Result.get()))
1190        return TokError("pointer to this type is invalid");
1191      Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1192      Lex.Lex();
1193      break;
1194
1195    // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1196    case lltok::kw_addrspace: {
1197      if (Result.get() == Type::LabelTy)
1198        return TokError("basic block pointers are invalid");
1199      if (Result.get() == Type::VoidTy)
1200        return TokError("pointers to void are invalid; use i8* instead");
1201      if (!PointerType::isValidElementType(Result.get()))
1202        return TokError("pointer to this type is invalid");
1203      unsigned AddrSpace;
1204      if (ParseOptionalAddrSpace(AddrSpace) ||
1205          ParseToken(lltok::star, "expected '*' in address space"))
1206        return true;
1207
1208      Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1209      break;
1210    }
1211
1212    /// Types '(' ArgTypeListI ')' OptFuncAttrs
1213    case lltok::lparen:
1214      if (ParseFunctionType(Result))
1215        return true;
1216      break;
1217    }
1218  }
1219}
1220
1221/// ParseParameterList
1222///    ::= '(' ')'
1223///    ::= '(' Arg (',' Arg)* ')'
1224///  Arg
1225///    ::= Type OptionalAttributes Value OptionalAttributes
1226bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1227                                  PerFunctionState &PFS) {
1228  if (ParseToken(lltok::lparen, "expected '(' in call"))
1229    return true;
1230
1231  while (Lex.getKind() != lltok::rparen) {
1232    // If this isn't the first argument, we need a comma.
1233    if (!ArgList.empty() &&
1234        ParseToken(lltok::comma, "expected ',' in argument list"))
1235      return true;
1236
1237    // Parse the argument.
1238    LocTy ArgLoc;
1239    PATypeHolder ArgTy(Type::VoidTy);
1240    unsigned ArgAttrs1, ArgAttrs2;
1241    Value *V;
1242    if (ParseType(ArgTy, ArgLoc) ||
1243        ParseOptionalAttrs(ArgAttrs1, 0) ||
1244        ParseValue(ArgTy, V, PFS) ||
1245        // FIXME: Should not allow attributes after the argument, remove this in
1246        // LLVM 3.0.
1247        ParseOptionalAttrs(ArgAttrs2, 3))
1248      return true;
1249    ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1250  }
1251
1252  Lex.Lex();  // Lex the ')'.
1253  return false;
1254}
1255
1256
1257
1258/// ParseArgumentList - Parse the argument list for a function type or function
1259/// prototype.  If 'inType' is true then we are parsing a FunctionType.
1260///   ::= '(' ArgTypeListI ')'
1261/// ArgTypeListI
1262///   ::= /*empty*/
1263///   ::= '...'
1264///   ::= ArgTypeList ',' '...'
1265///   ::= ArgType (',' ArgType)*
1266///
1267bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1268                                 bool &isVarArg, bool inType) {
1269  isVarArg = false;
1270  assert(Lex.getKind() == lltok::lparen);
1271  Lex.Lex(); // eat the (.
1272
1273  if (Lex.getKind() == lltok::rparen) {
1274    // empty
1275  } else if (Lex.getKind() == lltok::dotdotdot) {
1276    isVarArg = true;
1277    Lex.Lex();
1278  } else {
1279    LocTy TypeLoc = Lex.getLoc();
1280    PATypeHolder ArgTy(Type::VoidTy);
1281    unsigned Attrs;
1282    std::string Name;
1283
1284    // If we're parsing a type, use ParseTypeRec, because we allow recursive
1285    // types (such as a function returning a pointer to itself).  If parsing a
1286    // function prototype, we require fully resolved types.
1287    if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1288        ParseOptionalAttrs(Attrs, 0)) return true;
1289
1290    if (ArgTy == Type::VoidTy)
1291      return Error(TypeLoc, "argument can not have void type");
1292
1293    if (Lex.getKind() == lltok::LocalVar ||
1294        Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1295      Name = Lex.getStrVal();
1296      Lex.Lex();
1297    }
1298
1299    if (!FunctionType::isValidArgumentType(ArgTy))
1300      return Error(TypeLoc, "invalid type for function argument");
1301
1302    ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1303
1304    while (EatIfPresent(lltok::comma)) {
1305      // Handle ... at end of arg list.
1306      if (EatIfPresent(lltok::dotdotdot)) {
1307        isVarArg = true;
1308        break;
1309      }
1310
1311      // Otherwise must be an argument type.
1312      TypeLoc = Lex.getLoc();
1313      if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1314          ParseOptionalAttrs(Attrs, 0)) return true;
1315
1316      if (ArgTy == Type::VoidTy)
1317        return Error(TypeLoc, "argument can not have void type");
1318
1319      if (Lex.getKind() == lltok::LocalVar ||
1320          Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1321        Name = Lex.getStrVal();
1322        Lex.Lex();
1323      } else {
1324        Name = "";
1325      }
1326
1327      if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1328        return Error(TypeLoc, "invalid type for function argument");
1329
1330      ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1331    }
1332  }
1333
1334  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1335}
1336
1337/// ParseFunctionType
1338///  ::= Type ArgumentList OptionalAttrs
1339bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1340  assert(Lex.getKind() == lltok::lparen);
1341
1342  if (!FunctionType::isValidReturnType(Result))
1343    return TokError("invalid function return type");
1344
1345  std::vector<ArgInfo> ArgList;
1346  bool isVarArg;
1347  unsigned Attrs;
1348  if (ParseArgumentList(ArgList, isVarArg, true) ||
1349      // FIXME: Allow, but ignore attributes on function types!
1350      // FIXME: Remove in LLVM 3.0
1351      ParseOptionalAttrs(Attrs, 2))
1352    return true;
1353
1354  // Reject names on the arguments lists.
1355  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1356    if (!ArgList[i].Name.empty())
1357      return Error(ArgList[i].Loc, "argument name invalid in function type");
1358    if (!ArgList[i].Attrs != 0) {
1359      // Allow but ignore attributes on function types; this permits
1360      // auto-upgrade.
1361      // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1362    }
1363  }
1364
1365  std::vector<const Type*> ArgListTy;
1366  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1367    ArgListTy.push_back(ArgList[i].Type);
1368
1369  Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1370                                                ArgListTy, isVarArg));
1371  return false;
1372}
1373
1374/// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1375///   TypeRec
1376///     ::= '{' '}'
1377///     ::= '{' TypeRec (',' TypeRec)* '}'
1378///     ::= '<' '{' '}' '>'
1379///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1380bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1381  assert(Lex.getKind() == lltok::lbrace);
1382  Lex.Lex(); // Consume the '{'
1383
1384  if (EatIfPresent(lltok::rbrace)) {
1385    Result = Context.getStructType(Packed);
1386    return false;
1387  }
1388
1389  std::vector<PATypeHolder> ParamsList;
1390  LocTy EltTyLoc = Lex.getLoc();
1391  if (ParseTypeRec(Result)) return true;
1392  ParamsList.push_back(Result);
1393
1394  if (Result == Type::VoidTy)
1395    return Error(EltTyLoc, "struct element can not have void type");
1396  if (!StructType::isValidElementType(Result))
1397    return Error(EltTyLoc, "invalid element type for struct");
1398
1399  while (EatIfPresent(lltok::comma)) {
1400    EltTyLoc = Lex.getLoc();
1401    if (ParseTypeRec(Result)) return true;
1402
1403    if (Result == Type::VoidTy)
1404      return Error(EltTyLoc, "struct element can not have void type");
1405    if (!StructType::isValidElementType(Result))
1406      return Error(EltTyLoc, "invalid element type for struct");
1407
1408    ParamsList.push_back(Result);
1409  }
1410
1411  if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1412    return true;
1413
1414  std::vector<const Type*> ParamsListTy;
1415  for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1416    ParamsListTy.push_back(ParamsList[i].get());
1417  Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1418  return false;
1419}
1420
1421/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1422/// token has already been consumed.
1423///   TypeRec
1424///     ::= '[' APSINTVAL 'x' Types ']'
1425///     ::= '<' APSINTVAL 'x' Types '>'
1426bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1427  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1428      Lex.getAPSIntVal().getBitWidth() > 64)
1429    return TokError("expected number in address space");
1430
1431  LocTy SizeLoc = Lex.getLoc();
1432  uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1433  Lex.Lex();
1434
1435  if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1436      return true;
1437
1438  LocTy TypeLoc = Lex.getLoc();
1439  PATypeHolder EltTy(Type::VoidTy);
1440  if (ParseTypeRec(EltTy)) return true;
1441
1442  if (EltTy == Type::VoidTy)
1443    return Error(TypeLoc, "array and vector element type cannot be void");
1444
1445  if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1446                 "expected end of sequential type"))
1447    return true;
1448
1449  if (isVector) {
1450    if (Size == 0)
1451      return Error(SizeLoc, "zero element vector is illegal");
1452    if ((unsigned)Size != Size)
1453      return Error(SizeLoc, "size too large for vector");
1454    if (!VectorType::isValidElementType(EltTy))
1455      return Error(TypeLoc, "vector element type must be fp or integer");
1456    Result = Context.getVectorType(EltTy, unsigned(Size));
1457  } else {
1458    if (!ArrayType::isValidElementType(EltTy))
1459      return Error(TypeLoc, "invalid array element type");
1460    Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1461  }
1462  return false;
1463}
1464
1465//===----------------------------------------------------------------------===//
1466// Function Semantic Analysis.
1467//===----------------------------------------------------------------------===//
1468
1469LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1470  : P(p), F(f) {
1471
1472  // Insert unnamed arguments into the NumberedVals list.
1473  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1474       AI != E; ++AI)
1475    if (!AI->hasName())
1476      NumberedVals.push_back(AI);
1477}
1478
1479LLParser::PerFunctionState::~PerFunctionState() {
1480  // If there were any forward referenced non-basicblock values, delete them.
1481  for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1482       I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1483    if (!isa<BasicBlock>(I->second.first)) {
1484      I->second.first->replaceAllUsesWith(
1485                           P.getContext().getUndef(I->second.first->getType()));
1486      delete I->second.first;
1487      I->second.first = 0;
1488    }
1489
1490  for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1491       I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1492    if (!isa<BasicBlock>(I->second.first)) {
1493      I->second.first->replaceAllUsesWith(
1494                           P.getContext().getUndef(I->second.first->getType()));
1495      delete I->second.first;
1496      I->second.first = 0;
1497    }
1498}
1499
1500bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1501  if (!ForwardRefVals.empty())
1502    return P.Error(ForwardRefVals.begin()->second.second,
1503                   "use of undefined value '%" + ForwardRefVals.begin()->first +
1504                   "'");
1505  if (!ForwardRefValIDs.empty())
1506    return P.Error(ForwardRefValIDs.begin()->second.second,
1507                   "use of undefined value '%" +
1508                   utostr(ForwardRefValIDs.begin()->first) + "'");
1509  return false;
1510}
1511
1512
1513/// GetVal - Get a value with the specified name or ID, creating a
1514/// forward reference record if needed.  This can return null if the value
1515/// exists but does not have the right type.
1516Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1517                                          const Type *Ty, LocTy Loc) {
1518  // Look this name up in the normal function symbol table.
1519  Value *Val = F.getValueSymbolTable().lookup(Name);
1520
1521  // If this is a forward reference for the value, see if we already created a
1522  // forward ref record.
1523  if (Val == 0) {
1524    std::map<std::string, std::pair<Value*, LocTy> >::iterator
1525      I = ForwardRefVals.find(Name);
1526    if (I != ForwardRefVals.end())
1527      Val = I->second.first;
1528  }
1529
1530  // If we have the value in the symbol table or fwd-ref table, return it.
1531  if (Val) {
1532    if (Val->getType() == Ty) return Val;
1533    if (Ty == Type::LabelTy)
1534      P.Error(Loc, "'%" + Name + "' is not a basic block");
1535    else
1536      P.Error(Loc, "'%" + Name + "' defined with type '" +
1537              Val->getType()->getDescription() + "'");
1538    return 0;
1539  }
1540
1541  // Don't make placeholders with invalid type.
1542  if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1543    P.Error(Loc, "invalid use of a non-first-class type");
1544    return 0;
1545  }
1546
1547  // Otherwise, create a new forward reference for this value and remember it.
1548  Value *FwdVal;
1549  if (Ty == Type::LabelTy)
1550    FwdVal = BasicBlock::Create(Name, &F);
1551  else
1552    FwdVal = new Argument(Ty, Name);
1553
1554  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1555  return FwdVal;
1556}
1557
1558Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1559                                          LocTy Loc) {
1560  // Look this name up in the normal function symbol table.
1561  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1562
1563  // If this is a forward reference for the value, see if we already created a
1564  // forward ref record.
1565  if (Val == 0) {
1566    std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1567      I = ForwardRefValIDs.find(ID);
1568    if (I != ForwardRefValIDs.end())
1569      Val = I->second.first;
1570  }
1571
1572  // If we have the value in the symbol table or fwd-ref table, return it.
1573  if (Val) {
1574    if (Val->getType() == Ty) return Val;
1575    if (Ty == Type::LabelTy)
1576      P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1577    else
1578      P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1579              Val->getType()->getDescription() + "'");
1580    return 0;
1581  }
1582
1583  if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1584    P.Error(Loc, "invalid use of a non-first-class type");
1585    return 0;
1586  }
1587
1588  // Otherwise, create a new forward reference for this value and remember it.
1589  Value *FwdVal;
1590  if (Ty == Type::LabelTy)
1591    FwdVal = BasicBlock::Create("", &F);
1592  else
1593    FwdVal = new Argument(Ty);
1594
1595  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1596  return FwdVal;
1597}
1598
1599/// SetInstName - After an instruction is parsed and inserted into its
1600/// basic block, this installs its name.
1601bool LLParser::PerFunctionState::SetInstName(int NameID,
1602                                             const std::string &NameStr,
1603                                             LocTy NameLoc, Instruction *Inst) {
1604  // If this instruction has void type, it cannot have a name or ID specified.
1605  if (Inst->getType() == Type::VoidTy) {
1606    if (NameID != -1 || !NameStr.empty())
1607      return P.Error(NameLoc, "instructions returning void cannot have a name");
1608    return false;
1609  }
1610
1611  // If this was a numbered instruction, verify that the instruction is the
1612  // expected value and resolve any forward references.
1613  if (NameStr.empty()) {
1614    // If neither a name nor an ID was specified, just use the next ID.
1615    if (NameID == -1)
1616      NameID = NumberedVals.size();
1617
1618    if (unsigned(NameID) != NumberedVals.size())
1619      return P.Error(NameLoc, "instruction expected to be numbered '%" +
1620                     utostr(NumberedVals.size()) + "'");
1621
1622    std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1623      ForwardRefValIDs.find(NameID);
1624    if (FI != ForwardRefValIDs.end()) {
1625      if (FI->second.first->getType() != Inst->getType())
1626        return P.Error(NameLoc, "instruction forward referenced with type '" +
1627                       FI->second.first->getType()->getDescription() + "'");
1628      FI->second.first->replaceAllUsesWith(Inst);
1629      ForwardRefValIDs.erase(FI);
1630    }
1631
1632    NumberedVals.push_back(Inst);
1633    return false;
1634  }
1635
1636  // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1637  std::map<std::string, std::pair<Value*, LocTy> >::iterator
1638    FI = ForwardRefVals.find(NameStr);
1639  if (FI != ForwardRefVals.end()) {
1640    if (FI->second.first->getType() != Inst->getType())
1641      return P.Error(NameLoc, "instruction forward referenced with type '" +
1642                     FI->second.first->getType()->getDescription() + "'");
1643    FI->second.first->replaceAllUsesWith(Inst);
1644    ForwardRefVals.erase(FI);
1645  }
1646
1647  // Set the name on the instruction.
1648  Inst->setName(NameStr);
1649
1650  if (Inst->getNameStr() != NameStr)
1651    return P.Error(NameLoc, "multiple definition of local value named '" +
1652                   NameStr + "'");
1653  return false;
1654}
1655
1656/// GetBB - Get a basic block with the specified name or ID, creating a
1657/// forward reference record if needed.
1658BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1659                                              LocTy Loc) {
1660  return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1661}
1662
1663BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1664  return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1665}
1666
1667/// DefineBB - Define the specified basic block, which is either named or
1668/// unnamed.  If there is an error, this returns null otherwise it returns
1669/// the block being defined.
1670BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1671                                                 LocTy Loc) {
1672  BasicBlock *BB;
1673  if (Name.empty())
1674    BB = GetBB(NumberedVals.size(), Loc);
1675  else
1676    BB = GetBB(Name, Loc);
1677  if (BB == 0) return 0; // Already diagnosed error.
1678
1679  // Move the block to the end of the function.  Forward ref'd blocks are
1680  // inserted wherever they happen to be referenced.
1681  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1682
1683  // Remove the block from forward ref sets.
1684  if (Name.empty()) {
1685    ForwardRefValIDs.erase(NumberedVals.size());
1686    NumberedVals.push_back(BB);
1687  } else {
1688    // BB forward references are already in the function symbol table.
1689    ForwardRefVals.erase(Name);
1690  }
1691
1692  return BB;
1693}
1694
1695//===----------------------------------------------------------------------===//
1696// Constants.
1697//===----------------------------------------------------------------------===//
1698
1699/// ParseValID - Parse an abstract value that doesn't necessarily have a
1700/// type implied.  For example, if we parse "4" we don't know what integer type
1701/// it has.  The value will later be combined with its type and checked for
1702/// sanity.
1703bool LLParser::ParseValID(ValID &ID) {
1704  ID.Loc = Lex.getLoc();
1705  switch (Lex.getKind()) {
1706  default: return TokError("expected value token");
1707  case lltok::GlobalID:  // @42
1708    ID.UIntVal = Lex.getUIntVal();
1709    ID.Kind = ValID::t_GlobalID;
1710    break;
1711  case lltok::GlobalVar:  // @foo
1712    ID.StrVal = Lex.getStrVal();
1713    ID.Kind = ValID::t_GlobalName;
1714    break;
1715  case lltok::LocalVarID:  // %42
1716    ID.UIntVal = Lex.getUIntVal();
1717    ID.Kind = ValID::t_LocalID;
1718    break;
1719  case lltok::LocalVar:  // %foo
1720  case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1721    ID.StrVal = Lex.getStrVal();
1722    ID.Kind = ValID::t_LocalName;
1723    break;
1724  case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1725    ID.Kind = ValID::t_Metadata;
1726    Lex.Lex();
1727    if (Lex.getKind() == lltok::lbrace) {
1728      SmallVector<Value*, 16> Elts;
1729      if (ParseMDNodeVector(Elts) ||
1730          ParseToken(lltok::rbrace, "expected end of metadata node"))
1731        return true;
1732
1733      ID.MetadataVal = Context.getMDNode(Elts.data(), Elts.size());
1734      return false;
1735    }
1736
1737    // Standalone metadata reference
1738    // !{ ..., !42, ... }
1739    if (!ParseMDNode(ID.MetadataVal))
1740      return false;
1741
1742    // MDString:
1743    //   ::= '!' STRINGCONSTANT
1744    if (ParseMDString(ID.MetadataVal)) return true;
1745    ID.Kind = ValID::t_Metadata;
1746    return false;
1747  }
1748  case lltok::APSInt:
1749    ID.APSIntVal = Lex.getAPSIntVal();
1750    ID.Kind = ValID::t_APSInt;
1751    break;
1752  case lltok::APFloat:
1753    ID.APFloatVal = Lex.getAPFloatVal();
1754    ID.Kind = ValID::t_APFloat;
1755    break;
1756  case lltok::kw_true:
1757    ID.ConstantVal = Context.getTrue();
1758    ID.Kind = ValID::t_Constant;
1759    break;
1760  case lltok::kw_false:
1761    ID.ConstantVal = Context.getFalse();
1762    ID.Kind = ValID::t_Constant;
1763    break;
1764  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1765  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1766  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1767
1768  case lltok::lbrace: {
1769    // ValID ::= '{' ConstVector '}'
1770    Lex.Lex();
1771    SmallVector<Constant*, 16> Elts;
1772    if (ParseGlobalValueVector(Elts) ||
1773        ParseToken(lltok::rbrace, "expected end of struct constant"))
1774      return true;
1775
1776    ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
1777    ID.Kind = ValID::t_Constant;
1778    return false;
1779  }
1780  case lltok::less: {
1781    // ValID ::= '<' ConstVector '>'         --> Vector.
1782    // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1783    Lex.Lex();
1784    bool isPackedStruct = EatIfPresent(lltok::lbrace);
1785
1786    SmallVector<Constant*, 16> Elts;
1787    LocTy FirstEltLoc = Lex.getLoc();
1788    if (ParseGlobalValueVector(Elts) ||
1789        (isPackedStruct &&
1790         ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1791        ParseToken(lltok::greater, "expected end of constant"))
1792      return true;
1793
1794    if (isPackedStruct) {
1795      ID.ConstantVal =
1796        ConstantStruct::get(Elts.data(), Elts.size(), true);
1797      ID.Kind = ValID::t_Constant;
1798      return false;
1799    }
1800
1801    if (Elts.empty())
1802      return Error(ID.Loc, "constant vector must not be empty");
1803
1804    if (!Elts[0]->getType()->isInteger() &&
1805        !Elts[0]->getType()->isFloatingPoint())
1806      return Error(FirstEltLoc,
1807                   "vector elements must have integer or floating point type");
1808
1809    // Verify that all the vector elements have the same type.
1810    for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1811      if (Elts[i]->getType() != Elts[0]->getType())
1812        return Error(FirstEltLoc,
1813                     "vector element #" + utostr(i) +
1814                    " is not of type '" + Elts[0]->getType()->getDescription());
1815
1816    ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1817    ID.Kind = ValID::t_Constant;
1818    return false;
1819  }
1820  case lltok::lsquare: {   // Array Constant
1821    Lex.Lex();
1822    SmallVector<Constant*, 16> Elts;
1823    LocTy FirstEltLoc = Lex.getLoc();
1824    if (ParseGlobalValueVector(Elts) ||
1825        ParseToken(lltok::rsquare, "expected end of array constant"))
1826      return true;
1827
1828    // Handle empty element.
1829    if (Elts.empty()) {
1830      // Use undef instead of an array because it's inconvenient to determine
1831      // the element type at this point, there being no elements to examine.
1832      ID.Kind = ValID::t_EmptyArray;
1833      return false;
1834    }
1835
1836    if (!Elts[0]->getType()->isFirstClassType())
1837      return Error(FirstEltLoc, "invalid array element type: " +
1838                   Elts[0]->getType()->getDescription());
1839
1840    ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1841
1842    // Verify all elements are correct type!
1843    for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1844      if (Elts[i]->getType() != Elts[0]->getType())
1845        return Error(FirstEltLoc,
1846                     "array element #" + utostr(i) +
1847                     " is not of type '" +Elts[0]->getType()->getDescription());
1848    }
1849
1850    ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1851    ID.Kind = ValID::t_Constant;
1852    return false;
1853  }
1854  case lltok::kw_c:  // c "foo"
1855    Lex.Lex();
1856    ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1857    if (ParseToken(lltok::StringConstant, "expected string")) return true;
1858    ID.Kind = ValID::t_Constant;
1859    return false;
1860
1861  case lltok::kw_asm: {
1862    // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1863    bool HasSideEffect;
1864    Lex.Lex();
1865    if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1866        ParseStringConstant(ID.StrVal) ||
1867        ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1868        ParseToken(lltok::StringConstant, "expected constraint string"))
1869      return true;
1870    ID.StrVal2 = Lex.getStrVal();
1871    ID.UIntVal = HasSideEffect;
1872    ID.Kind = ValID::t_InlineAsm;
1873    return false;
1874  }
1875
1876  case lltok::kw_trunc:
1877  case lltok::kw_zext:
1878  case lltok::kw_sext:
1879  case lltok::kw_fptrunc:
1880  case lltok::kw_fpext:
1881  case lltok::kw_bitcast:
1882  case lltok::kw_uitofp:
1883  case lltok::kw_sitofp:
1884  case lltok::kw_fptoui:
1885  case lltok::kw_fptosi:
1886  case lltok::kw_inttoptr:
1887  case lltok::kw_ptrtoint: {
1888    unsigned Opc = Lex.getUIntVal();
1889    PATypeHolder DestTy(Type::VoidTy);
1890    Constant *SrcVal;
1891    Lex.Lex();
1892    if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1893        ParseGlobalTypeAndValue(SrcVal) ||
1894        ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1895        ParseType(DestTy) ||
1896        ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1897      return true;
1898    if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1899      return Error(ID.Loc, "invalid cast opcode for cast from '" +
1900                   SrcVal->getType()->getDescription() + "' to '" +
1901                   DestTy->getDescription() + "'");
1902    ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1903                                                 SrcVal, DestTy);
1904    ID.Kind = ValID::t_Constant;
1905    return false;
1906  }
1907  case lltok::kw_extractvalue: {
1908    Lex.Lex();
1909    Constant *Val;
1910    SmallVector<unsigned, 4> Indices;
1911    if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1912        ParseGlobalTypeAndValue(Val) ||
1913        ParseIndexList(Indices) ||
1914        ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1915      return true;
1916    if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1917      return Error(ID.Loc, "extractvalue operand must be array or struct");
1918    if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1919                                          Indices.end()))
1920      return Error(ID.Loc, "invalid indices for extractvalue");
1921    ID.ConstantVal =
1922      Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1923    ID.Kind = ValID::t_Constant;
1924    return false;
1925  }
1926  case lltok::kw_insertvalue: {
1927    Lex.Lex();
1928    Constant *Val0, *Val1;
1929    SmallVector<unsigned, 4> Indices;
1930    if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1931        ParseGlobalTypeAndValue(Val0) ||
1932        ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1933        ParseGlobalTypeAndValue(Val1) ||
1934        ParseIndexList(Indices) ||
1935        ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1936      return true;
1937    if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1938      return Error(ID.Loc, "extractvalue operand must be array or struct");
1939    if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1940                                          Indices.end()))
1941      return Error(ID.Loc, "invalid indices for insertvalue");
1942    ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1943                       Indices.data(), Indices.size());
1944    ID.Kind = ValID::t_Constant;
1945    return false;
1946  }
1947  case lltok::kw_icmp:
1948  case lltok::kw_fcmp: {
1949    unsigned PredVal, Opc = Lex.getUIntVal();
1950    Constant *Val0, *Val1;
1951    Lex.Lex();
1952    if (ParseCmpPredicate(PredVal, Opc) ||
1953        ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1954        ParseGlobalTypeAndValue(Val0) ||
1955        ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1956        ParseGlobalTypeAndValue(Val1) ||
1957        ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1958      return true;
1959
1960    if (Val0->getType() != Val1->getType())
1961      return Error(ID.Loc, "compare operands must have the same type");
1962
1963    CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1964
1965    if (Opc == Instruction::FCmp) {
1966      if (!Val0->getType()->isFPOrFPVector())
1967        return Error(ID.Loc, "fcmp requires floating point operands");
1968      ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1969    } else {
1970      assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1971      if (!Val0->getType()->isIntOrIntVector() &&
1972          !isa<PointerType>(Val0->getType()))
1973        return Error(ID.Loc, "icmp requires pointer or integer operands");
1974      ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1975    }
1976    ID.Kind = ValID::t_Constant;
1977    return false;
1978  }
1979
1980  // Binary Operators.
1981  case lltok::kw_add:
1982  case lltok::kw_fadd:
1983  case lltok::kw_sub:
1984  case lltok::kw_fsub:
1985  case lltok::kw_mul:
1986  case lltok::kw_fmul:
1987  case lltok::kw_udiv:
1988  case lltok::kw_sdiv:
1989  case lltok::kw_fdiv:
1990  case lltok::kw_urem:
1991  case lltok::kw_srem:
1992  case lltok::kw_frem: {
1993    bool NUW = false;
1994    bool NSW = false;
1995    bool Exact = false;
1996    unsigned Opc = Lex.getUIntVal();
1997    Constant *Val0, *Val1;
1998    Lex.Lex();
1999    LocTy ModifierLoc = Lex.getLoc();
2000    if (Opc == Instruction::Add ||
2001        Opc == Instruction::Sub ||
2002        Opc == Instruction::Mul) {
2003      if (EatIfPresent(lltok::kw_nuw))
2004        NUW = true;
2005      if (EatIfPresent(lltok::kw_nsw)) {
2006        NSW = true;
2007        if (EatIfPresent(lltok::kw_nuw))
2008          NUW = true;
2009      }
2010    } else if (Opc == Instruction::SDiv) {
2011      if (EatIfPresent(lltok::kw_exact))
2012        Exact = true;
2013    }
2014    if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2015        ParseGlobalTypeAndValue(Val0) ||
2016        ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2017        ParseGlobalTypeAndValue(Val1) ||
2018        ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2019      return true;
2020    if (Val0->getType() != Val1->getType())
2021      return Error(ID.Loc, "operands of constexpr must have same type");
2022    if (!Val0->getType()->isIntOrIntVector()) {
2023      if (NUW)
2024        return Error(ModifierLoc, "nuw only applies to integer operations");
2025      if (NSW)
2026        return Error(ModifierLoc, "nsw only applies to integer operations");
2027    }
2028    // API compatibility: Accept either integer or floating-point types with
2029    // add, sub, and mul.
2030    if (!Val0->getType()->isIntOrIntVector() &&
2031        !Val0->getType()->isFPOrFPVector())
2032      return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2033    Constant *C = Context.getConstantExpr(Opc, Val0, Val1);
2034    if (NUW)
2035      cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedOverflow(true);
2036    if (NSW)
2037      cast<OverflowingBinaryOperator>(C)->setHasNoSignedOverflow(true);
2038    if (Exact)
2039      cast<SDivOperator>(C)->setIsExact(true);
2040    ID.ConstantVal = C;
2041    ID.Kind = ValID::t_Constant;
2042    return false;
2043  }
2044
2045  // Logical Operations
2046  case lltok::kw_shl:
2047  case lltok::kw_lshr:
2048  case lltok::kw_ashr:
2049  case lltok::kw_and:
2050  case lltok::kw_or:
2051  case lltok::kw_xor: {
2052    unsigned Opc = Lex.getUIntVal();
2053    Constant *Val0, *Val1;
2054    Lex.Lex();
2055    if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2056        ParseGlobalTypeAndValue(Val0) ||
2057        ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2058        ParseGlobalTypeAndValue(Val1) ||
2059        ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2060      return true;
2061    if (Val0->getType() != Val1->getType())
2062      return Error(ID.Loc, "operands of constexpr must have same type");
2063    if (!Val0->getType()->isIntOrIntVector())
2064      return Error(ID.Loc,
2065                   "constexpr requires integer or integer vector operands");
2066    ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
2067    ID.Kind = ValID::t_Constant;
2068    return false;
2069  }
2070
2071  case lltok::kw_getelementptr:
2072  case lltok::kw_shufflevector:
2073  case lltok::kw_insertelement:
2074  case lltok::kw_extractelement:
2075  case lltok::kw_select: {
2076    unsigned Opc = Lex.getUIntVal();
2077    SmallVector<Constant*, 16> Elts;
2078    bool InBounds = false;
2079    Lex.Lex();
2080    if (Opc == Instruction::GetElementPtr)
2081      InBounds = EatIfPresent(lltok::kw_inbounds);
2082    if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2083        ParseGlobalValueVector(Elts) ||
2084        ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2085      return true;
2086
2087    if (Opc == Instruction::GetElementPtr) {
2088      if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2089        return Error(ID.Loc, "getelementptr requires pointer operand");
2090
2091      if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2092                                             (Value**)(Elts.data() + 1),
2093                                             Elts.size() - 1))
2094        return Error(ID.Loc, "invalid indices for getelementptr");
2095      ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
2096                                              Elts.data() + 1, Elts.size() - 1);
2097      if (InBounds)
2098        cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
2099    } else if (Opc == Instruction::Select) {
2100      if (Elts.size() != 3)
2101        return Error(ID.Loc, "expected three operands to select");
2102      if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2103                                                              Elts[2]))
2104        return Error(ID.Loc, Reason);
2105      ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
2106    } else if (Opc == Instruction::ShuffleVector) {
2107      if (Elts.size() != 3)
2108        return Error(ID.Loc, "expected three operands to shufflevector");
2109      if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2110        return Error(ID.Loc, "invalid operands to shufflevector");
2111      ID.ConstantVal =
2112                 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2113    } else if (Opc == Instruction::ExtractElement) {
2114      if (Elts.size() != 2)
2115        return Error(ID.Loc, "expected two operands to extractelement");
2116      if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2117        return Error(ID.Loc, "invalid extractelement operands");
2118      ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2119    } else {
2120      assert(Opc == Instruction::InsertElement && "Unknown opcode");
2121      if (Elts.size() != 3)
2122      return Error(ID.Loc, "expected three operands to insertelement");
2123      if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2124        return Error(ID.Loc, "invalid insertelement operands");
2125      ID.ConstantVal =
2126                 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2127    }
2128
2129    ID.Kind = ValID::t_Constant;
2130    return false;
2131  }
2132  }
2133
2134  Lex.Lex();
2135  return false;
2136}
2137
2138/// ParseGlobalValue - Parse a global value with the specified type.
2139bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2140  V = 0;
2141  ValID ID;
2142  return ParseValID(ID) ||
2143         ConvertGlobalValIDToValue(Ty, ID, V);
2144}
2145
2146/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2147/// constant.
2148bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2149                                         Constant *&V) {
2150  if (isa<FunctionType>(Ty))
2151    return Error(ID.Loc, "functions are not values, refer to them as pointers");
2152
2153  switch (ID.Kind) {
2154  default: llvm_unreachable("Unknown ValID!");
2155  case ValID::t_Metadata:
2156    return Error(ID.Loc, "invalid use of metadata");
2157  case ValID::t_LocalID:
2158  case ValID::t_LocalName:
2159    return Error(ID.Loc, "invalid use of function-local name");
2160  case ValID::t_InlineAsm:
2161    return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2162  case ValID::t_GlobalName:
2163    V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2164    return V == 0;
2165  case ValID::t_GlobalID:
2166    V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2167    return V == 0;
2168  case ValID::t_APSInt:
2169    if (!isa<IntegerType>(Ty))
2170      return Error(ID.Loc, "integer constant must have integer type");
2171    ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2172    V = ConstantInt::get(Context, ID.APSIntVal);
2173    return false;
2174  case ValID::t_APFloat:
2175    if (!Ty->isFloatingPoint() ||
2176        !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2177      return Error(ID.Loc, "floating point constant invalid for type");
2178
2179    // The lexer has no type info, so builds all float and double FP constants
2180    // as double.  Fix this here.  Long double does not need this.
2181    if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2182        Ty == Type::FloatTy) {
2183      bool Ignored;
2184      ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2185                            &Ignored);
2186    }
2187    V = ConstantFP::get(Context, ID.APFloatVal);
2188
2189    if (V->getType() != Ty)
2190      return Error(ID.Loc, "floating point constant does not have type '" +
2191                   Ty->getDescription() + "'");
2192
2193    return false;
2194  case ValID::t_Null:
2195    if (!isa<PointerType>(Ty))
2196      return Error(ID.Loc, "null must be a pointer type");
2197    V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2198    return false;
2199  case ValID::t_Undef:
2200    // FIXME: LabelTy should not be a first-class type.
2201    if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2202        !isa<OpaqueType>(Ty))
2203      return Error(ID.Loc, "invalid type for undef constant");
2204    V = Context.getUndef(Ty);
2205    return false;
2206  case ValID::t_EmptyArray:
2207    if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2208      return Error(ID.Loc, "invalid empty array initializer");
2209    V = Context.getUndef(Ty);
2210    return false;
2211  case ValID::t_Zero:
2212    // FIXME: LabelTy should not be a first-class type.
2213    if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2214      return Error(ID.Loc, "invalid type for null constant");
2215    V = Context.getNullValue(Ty);
2216    return false;
2217  case ValID::t_Constant:
2218    if (ID.ConstantVal->getType() != Ty)
2219      return Error(ID.Loc, "constant expression type mismatch");
2220    V = ID.ConstantVal;
2221    return false;
2222  }
2223}
2224
2225bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2226  PATypeHolder Type(Type::VoidTy);
2227  return ParseType(Type) ||
2228         ParseGlobalValue(Type, V);
2229}
2230
2231/// ParseGlobalValueVector
2232///   ::= /*empty*/
2233///   ::= TypeAndValue (',' TypeAndValue)*
2234bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2235  // Empty list.
2236  if (Lex.getKind() == lltok::rbrace ||
2237      Lex.getKind() == lltok::rsquare ||
2238      Lex.getKind() == lltok::greater ||
2239      Lex.getKind() == lltok::rparen)
2240    return false;
2241
2242  Constant *C;
2243  if (ParseGlobalTypeAndValue(C)) return true;
2244  Elts.push_back(C);
2245
2246  while (EatIfPresent(lltok::comma)) {
2247    if (ParseGlobalTypeAndValue(C)) return true;
2248    Elts.push_back(C);
2249  }
2250
2251  return false;
2252}
2253
2254
2255//===----------------------------------------------------------------------===//
2256// Function Parsing.
2257//===----------------------------------------------------------------------===//
2258
2259bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2260                                   PerFunctionState &PFS) {
2261  if (ID.Kind == ValID::t_LocalID)
2262    V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2263  else if (ID.Kind == ValID::t_LocalName)
2264    V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2265  else if (ID.Kind == ValID::t_InlineAsm) {
2266    const PointerType *PTy = dyn_cast<PointerType>(Ty);
2267    const FunctionType *FTy =
2268      PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2269    if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2270      return Error(ID.Loc, "invalid type for inline asm constraint string");
2271    V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2272    return false;
2273  } else if (ID.Kind == ValID::t_Metadata) {
2274    V = ID.MetadataVal;
2275  } else {
2276    Constant *C;
2277    if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2278    V = C;
2279    return false;
2280  }
2281
2282  return V == 0;
2283}
2284
2285bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2286  V = 0;
2287  ValID ID;
2288  return ParseValID(ID) ||
2289         ConvertValIDToValue(Ty, ID, V, PFS);
2290}
2291
2292bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2293  PATypeHolder T(Type::VoidTy);
2294  return ParseType(T) ||
2295         ParseValue(T, V, PFS);
2296}
2297
2298/// FunctionHeader
2299///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2300///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2301///       OptionalAlign OptGC
2302bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2303  // Parse the linkage.
2304  LocTy LinkageLoc = Lex.getLoc();
2305  unsigned Linkage;
2306
2307  unsigned Visibility, CC, RetAttrs;
2308  PATypeHolder RetType(Type::VoidTy);
2309  LocTy RetTypeLoc = Lex.getLoc();
2310  if (ParseOptionalLinkage(Linkage) ||
2311      ParseOptionalVisibility(Visibility) ||
2312      ParseOptionalCallingConv(CC) ||
2313      ParseOptionalAttrs(RetAttrs, 1) ||
2314      ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2315    return true;
2316
2317  // Verify that the linkage is ok.
2318  switch ((GlobalValue::LinkageTypes)Linkage) {
2319  case GlobalValue::ExternalLinkage:
2320    break; // always ok.
2321  case GlobalValue::DLLImportLinkage:
2322  case GlobalValue::ExternalWeakLinkage:
2323    if (isDefine)
2324      return Error(LinkageLoc, "invalid linkage for function definition");
2325    break;
2326  case GlobalValue::PrivateLinkage:
2327  case GlobalValue::LinkerPrivateLinkage:
2328  case GlobalValue::InternalLinkage:
2329  case GlobalValue::AvailableExternallyLinkage:
2330  case GlobalValue::LinkOnceAnyLinkage:
2331  case GlobalValue::LinkOnceODRLinkage:
2332  case GlobalValue::WeakAnyLinkage:
2333  case GlobalValue::WeakODRLinkage:
2334  case GlobalValue::DLLExportLinkage:
2335    if (!isDefine)
2336      return Error(LinkageLoc, "invalid linkage for function declaration");
2337    break;
2338  case GlobalValue::AppendingLinkage:
2339  case GlobalValue::GhostLinkage:
2340  case GlobalValue::CommonLinkage:
2341    return Error(LinkageLoc, "invalid function linkage type");
2342  }
2343
2344  if (!FunctionType::isValidReturnType(RetType) ||
2345      isa<OpaqueType>(RetType))
2346    return Error(RetTypeLoc, "invalid function return type");
2347
2348  LocTy NameLoc = Lex.getLoc();
2349
2350  std::string FunctionName;
2351  if (Lex.getKind() == lltok::GlobalVar) {
2352    FunctionName = Lex.getStrVal();
2353  } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2354    unsigned NameID = Lex.getUIntVal();
2355
2356    if (NameID != NumberedVals.size())
2357      return TokError("function expected to be numbered '%" +
2358                      utostr(NumberedVals.size()) + "'");
2359  } else {
2360    return TokError("expected function name");
2361  }
2362
2363  Lex.Lex();
2364
2365  if (Lex.getKind() != lltok::lparen)
2366    return TokError("expected '(' in function argument list");
2367
2368  std::vector<ArgInfo> ArgList;
2369  bool isVarArg;
2370  unsigned FuncAttrs;
2371  std::string Section;
2372  unsigned Alignment;
2373  std::string GC;
2374
2375  if (ParseArgumentList(ArgList, isVarArg, false) ||
2376      ParseOptionalAttrs(FuncAttrs, 2) ||
2377      (EatIfPresent(lltok::kw_section) &&
2378       ParseStringConstant(Section)) ||
2379      ParseOptionalAlignment(Alignment) ||
2380      (EatIfPresent(lltok::kw_gc) &&
2381       ParseStringConstant(GC)))
2382    return true;
2383
2384  // If the alignment was parsed as an attribute, move to the alignment field.
2385  if (FuncAttrs & Attribute::Alignment) {
2386    Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2387    FuncAttrs &= ~Attribute::Alignment;
2388  }
2389
2390  // Okay, if we got here, the function is syntactically valid.  Convert types
2391  // and do semantic checks.
2392  std::vector<const Type*> ParamTypeList;
2393  SmallVector<AttributeWithIndex, 8> Attrs;
2394  // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2395  // attributes.
2396  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2397  if (FuncAttrs & ObsoleteFuncAttrs) {
2398    RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2399    FuncAttrs &= ~ObsoleteFuncAttrs;
2400  }
2401
2402  if (RetAttrs != Attribute::None)
2403    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2404
2405  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2406    ParamTypeList.push_back(ArgList[i].Type);
2407    if (ArgList[i].Attrs != Attribute::None)
2408      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2409  }
2410
2411  if (FuncAttrs != Attribute::None)
2412    Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2413
2414  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2415
2416  if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2417      RetType != Type::VoidTy)
2418    return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2419
2420  const FunctionType *FT =
2421    Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2422  const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2423
2424  Fn = 0;
2425  if (!FunctionName.empty()) {
2426    // If this was a definition of a forward reference, remove the definition
2427    // from the forward reference table and fill in the forward ref.
2428    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2429      ForwardRefVals.find(FunctionName);
2430    if (FRVI != ForwardRefVals.end()) {
2431      Fn = M->getFunction(FunctionName);
2432      ForwardRefVals.erase(FRVI);
2433    } else if ((Fn = M->getFunction(FunctionName))) {
2434      // If this function already exists in the symbol table, then it is
2435      // multiply defined.  We accept a few cases for old backwards compat.
2436      // FIXME: Remove this stuff for LLVM 3.0.
2437      if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2438          (!Fn->isDeclaration() && isDefine)) {
2439        // If the redefinition has different type or different attributes,
2440        // reject it.  If both have bodies, reject it.
2441        return Error(NameLoc, "invalid redefinition of function '" +
2442                     FunctionName + "'");
2443      } else if (Fn->isDeclaration()) {
2444        // Make sure to strip off any argument names so we can't get conflicts.
2445        for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2446             AI != AE; ++AI)
2447          AI->setName("");
2448      }
2449    }
2450
2451  } else if (FunctionName.empty()) {
2452    // If this is a definition of a forward referenced function, make sure the
2453    // types agree.
2454    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2455      = ForwardRefValIDs.find(NumberedVals.size());
2456    if (I != ForwardRefValIDs.end()) {
2457      Fn = cast<Function>(I->second.first);
2458      if (Fn->getType() != PFT)
2459        return Error(NameLoc, "type of definition and forward reference of '@" +
2460                     utostr(NumberedVals.size()) +"' disagree");
2461      ForwardRefValIDs.erase(I);
2462    }
2463  }
2464
2465  if (Fn == 0)
2466    Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2467  else // Move the forward-reference to the correct spot in the module.
2468    M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2469
2470  if (FunctionName.empty())
2471    NumberedVals.push_back(Fn);
2472
2473  Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2474  Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2475  Fn->setCallingConv(CC);
2476  Fn->setAttributes(PAL);
2477  Fn->setAlignment(Alignment);
2478  Fn->setSection(Section);
2479  if (!GC.empty()) Fn->setGC(GC.c_str());
2480
2481  // Add all of the arguments we parsed to the function.
2482  Function::arg_iterator ArgIt = Fn->arg_begin();
2483  for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2484    // If the argument has a name, insert it into the argument symbol table.
2485    if (ArgList[i].Name.empty()) continue;
2486
2487    // Set the name, if it conflicted, it will be auto-renamed.
2488    ArgIt->setName(ArgList[i].Name);
2489
2490    if (ArgIt->getNameStr() != ArgList[i].Name)
2491      return Error(ArgList[i].Loc, "redefinition of argument '%" +
2492                   ArgList[i].Name + "'");
2493  }
2494
2495  return false;
2496}
2497
2498
2499/// ParseFunctionBody
2500///   ::= '{' BasicBlock+ '}'
2501///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2502///
2503bool LLParser::ParseFunctionBody(Function &Fn) {
2504  if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2505    return TokError("expected '{' in function body");
2506  Lex.Lex();  // eat the {.
2507
2508  PerFunctionState PFS(*this, Fn);
2509
2510  while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2511    if (ParseBasicBlock(PFS)) return true;
2512
2513  // Eat the }.
2514  Lex.Lex();
2515
2516  // Verify function is ok.
2517  return PFS.VerifyFunctionComplete();
2518}
2519
2520/// ParseBasicBlock
2521///   ::= LabelStr? Instruction*
2522bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2523  // If this basic block starts out with a name, remember it.
2524  std::string Name;
2525  LocTy NameLoc = Lex.getLoc();
2526  if (Lex.getKind() == lltok::LabelStr) {
2527    Name = Lex.getStrVal();
2528    Lex.Lex();
2529  }
2530
2531  BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2532  if (BB == 0) return true;
2533
2534  std::string NameStr;
2535
2536  // Parse the instructions in this block until we get a terminator.
2537  Instruction *Inst;
2538  do {
2539    // This instruction may have three possibilities for a name: a) none
2540    // specified, b) name specified "%foo =", c) number specified: "%4 =".
2541    LocTy NameLoc = Lex.getLoc();
2542    int NameID = -1;
2543    NameStr = "";
2544
2545    if (Lex.getKind() == lltok::LocalVarID) {
2546      NameID = Lex.getUIntVal();
2547      Lex.Lex();
2548      if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2549        return true;
2550    } else if (Lex.getKind() == lltok::LocalVar ||
2551               // FIXME: REMOVE IN LLVM 3.0
2552               Lex.getKind() == lltok::StringConstant) {
2553      NameStr = Lex.getStrVal();
2554      Lex.Lex();
2555      if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2556        return true;
2557    }
2558
2559    if (ParseInstruction(Inst, BB, PFS)) return true;
2560
2561    BB->getInstList().push_back(Inst);
2562
2563    // Set the name on the instruction.
2564    if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2565  } while (!isa<TerminatorInst>(Inst));
2566
2567  return false;
2568}
2569
2570//===----------------------------------------------------------------------===//
2571// Instruction Parsing.
2572//===----------------------------------------------------------------------===//
2573
2574/// ParseInstruction - Parse one of the many different instructions.
2575///
2576bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2577                                PerFunctionState &PFS) {
2578  lltok::Kind Token = Lex.getKind();
2579  if (Token == lltok::Eof)
2580    return TokError("found end of file when expecting more instructions");
2581  LocTy Loc = Lex.getLoc();
2582  unsigned KeywordVal = Lex.getUIntVal();
2583  Lex.Lex();  // Eat the keyword.
2584
2585  switch (Token) {
2586  default:                    return Error(Loc, "expected instruction opcode");
2587  // Terminator Instructions.
2588  case lltok::kw_unwind:      Inst = new UnwindInst(); return false;
2589  case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2590  case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2591  case lltok::kw_br:          return ParseBr(Inst, PFS);
2592  case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2593  case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2594  // Binary Operators.
2595  case lltok::kw_add:
2596  case lltok::kw_sub:
2597  case lltok::kw_mul: {
2598    bool NUW = false;
2599    bool NSW = false;
2600    LocTy ModifierLoc = Lex.getLoc();
2601    if (EatIfPresent(lltok::kw_nuw))
2602      NUW = true;
2603    if (EatIfPresent(lltok::kw_nsw)) {
2604      NSW = true;
2605      if (EatIfPresent(lltok::kw_nuw))
2606        NUW = true;
2607    }
2608    // API compatibility: Accept either integer or floating-point types.
2609    bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2610    if (!Result) {
2611      if (!Inst->getType()->isIntOrIntVector()) {
2612        if (NUW)
2613          return Error(ModifierLoc, "nuw only applies to integer operations");
2614        if (NSW)
2615          return Error(ModifierLoc, "nsw only applies to integer operations");
2616      }
2617      if (NUW)
2618        cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2619      if (NSW)
2620        cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2621    }
2622    return Result;
2623  }
2624  case lltok::kw_fadd:
2625  case lltok::kw_fsub:
2626  case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2627
2628  case lltok::kw_sdiv: {
2629    bool Exact = false;
2630    if (EatIfPresent(lltok::kw_exact))
2631      Exact = true;
2632    bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2633    if (!Result)
2634      if (Exact)
2635        cast<SDivOperator>(Inst)->setIsExact(true);
2636    return Result;
2637  }
2638
2639  case lltok::kw_udiv:
2640  case lltok::kw_urem:
2641  case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2642  case lltok::kw_fdiv:
2643  case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2644  case lltok::kw_shl:
2645  case lltok::kw_lshr:
2646  case lltok::kw_ashr:
2647  case lltok::kw_and:
2648  case lltok::kw_or:
2649  case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2650  case lltok::kw_icmp:
2651  case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2652  // Casts.
2653  case lltok::kw_trunc:
2654  case lltok::kw_zext:
2655  case lltok::kw_sext:
2656  case lltok::kw_fptrunc:
2657  case lltok::kw_fpext:
2658  case lltok::kw_bitcast:
2659  case lltok::kw_uitofp:
2660  case lltok::kw_sitofp:
2661  case lltok::kw_fptoui:
2662  case lltok::kw_fptosi:
2663  case lltok::kw_inttoptr:
2664  case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2665  // Other.
2666  case lltok::kw_select:         return ParseSelect(Inst, PFS);
2667  case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2668  case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2669  case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2670  case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2671  case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2672  case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2673  case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2674  // Memory.
2675  case lltok::kw_alloca:
2676  case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
2677  case lltok::kw_free:           return ParseFree(Inst, PFS);
2678  case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2679  case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2680  case lltok::kw_volatile:
2681    if (EatIfPresent(lltok::kw_load))
2682      return ParseLoad(Inst, PFS, true);
2683    else if (EatIfPresent(lltok::kw_store))
2684      return ParseStore(Inst, PFS, true);
2685    else
2686      return TokError("expected 'load' or 'store'");
2687  case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2688  case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2689  case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2690  case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2691  }
2692}
2693
2694/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2695bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2696  if (Opc == Instruction::FCmp) {
2697    switch (Lex.getKind()) {
2698    default: TokError("expected fcmp predicate (e.g. 'oeq')");
2699    case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2700    case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2701    case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2702    case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2703    case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2704    case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2705    case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2706    case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2707    case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2708    case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2709    case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2710    case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2711    case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2712    case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2713    case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2714    case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2715    }
2716  } else {
2717    switch (Lex.getKind()) {
2718    default: TokError("expected icmp predicate (e.g. 'eq')");
2719    case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2720    case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2721    case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2722    case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2723    case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2724    case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2725    case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2726    case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2727    case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2728    case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2729    }
2730  }
2731  Lex.Lex();
2732  return false;
2733}
2734
2735//===----------------------------------------------------------------------===//
2736// Terminator Instructions.
2737//===----------------------------------------------------------------------===//
2738
2739/// ParseRet - Parse a return instruction.
2740///   ::= 'ret' void
2741///   ::= 'ret' TypeAndValue
2742///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  [[obsolete: LLVM 3.0]]
2743bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2744                        PerFunctionState &PFS) {
2745  PATypeHolder Ty(Type::VoidTy);
2746  if (ParseType(Ty, true /*void allowed*/)) return true;
2747
2748  if (Ty == Type::VoidTy) {
2749    Inst = ReturnInst::Create();
2750    return false;
2751  }
2752
2753  Value *RV;
2754  if (ParseValue(Ty, RV, PFS)) return true;
2755
2756  // The normal case is one return value.
2757  if (Lex.getKind() == lltok::comma) {
2758    // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2759    // of 'ret {i32,i32} {i32 1, i32 2}'
2760    SmallVector<Value*, 8> RVs;
2761    RVs.push_back(RV);
2762
2763    while (EatIfPresent(lltok::comma)) {
2764      if (ParseTypeAndValue(RV, PFS)) return true;
2765      RVs.push_back(RV);
2766    }
2767
2768    RV = Context.getUndef(PFS.getFunction().getReturnType());
2769    for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2770      Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2771      BB->getInstList().push_back(I);
2772      RV = I;
2773    }
2774  }
2775  Inst = ReturnInst::Create(RV);
2776  return false;
2777}
2778
2779
2780/// ParseBr
2781///   ::= 'br' TypeAndValue
2782///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2783bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2784  LocTy Loc, Loc2;
2785  Value *Op0, *Op1, *Op2;
2786  if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2787
2788  if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2789    Inst = BranchInst::Create(BB);
2790    return false;
2791  }
2792
2793  if (Op0->getType() != Type::Int1Ty)
2794    return Error(Loc, "branch condition must have 'i1' type");
2795
2796  if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2797      ParseTypeAndValue(Op1, Loc, PFS) ||
2798      ParseToken(lltok::comma, "expected ',' after true destination") ||
2799      ParseTypeAndValue(Op2, Loc2, PFS))
2800    return true;
2801
2802  if (!isa<BasicBlock>(Op1))
2803    return Error(Loc, "true destination of branch must be a basic block");
2804  if (!isa<BasicBlock>(Op2))
2805    return Error(Loc2, "true destination of branch must be a basic block");
2806
2807  Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2808  return false;
2809}
2810
2811/// ParseSwitch
2812///  Instruction
2813///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2814///  JumpTable
2815///    ::= (TypeAndValue ',' TypeAndValue)*
2816bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2817  LocTy CondLoc, BBLoc;
2818  Value *Cond, *DefaultBB;
2819  if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2820      ParseToken(lltok::comma, "expected ',' after switch condition") ||
2821      ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2822      ParseToken(lltok::lsquare, "expected '[' with switch table"))
2823    return true;
2824
2825  if (!isa<IntegerType>(Cond->getType()))
2826    return Error(CondLoc, "switch condition must have integer type");
2827  if (!isa<BasicBlock>(DefaultBB))
2828    return Error(BBLoc, "default destination must be a basic block");
2829
2830  // Parse the jump table pairs.
2831  SmallPtrSet<Value*, 32> SeenCases;
2832  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2833  while (Lex.getKind() != lltok::rsquare) {
2834    Value *Constant, *DestBB;
2835
2836    if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2837        ParseToken(lltok::comma, "expected ',' after case value") ||
2838        ParseTypeAndValue(DestBB, BBLoc, PFS))
2839      return true;
2840
2841    if (!SeenCases.insert(Constant))
2842      return Error(CondLoc, "duplicate case value in switch");
2843    if (!isa<ConstantInt>(Constant))
2844      return Error(CondLoc, "case value is not a constant integer");
2845    if (!isa<BasicBlock>(DestBB))
2846      return Error(BBLoc, "case destination is not a basic block");
2847
2848    Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2849                                   cast<BasicBlock>(DestBB)));
2850  }
2851
2852  Lex.Lex();  // Eat the ']'.
2853
2854  SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2855                                      Table.size());
2856  for (unsigned i = 0, e = Table.size(); i != e; ++i)
2857    SI->addCase(Table[i].first, Table[i].second);
2858  Inst = SI;
2859  return false;
2860}
2861
2862/// ParseInvoke
2863///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2864///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2865bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2866  LocTy CallLoc = Lex.getLoc();
2867  unsigned CC, RetAttrs, FnAttrs;
2868  PATypeHolder RetType(Type::VoidTy);
2869  LocTy RetTypeLoc;
2870  ValID CalleeID;
2871  SmallVector<ParamInfo, 16> ArgList;
2872
2873  Value *NormalBB, *UnwindBB;
2874  if (ParseOptionalCallingConv(CC) ||
2875      ParseOptionalAttrs(RetAttrs, 1) ||
2876      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2877      ParseValID(CalleeID) ||
2878      ParseParameterList(ArgList, PFS) ||
2879      ParseOptionalAttrs(FnAttrs, 2) ||
2880      ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2881      ParseTypeAndValue(NormalBB, PFS) ||
2882      ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2883      ParseTypeAndValue(UnwindBB, PFS))
2884    return true;
2885
2886  if (!isa<BasicBlock>(NormalBB))
2887    return Error(CallLoc, "normal destination is not a basic block");
2888  if (!isa<BasicBlock>(UnwindBB))
2889    return Error(CallLoc, "unwind destination is not a basic block");
2890
2891  // If RetType is a non-function pointer type, then this is the short syntax
2892  // for the call, which means that RetType is just the return type.  Infer the
2893  // rest of the function argument types from the arguments that are present.
2894  const PointerType *PFTy = 0;
2895  const FunctionType *Ty = 0;
2896  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2897      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2898    // Pull out the types of all of the arguments...
2899    std::vector<const Type*> ParamTypes;
2900    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2901      ParamTypes.push_back(ArgList[i].V->getType());
2902
2903    if (!FunctionType::isValidReturnType(RetType))
2904      return Error(RetTypeLoc, "Invalid result type for LLVM function");
2905
2906    Ty = Context.getFunctionType(RetType, ParamTypes, false);
2907    PFTy = Context.getPointerTypeUnqual(Ty);
2908  }
2909
2910  // Look up the callee.
2911  Value *Callee;
2912  if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2913
2914  // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2915  // function attributes.
2916  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2917  if (FnAttrs & ObsoleteFuncAttrs) {
2918    RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2919    FnAttrs &= ~ObsoleteFuncAttrs;
2920  }
2921
2922  // Set up the Attributes for the function.
2923  SmallVector<AttributeWithIndex, 8> Attrs;
2924  if (RetAttrs != Attribute::None)
2925    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2926
2927  SmallVector<Value*, 8> Args;
2928
2929  // Loop through FunctionType's arguments and ensure they are specified
2930  // correctly.  Also, gather any parameter attributes.
2931  FunctionType::param_iterator I = Ty->param_begin();
2932  FunctionType::param_iterator E = Ty->param_end();
2933  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2934    const Type *ExpectedTy = 0;
2935    if (I != E) {
2936      ExpectedTy = *I++;
2937    } else if (!Ty->isVarArg()) {
2938      return Error(ArgList[i].Loc, "too many arguments specified");
2939    }
2940
2941    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2942      return Error(ArgList[i].Loc, "argument is not of expected type '" +
2943                   ExpectedTy->getDescription() + "'");
2944    Args.push_back(ArgList[i].V);
2945    if (ArgList[i].Attrs != Attribute::None)
2946      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2947  }
2948
2949  if (I != E)
2950    return Error(CallLoc, "not enough parameters specified for call");
2951
2952  if (FnAttrs != Attribute::None)
2953    Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2954
2955  // Finish off the Attributes and check them
2956  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2957
2958  InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2959                                      cast<BasicBlock>(UnwindBB),
2960                                      Args.begin(), Args.end());
2961  II->setCallingConv(CC);
2962  II->setAttributes(PAL);
2963  Inst = II;
2964  return false;
2965}
2966
2967
2968
2969//===----------------------------------------------------------------------===//
2970// Binary Operators.
2971//===----------------------------------------------------------------------===//
2972
2973/// ParseArithmetic
2974///  ::= ArithmeticOps TypeAndValue ',' Value
2975///
2976/// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
2977/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2978bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2979                               unsigned Opc, unsigned OperandType) {
2980  LocTy Loc; Value *LHS, *RHS;
2981  if (ParseTypeAndValue(LHS, Loc, PFS) ||
2982      ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2983      ParseValue(LHS->getType(), RHS, PFS))
2984    return true;
2985
2986  bool Valid;
2987  switch (OperandType) {
2988  default: llvm_unreachable("Unknown operand type!");
2989  case 0: // int or FP.
2990    Valid = LHS->getType()->isIntOrIntVector() ||
2991            LHS->getType()->isFPOrFPVector();
2992    break;
2993  case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2994  case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2995  }
2996
2997  if (!Valid)
2998    return Error(Loc, "invalid operand type for instruction");
2999
3000  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3001  return false;
3002}
3003
3004/// ParseLogical
3005///  ::= ArithmeticOps TypeAndValue ',' Value {
3006bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3007                            unsigned Opc) {
3008  LocTy Loc; Value *LHS, *RHS;
3009  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3010      ParseToken(lltok::comma, "expected ',' in logical operation") ||
3011      ParseValue(LHS->getType(), RHS, PFS))
3012    return true;
3013
3014  if (!LHS->getType()->isIntOrIntVector())
3015    return Error(Loc,"instruction requires integer or integer vector operands");
3016
3017  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3018  return false;
3019}
3020
3021
3022/// ParseCompare
3023///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3024///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3025bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3026                            unsigned Opc) {
3027  // Parse the integer/fp comparison predicate.
3028  LocTy Loc;
3029  unsigned Pred;
3030  Value *LHS, *RHS;
3031  if (ParseCmpPredicate(Pred, Opc) ||
3032      ParseTypeAndValue(LHS, Loc, PFS) ||
3033      ParseToken(lltok::comma, "expected ',' after compare value") ||
3034      ParseValue(LHS->getType(), RHS, PFS))
3035    return true;
3036
3037  if (Opc == Instruction::FCmp) {
3038    if (!LHS->getType()->isFPOrFPVector())
3039      return Error(Loc, "fcmp requires floating point operands");
3040    Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3041  } else {
3042    assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3043    if (!LHS->getType()->isIntOrIntVector() &&
3044        !isa<PointerType>(LHS->getType()))
3045      return Error(Loc, "icmp requires integer operands");
3046    Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3047  }
3048  return false;
3049}
3050
3051//===----------------------------------------------------------------------===//
3052// Other Instructions.
3053//===----------------------------------------------------------------------===//
3054
3055
3056/// ParseCast
3057///   ::= CastOpc TypeAndValue 'to' Type
3058bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3059                         unsigned Opc) {
3060  LocTy Loc;  Value *Op;
3061  PATypeHolder DestTy(Type::VoidTy);
3062  if (ParseTypeAndValue(Op, Loc, PFS) ||
3063      ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3064      ParseType(DestTy))
3065    return true;
3066
3067  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3068    CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3069    return Error(Loc, "invalid cast opcode for cast from '" +
3070                 Op->getType()->getDescription() + "' to '" +
3071                 DestTy->getDescription() + "'");
3072  }
3073  Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3074  return false;
3075}
3076
3077/// ParseSelect
3078///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3079bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3080  LocTy Loc;
3081  Value *Op0, *Op1, *Op2;
3082  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3083      ParseToken(lltok::comma, "expected ',' after select condition") ||
3084      ParseTypeAndValue(Op1, PFS) ||
3085      ParseToken(lltok::comma, "expected ',' after select value") ||
3086      ParseTypeAndValue(Op2, PFS))
3087    return true;
3088
3089  if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3090    return Error(Loc, Reason);
3091
3092  Inst = SelectInst::Create(Op0, Op1, Op2);
3093  return false;
3094}
3095
3096/// ParseVA_Arg
3097///   ::= 'va_arg' TypeAndValue ',' Type
3098bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3099  Value *Op;
3100  PATypeHolder EltTy(Type::VoidTy);
3101  LocTy TypeLoc;
3102  if (ParseTypeAndValue(Op, PFS) ||
3103      ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3104      ParseType(EltTy, TypeLoc))
3105    return true;
3106
3107  if (!EltTy->isFirstClassType())
3108    return Error(TypeLoc, "va_arg requires operand with first class type");
3109
3110  Inst = new VAArgInst(Op, EltTy);
3111  return false;
3112}
3113
3114/// ParseExtractElement
3115///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3116bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3117  LocTy Loc;
3118  Value *Op0, *Op1;
3119  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3120      ParseToken(lltok::comma, "expected ',' after extract value") ||
3121      ParseTypeAndValue(Op1, PFS))
3122    return true;
3123
3124  if (!ExtractElementInst::isValidOperands(Op0, Op1))
3125    return Error(Loc, "invalid extractelement operands");
3126
3127  Inst = ExtractElementInst::Create(Op0, Op1);
3128  return false;
3129}
3130
3131/// ParseInsertElement
3132///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3133bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3134  LocTy Loc;
3135  Value *Op0, *Op1, *Op2;
3136  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3137      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3138      ParseTypeAndValue(Op1, PFS) ||
3139      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3140      ParseTypeAndValue(Op2, PFS))
3141    return true;
3142
3143  if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3144    return Error(Loc, "invalid insertelement operands");
3145
3146  Inst = InsertElementInst::Create(Op0, Op1, Op2);
3147  return false;
3148}
3149
3150/// ParseShuffleVector
3151///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3152bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3153  LocTy Loc;
3154  Value *Op0, *Op1, *Op2;
3155  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3156      ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3157      ParseTypeAndValue(Op1, PFS) ||
3158      ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3159      ParseTypeAndValue(Op2, PFS))
3160    return true;
3161
3162  if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3163    return Error(Loc, "invalid extractelement operands");
3164
3165  Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3166  return false;
3167}
3168
3169/// ParsePHI
3170///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3171bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3172  PATypeHolder Ty(Type::VoidTy);
3173  Value *Op0, *Op1;
3174  LocTy TypeLoc = Lex.getLoc();
3175
3176  if (ParseType(Ty) ||
3177      ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3178      ParseValue(Ty, Op0, PFS) ||
3179      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3180      ParseValue(Type::LabelTy, Op1, PFS) ||
3181      ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3182    return true;
3183
3184  SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3185  while (1) {
3186    PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3187
3188    if (!EatIfPresent(lltok::comma))
3189      break;
3190
3191    if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3192        ParseValue(Ty, Op0, PFS) ||
3193        ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3194        ParseValue(Type::LabelTy, Op1, PFS) ||
3195        ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3196      return true;
3197  }
3198
3199  if (!Ty->isFirstClassType())
3200    return Error(TypeLoc, "phi node must have first class type");
3201
3202  PHINode *PN = PHINode::Create(Ty);
3203  PN->reserveOperandSpace(PHIVals.size());
3204  for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3205    PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3206  Inst = PN;
3207  return false;
3208}
3209
3210/// ParseCall
3211///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3212///       ParameterList OptionalAttrs
3213bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3214                         bool isTail) {
3215  unsigned CC, RetAttrs, FnAttrs;
3216  PATypeHolder RetType(Type::VoidTy);
3217  LocTy RetTypeLoc;
3218  ValID CalleeID;
3219  SmallVector<ParamInfo, 16> ArgList;
3220  LocTy CallLoc = Lex.getLoc();
3221
3222  if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3223      ParseOptionalCallingConv(CC) ||
3224      ParseOptionalAttrs(RetAttrs, 1) ||
3225      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3226      ParseValID(CalleeID) ||
3227      ParseParameterList(ArgList, PFS) ||
3228      ParseOptionalAttrs(FnAttrs, 2))
3229    return true;
3230
3231  // If RetType is a non-function pointer type, then this is the short syntax
3232  // for the call, which means that RetType is just the return type.  Infer the
3233  // rest of the function argument types from the arguments that are present.
3234  const PointerType *PFTy = 0;
3235  const FunctionType *Ty = 0;
3236  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3237      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3238    // Pull out the types of all of the arguments...
3239    std::vector<const Type*> ParamTypes;
3240    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3241      ParamTypes.push_back(ArgList[i].V->getType());
3242
3243    if (!FunctionType::isValidReturnType(RetType))
3244      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3245
3246    Ty = Context.getFunctionType(RetType, ParamTypes, false);
3247    PFTy = Context.getPointerTypeUnqual(Ty);
3248  }
3249
3250  // Look up the callee.
3251  Value *Callee;
3252  if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3253
3254  // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3255  // function attributes.
3256  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3257  if (FnAttrs & ObsoleteFuncAttrs) {
3258    RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3259    FnAttrs &= ~ObsoleteFuncAttrs;
3260  }
3261
3262  // Set up the Attributes for the function.
3263  SmallVector<AttributeWithIndex, 8> Attrs;
3264  if (RetAttrs != Attribute::None)
3265    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3266
3267  SmallVector<Value*, 8> Args;
3268
3269  // Loop through FunctionType's arguments and ensure they are specified
3270  // correctly.  Also, gather any parameter attributes.
3271  FunctionType::param_iterator I = Ty->param_begin();
3272  FunctionType::param_iterator E = Ty->param_end();
3273  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3274    const Type *ExpectedTy = 0;
3275    if (I != E) {
3276      ExpectedTy = *I++;
3277    } else if (!Ty->isVarArg()) {
3278      return Error(ArgList[i].Loc, "too many arguments specified");
3279    }
3280
3281    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3282      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3283                   ExpectedTy->getDescription() + "'");
3284    Args.push_back(ArgList[i].V);
3285    if (ArgList[i].Attrs != Attribute::None)
3286      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3287  }
3288
3289  if (I != E)
3290    return Error(CallLoc, "not enough parameters specified for call");
3291
3292  if (FnAttrs != Attribute::None)
3293    Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3294
3295  // Finish off the Attributes and check them
3296  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3297
3298  CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3299  CI->setTailCall(isTail);
3300  CI->setCallingConv(CC);
3301  CI->setAttributes(PAL);
3302  Inst = CI;
3303  return false;
3304}
3305
3306//===----------------------------------------------------------------------===//
3307// Memory Instructions.
3308//===----------------------------------------------------------------------===//
3309
3310/// ParseAlloc
3311///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3312///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3313bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3314                          unsigned Opc) {
3315  PATypeHolder Ty(Type::VoidTy);
3316  Value *Size = 0;
3317  LocTy SizeLoc;
3318  unsigned Alignment = 0;
3319  if (ParseType(Ty)) return true;
3320
3321  if (EatIfPresent(lltok::comma)) {
3322    if (Lex.getKind() == lltok::kw_align) {
3323      if (ParseOptionalAlignment(Alignment)) return true;
3324    } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3325               ParseOptionalCommaAlignment(Alignment)) {
3326      return true;
3327    }
3328  }
3329
3330  if (Size && Size->getType() != Type::Int32Ty)
3331    return Error(SizeLoc, "element count must be i32");
3332
3333  if (Opc == Instruction::Malloc)
3334    Inst = new MallocInst(Ty, Size, Alignment);
3335  else
3336    Inst = new AllocaInst(Ty, Size, Alignment);
3337  return false;
3338}
3339
3340/// ParseFree
3341///   ::= 'free' TypeAndValue
3342bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3343  Value *Val; LocTy Loc;
3344  if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3345  if (!isa<PointerType>(Val->getType()))
3346    return Error(Loc, "operand to free must be a pointer");
3347  Inst = new FreeInst(Val);
3348  return false;
3349}
3350
3351/// ParseLoad
3352///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3353bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3354                         bool isVolatile) {
3355  Value *Val; LocTy Loc;
3356  unsigned Alignment;
3357  if (ParseTypeAndValue(Val, Loc, PFS) ||
3358      ParseOptionalCommaAlignment(Alignment))
3359    return true;
3360
3361  if (!isa<PointerType>(Val->getType()) ||
3362      !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3363    return Error(Loc, "load operand must be a pointer to a first class type");
3364
3365  Inst = new LoadInst(Val, "", isVolatile, Alignment);
3366  return false;
3367}
3368
3369/// ParseStore
3370///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3371bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3372                          bool isVolatile) {
3373  Value *Val, *Ptr; LocTy Loc, PtrLoc;
3374  unsigned Alignment;
3375  if (ParseTypeAndValue(Val, Loc, PFS) ||
3376      ParseToken(lltok::comma, "expected ',' after store operand") ||
3377      ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3378      ParseOptionalCommaAlignment(Alignment))
3379    return true;
3380
3381  if (!isa<PointerType>(Ptr->getType()))
3382    return Error(PtrLoc, "store operand must be a pointer");
3383  if (!Val->getType()->isFirstClassType())
3384    return Error(Loc, "store operand must be a first class value");
3385  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3386    return Error(Loc, "stored value and pointer type do not match");
3387
3388  Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3389  return false;
3390}
3391
3392/// ParseGetResult
3393///   ::= 'getresult' TypeAndValue ',' i32
3394/// FIXME: Remove support for getresult in LLVM 3.0
3395bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3396  Value *Val; LocTy ValLoc, EltLoc;
3397  unsigned Element;
3398  if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3399      ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3400      ParseUInt32(Element, EltLoc))
3401    return true;
3402
3403  if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3404    return Error(ValLoc, "getresult inst requires an aggregate operand");
3405  if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3406    return Error(EltLoc, "invalid getresult index for value");
3407  Inst = ExtractValueInst::Create(Val, Element);
3408  return false;
3409}
3410
3411/// ParseGetElementPtr
3412///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3413bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3414  Value *Ptr, *Val; LocTy Loc, EltLoc;
3415
3416  bool InBounds = EatIfPresent(lltok::kw_inbounds);
3417
3418  if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3419
3420  if (!isa<PointerType>(Ptr->getType()))
3421    return Error(Loc, "base of getelementptr must be a pointer");
3422
3423  SmallVector<Value*, 16> Indices;
3424  while (EatIfPresent(lltok::comma)) {
3425    if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3426    if (!isa<IntegerType>(Val->getType()))
3427      return Error(EltLoc, "getelementptr index must be an integer");
3428    Indices.push_back(Val);
3429  }
3430
3431  if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3432                                         Indices.begin(), Indices.end()))
3433    return Error(Loc, "invalid getelementptr indices");
3434  Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3435  if (InBounds)
3436    cast<GEPOperator>(Inst)->setIsInBounds(true);
3437  return false;
3438}
3439
3440/// ParseExtractValue
3441///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3442bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3443  Value *Val; LocTy Loc;
3444  SmallVector<unsigned, 4> Indices;
3445  if (ParseTypeAndValue(Val, Loc, PFS) ||
3446      ParseIndexList(Indices))
3447    return true;
3448
3449  if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3450    return Error(Loc, "extractvalue operand must be array or struct");
3451
3452  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3453                                        Indices.end()))
3454    return Error(Loc, "invalid indices for extractvalue");
3455  Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3456  return false;
3457}
3458
3459/// ParseInsertValue
3460///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3461bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3462  Value *Val0, *Val1; LocTy Loc0, Loc1;
3463  SmallVector<unsigned, 4> Indices;
3464  if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3465      ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3466      ParseTypeAndValue(Val1, Loc1, PFS) ||
3467      ParseIndexList(Indices))
3468    return true;
3469
3470  if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3471    return Error(Loc0, "extractvalue operand must be array or struct");
3472
3473  if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3474                                        Indices.end()))
3475    return Error(Loc0, "invalid indices for insertvalue");
3476  Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3477  return false;
3478}
3479
3480//===----------------------------------------------------------------------===//
3481// Embedded metadata.
3482//===----------------------------------------------------------------------===//
3483
3484/// ParseMDNodeVector
3485///   ::= Element (',' Element)*
3486/// Element
3487///   ::= 'null' | TypeAndValue
3488bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3489  assert(Lex.getKind() == lltok::lbrace);
3490  Lex.Lex();
3491  do {
3492    Value *V = 0;
3493    if (Lex.getKind() == lltok::kw_null) {
3494      Lex.Lex();
3495      V = 0;
3496    } else {
3497      PATypeHolder Ty(Type::VoidTy);
3498      if (ParseType(Ty)) return true;
3499      if (Lex.getKind() == lltok::Metadata) {
3500        Lex.Lex();
3501        MetadataBase *Node = 0;
3502        if (!ParseMDNode(Node))
3503          V = Node;
3504        else {
3505          MetadataBase *MDS = 0;
3506          if (ParseMDString(MDS)) return true;
3507          V = MDS;
3508        }
3509      } else {
3510        Constant *C;
3511        if (ParseGlobalValue(Ty, C)) return true;
3512        V = C;
3513      }
3514    }
3515    Elts.push_back(V);
3516  } while (EatIfPresent(lltok::comma));
3517
3518  return false;
3519}
3520