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