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