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