LLParser.cpp revision 212904
1193323Sed//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed//  This file defines the parser class for .ll files.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#include "LLParser.h"
15193323Sed#include "llvm/AutoUpgrade.h"
16193323Sed#include "llvm/CallingConv.h"
17193323Sed#include "llvm/Constants.h"
18193323Sed#include "llvm/DerivedTypes.h"
19193323Sed#include "llvm/InlineAsm.h"
20193323Sed#include "llvm/Instructions.h"
21193323Sed#include "llvm/Module.h"
22198090Srdivacky#include "llvm/Operator.h"
23193323Sed#include "llvm/ValueSymbolTable.h"
24193323Sed#include "llvm/ADT/SmallPtrSet.h"
25193323Sed#include "llvm/ADT/StringExtras.h"
26198090Srdivacky#include "llvm/Support/ErrorHandling.h"
27193323Sed#include "llvm/Support/raw_ostream.h"
28193323Sedusing namespace llvm;
29193323Sed
30193323Sed/// Run: module ::= toplevelentity*
31193323Sedbool LLParser::Run() {
32193323Sed  // Prime the lexer.
33193323Sed  Lex.Lex();
34193323Sed
35193323Sed  return ParseTopLevelEntities() ||
36193323Sed         ValidateEndOfModule();
37193323Sed}
38193323Sed
39193323Sed/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40193323Sed/// module.
41193323Sedbool LLParser::ValidateEndOfModule() {
42206083Srdivacky  // Handle any instruction metadata forward references.
43206083Srdivacky  if (!ForwardRefInstMetadata.empty()) {
44206083Srdivacky    for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45206083Srdivacky         I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46206083Srdivacky         I != E; ++I) {
47206083Srdivacky      Instruction *Inst = I->first;
48206083Srdivacky      const std::vector<MDRef> &MDList = I->second;
49206083Srdivacky
50206083Srdivacky      for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51206083Srdivacky        unsigned SlotNo = MDList[i].MDSlot;
52206083Srdivacky
53206083Srdivacky        if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54206083Srdivacky          return Error(MDList[i].Loc, "use of undefined metadata '!" +
55206083Srdivacky                       utostr(SlotNo) + "'");
56206083Srdivacky        Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
57206083Srdivacky      }
58206083Srdivacky    }
59206083Srdivacky    ForwardRefInstMetadata.clear();
60206083Srdivacky  }
61206083Srdivacky
62206083Srdivacky
63198396Srdivacky  // Update auto-upgraded malloc calls to "malloc".
64198396Srdivacky  // FIXME: Remove in LLVM 3.0.
65198396Srdivacky  if (MallocF) {
66198396Srdivacky    MallocF->setName("malloc");
67198396Srdivacky    // If setName() does not set the name to "malloc", then there is already a
68198396Srdivacky    // declaration of "malloc".  In that case, iterate over all calls to MallocF
69198396Srdivacky    // and get them to call the declared "malloc" instead.
70198396Srdivacky    if (MallocF->getName() != "malloc") {
71198892Srdivacky      Constant *RealMallocF = M->getFunction("malloc");
72198396Srdivacky      if (RealMallocF->getType() != MallocF->getType())
73198396Srdivacky        RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74198396Srdivacky      MallocF->replaceAllUsesWith(RealMallocF);
75198396Srdivacky      MallocF->eraseFromParent();
76198396Srdivacky      MallocF = NULL;
77198396Srdivacky    }
78198396Srdivacky  }
79198892Srdivacky
80198892Srdivacky
81198892Srdivacky  // If there are entries in ForwardRefBlockAddresses at this point, they are
82198892Srdivacky  // references after the function was defined.  Resolve those now.
83198892Srdivacky  while (!ForwardRefBlockAddresses.empty()) {
84198892Srdivacky    // Okay, we are referencing an already-parsed function, resolve them now.
85198892Srdivacky    Function *TheFn = 0;
86198892Srdivacky    const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87198892Srdivacky    if (Fn.Kind == ValID::t_GlobalName)
88198892Srdivacky      TheFn = M->getFunction(Fn.StrVal);
89198892Srdivacky    else if (Fn.UIntVal < NumberedVals.size())
90198892Srdivacky      TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
91198892Srdivacky
92198892Srdivacky    if (TheFn == 0)
93198892Srdivacky      return Error(Fn.Loc, "unknown function referenced by blockaddress");
94198892Srdivacky
95198892Srdivacky    // Resolve all these references.
96198892Srdivacky    if (ResolveForwardRefBlockAddresses(TheFn,
97198892Srdivacky                                      ForwardRefBlockAddresses.begin()->second,
98198892Srdivacky                                        0))
99198892Srdivacky      return true;
100198892Srdivacky
101198892Srdivacky    ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
102198892Srdivacky  }
103198892Srdivacky
104198892Srdivacky
105193323Sed  if (!ForwardRefTypes.empty())
106193323Sed    return Error(ForwardRefTypes.begin()->second.second,
107193323Sed                 "use of undefined type named '" +
108193323Sed                 ForwardRefTypes.begin()->first + "'");
109193323Sed  if (!ForwardRefTypeIDs.empty())
110193323Sed    return Error(ForwardRefTypeIDs.begin()->second.second,
111193323Sed                 "use of undefined type '%" +
112193323Sed                 utostr(ForwardRefTypeIDs.begin()->first) + "'");
113198090Srdivacky
114193323Sed  if (!ForwardRefVals.empty())
115193323Sed    return Error(ForwardRefVals.begin()->second.second,
116193323Sed                 "use of undefined value '@" + ForwardRefVals.begin()->first +
117193323Sed                 "'");
118198090Srdivacky
119193323Sed  if (!ForwardRefValIDs.empty())
120193323Sed    return Error(ForwardRefValIDs.begin()->second.second,
121193323Sed                 "use of undefined value '@" +
122193323Sed                 utostr(ForwardRefValIDs.begin()->first) + "'");
123198090Srdivacky
124198090Srdivacky  if (!ForwardRefMDNodes.empty())
125198090Srdivacky    return Error(ForwardRefMDNodes.begin()->second.second,
126198090Srdivacky                 "use of undefined metadata '!" +
127198090Srdivacky                 utostr(ForwardRefMDNodes.begin()->first) + "'");
128198090Srdivacky
129198090Srdivacky
130193323Sed  // Look for intrinsic functions and CallInst that need to be upgraded
131193323Sed  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132193323Sed    UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
133198090Srdivacky
134198090Srdivacky  // Check debug info intrinsics.
135198090Srdivacky  CheckDebugInfoIntrinsics(M);
136193323Sed  return false;
137193323Sed}
138193323Sed
139198892Srdivackybool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140198892Srdivacky                             std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141198892Srdivacky                                               PerFunctionState *PFS) {
142198892Srdivacky  // Loop over all the references, resolving them.
143198892Srdivacky  for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
144198892Srdivacky    BasicBlock *Res;
145198892Srdivacky    if (PFS) {
146198892Srdivacky      if (Refs[i].first.Kind == ValID::t_LocalName)
147198892Srdivacky        Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
148198892Srdivacky      else
149198892Srdivacky        Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150198892Srdivacky    } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151198892Srdivacky      return Error(Refs[i].first.Loc,
152198892Srdivacky       "cannot take address of numeric label after the function is defined");
153198892Srdivacky    } else {
154198892Srdivacky      Res = dyn_cast_or_null<BasicBlock>(
155198892Srdivacky                     TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
156198892Srdivacky    }
157198892Srdivacky
158198892Srdivacky    if (Res == 0)
159198892Srdivacky      return Error(Refs[i].first.Loc,
160198892Srdivacky                   "referenced value is not a basic block");
161198892Srdivacky
162198892Srdivacky    // Get the BlockAddress for this and update references to use it.
163198892Srdivacky    BlockAddress *BA = BlockAddress::get(TheFn, Res);
164198892Srdivacky    Refs[i].second->replaceAllUsesWith(BA);
165198892Srdivacky    Refs[i].second->eraseFromParent();
166198892Srdivacky  }
167198892Srdivacky  return false;
168198892Srdivacky}
169198892Srdivacky
170198892Srdivacky
171193323Sed//===----------------------------------------------------------------------===//
172193323Sed// Top-Level Entities
173193323Sed//===----------------------------------------------------------------------===//
174193323Sed
175193323Sedbool LLParser::ParseTopLevelEntities() {
176193323Sed  while (1) {
177193323Sed    switch (Lex.getKind()) {
178193323Sed    default:         return TokError("expected top-level entity");
179193323Sed    case lltok::Eof: return false;
180193323Sed    //case lltok::kw_define:
181193323Sed    case lltok::kw_declare: if (ParseDeclare()) return true; break;
182193323Sed    case lltok::kw_define:  if (ParseDefine()) return true; break;
183193323Sed    case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
184193323Sed    case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
185193323Sed    case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186193323Sed    case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
187198090Srdivacky    case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
188193323Sed    case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189193323Sed    case lltok::LocalVar:   if (ParseNamedType()) return true; break;
190198090Srdivacky    case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
191193323Sed    case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
192201360Srdivacky    case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
193201360Srdivacky    case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
194193323Sed
195193323Sed    // The Global variable production with no name can have many different
196193323Sed    // optional leading prefixes, the production is:
197193323Sed    // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198193323Sed    //               OptionalAddrSpace ('constant'|'global') ...
199210299Sed    case lltok::kw_private:             // OptionalLinkage
200210299Sed    case lltok::kw_linker_private:      // OptionalLinkage
201210299Sed    case lltok::kw_linker_private_weak: // OptionalLinkage
202212904Sdim    case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
203210299Sed    case lltok::kw_internal:            // OptionalLinkage
204210299Sed    case lltok::kw_weak:                // OptionalLinkage
205210299Sed    case lltok::kw_weak_odr:            // OptionalLinkage
206210299Sed    case lltok::kw_linkonce:            // OptionalLinkage
207210299Sed    case lltok::kw_linkonce_odr:        // OptionalLinkage
208210299Sed    case lltok::kw_appending:           // OptionalLinkage
209210299Sed    case lltok::kw_dllexport:           // OptionalLinkage
210210299Sed    case lltok::kw_common:              // OptionalLinkage
211210299Sed    case lltok::kw_dllimport:           // OptionalLinkage
212210299Sed    case lltok::kw_extern_weak:         // OptionalLinkage
213210299Sed    case lltok::kw_external: {          // OptionalLinkage
214193323Sed      unsigned Linkage, Visibility;
215193323Sed      if (ParseOptionalLinkage(Linkage) ||
216193323Sed          ParseOptionalVisibility(Visibility) ||
217195340Sed          ParseGlobal("", SMLoc(), Linkage, true, Visibility))
218193323Sed        return true;
219193323Sed      break;
220193323Sed    }
221193323Sed    case lltok::kw_default:       // OptionalVisibility
222193323Sed    case lltok::kw_hidden:        // OptionalVisibility
223193323Sed    case lltok::kw_protected: {   // OptionalVisibility
224193323Sed      unsigned Visibility;
225193323Sed      if (ParseOptionalVisibility(Visibility) ||
226195340Sed          ParseGlobal("", SMLoc(), 0, false, Visibility))
227193323Sed        return true;
228193323Sed      break;
229193323Sed    }
230198090Srdivacky
231193323Sed    case lltok::kw_thread_local:  // OptionalThreadLocal
232193323Sed    case lltok::kw_addrspace:     // OptionalAddrSpace
233193323Sed    case lltok::kw_constant:      // GlobalType
234193323Sed    case lltok::kw_global:        // GlobalType
235195340Sed      if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
236193323Sed      break;
237193323Sed    }
238193323Sed  }
239193323Sed}
240193323Sed
241193323Sed
242193323Sed/// toplevelentity
243193323Sed///   ::= 'module' 'asm' STRINGCONSTANT
244193323Sedbool LLParser::ParseModuleAsm() {
245193323Sed  assert(Lex.getKind() == lltok::kw_module);
246193323Sed  Lex.Lex();
247198090Srdivacky
248198090Srdivacky  std::string AsmStr;
249193323Sed  if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
250193323Sed      ParseStringConstant(AsmStr)) return true;
251198090Srdivacky
252193323Sed  const std::string &AsmSoFar = M->getModuleInlineAsm();
253193323Sed  if (AsmSoFar.empty())
254193323Sed    M->setModuleInlineAsm(AsmStr);
255193323Sed  else
256193323Sed    M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
257193323Sed  return false;
258193323Sed}
259193323Sed
260193323Sed/// toplevelentity
261193323Sed///   ::= 'target' 'triple' '=' STRINGCONSTANT
262193323Sed///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
263193323Sedbool LLParser::ParseTargetDefinition() {
264193323Sed  assert(Lex.getKind() == lltok::kw_target);
265193323Sed  std::string Str;
266193323Sed  switch (Lex.Lex()) {
267193323Sed  default: return TokError("unknown target property");
268193323Sed  case lltok::kw_triple:
269193323Sed    Lex.Lex();
270193323Sed    if (ParseToken(lltok::equal, "expected '=' after target triple") ||
271193323Sed        ParseStringConstant(Str))
272193323Sed      return true;
273193323Sed    M->setTargetTriple(Str);
274193323Sed    return false;
275193323Sed  case lltok::kw_datalayout:
276193323Sed    Lex.Lex();
277193323Sed    if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
278193323Sed        ParseStringConstant(Str))
279193323Sed      return true;
280193323Sed    M->setDataLayout(Str);
281193323Sed    return false;
282193323Sed  }
283193323Sed}
284193323Sed
285193323Sed/// toplevelentity
286193323Sed///   ::= 'deplibs' '=' '[' ']'
287193323Sed///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
288193323Sedbool LLParser::ParseDepLibs() {
289193323Sed  assert(Lex.getKind() == lltok::kw_deplibs);
290193323Sed  Lex.Lex();
291193323Sed  if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
292193323Sed      ParseToken(lltok::lsquare, "expected '=' after deplibs"))
293193323Sed    return true;
294193323Sed
295193323Sed  if (EatIfPresent(lltok::rsquare))
296193323Sed    return false;
297198090Srdivacky
298193323Sed  std::string Str;
299193323Sed  if (ParseStringConstant(Str)) return true;
300193323Sed  M->addLibrary(Str);
301193323Sed
302193323Sed  while (EatIfPresent(lltok::comma)) {
303193323Sed    if (ParseStringConstant(Str)) return true;
304193323Sed    M->addLibrary(Str);
305193323Sed  }
306193323Sed
307193323Sed  return ParseToken(lltok::rsquare, "expected ']' at end of list");
308193323Sed}
309193323Sed
310198090Srdivacky/// ParseUnnamedType:
311193323Sed///   ::= 'type' type
312198090Srdivacky///   ::= LocalVarID '=' 'type' type
313193323Sedbool LLParser::ParseUnnamedType() {
314198090Srdivacky  unsigned TypeID = NumberedTypes.size();
315198090Srdivacky
316198090Srdivacky  // Handle the LocalVarID form.
317198090Srdivacky  if (Lex.getKind() == lltok::LocalVarID) {
318198090Srdivacky    if (Lex.getUIntVal() != TypeID)
319198090Srdivacky      return Error(Lex.getLoc(), "type expected to be numbered '%" +
320198090Srdivacky                   utostr(TypeID) + "'");
321198090Srdivacky    Lex.Lex(); // eat LocalVarID;
322198090Srdivacky
323198090Srdivacky    if (ParseToken(lltok::equal, "expected '=' after name"))
324198090Srdivacky      return true;
325198090Srdivacky  }
326198090Srdivacky
327193323Sed  LocTy TypeLoc = Lex.getLoc();
328207618Srdivacky  if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
329193323Sed
330198090Srdivacky  PATypeHolder Ty(Type::getVoidTy(Context));
331193323Sed  if (ParseType(Ty)) return true;
332198090Srdivacky
333193323Sed  // See if this type was previously referenced.
334193323Sed  std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
335193323Sed    FI = ForwardRefTypeIDs.find(TypeID);
336193323Sed  if (FI != ForwardRefTypeIDs.end()) {
337193323Sed    if (FI->second.first.get() == Ty)
338193323Sed      return Error(TypeLoc, "self referential type is invalid");
339198090Srdivacky
340193323Sed    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
341193323Sed    Ty = FI->second.first.get();
342193323Sed    ForwardRefTypeIDs.erase(FI);
343193323Sed  }
344198090Srdivacky
345193323Sed  NumberedTypes.push_back(Ty);
346198090Srdivacky
347193323Sed  return false;
348193323Sed}
349193323Sed
350193323Sed/// toplevelentity
351193323Sed///   ::= LocalVar '=' 'type' type
352193323Sedbool LLParser::ParseNamedType() {
353193323Sed  std::string Name = Lex.getStrVal();
354193323Sed  LocTy NameLoc = Lex.getLoc();
355193323Sed  Lex.Lex();  // eat LocalVar.
356198090Srdivacky
357198090Srdivacky  PATypeHolder Ty(Type::getVoidTy(Context));
358198090Srdivacky
359193323Sed  if (ParseToken(lltok::equal, "expected '=' after name") ||
360193323Sed      ParseToken(lltok::kw_type, "expected 'type' after name") ||
361193323Sed      ParseType(Ty))
362193323Sed    return true;
363198090Srdivacky
364193323Sed  // Set the type name, checking for conflicts as we do so.
365193323Sed  bool AlreadyExists = M->addTypeName(Name, Ty);
366193323Sed  if (!AlreadyExists) return false;
367193323Sed
368193323Sed  // See if this type is a forward reference.  We need to eagerly resolve
369193323Sed  // types to allow recursive type redefinitions below.
370193323Sed  std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
371193323Sed  FI = ForwardRefTypes.find(Name);
372193323Sed  if (FI != ForwardRefTypes.end()) {
373193323Sed    if (FI->second.first.get() == Ty)
374193323Sed      return Error(NameLoc, "self referential type is invalid");
375193323Sed
376193323Sed    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
377193323Sed    Ty = FI->second.first.get();
378193323Sed    ForwardRefTypes.erase(FI);
379193323Sed  }
380198090Srdivacky
381193323Sed  // Inserting a name that is already defined, get the existing name.
382193323Sed  const Type *Existing = M->getTypeByName(Name);
383193323Sed  assert(Existing && "Conflict but no matching type?!");
384198090Srdivacky
385193323Sed  // Otherwise, this is an attempt to redefine a type. That's okay if
386193323Sed  // the redefinition is identical to the original.
387193323Sed  // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
388193323Sed  if (Existing == Ty) return false;
389198090Srdivacky
390193323Sed  // Any other kind of (non-equivalent) redefinition is an error.
391193323Sed  return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
392193323Sed               Ty->getDescription() + "'");
393193323Sed}
394193323Sed
395193323Sed
396193323Sed/// toplevelentity
397193323Sed///   ::= 'declare' FunctionHeader
398193323Sedbool LLParser::ParseDeclare() {
399193323Sed  assert(Lex.getKind() == lltok::kw_declare);
400193323Sed  Lex.Lex();
401198090Srdivacky
402193323Sed  Function *F;
403193323Sed  return ParseFunctionHeader(F, false);
404193323Sed}
405193323Sed
406193323Sed/// toplevelentity
407193323Sed///   ::= 'define' FunctionHeader '{' ...
408193323Sedbool LLParser::ParseDefine() {
409193323Sed  assert(Lex.getKind() == lltok::kw_define);
410193323Sed  Lex.Lex();
411198090Srdivacky
412193323Sed  Function *F;
413193323Sed  return ParseFunctionHeader(F, true) ||
414193323Sed         ParseFunctionBody(*F);
415193323Sed}
416193323Sed
417193323Sed/// ParseGlobalType
418193323Sed///   ::= 'constant'
419193323Sed///   ::= 'global'
420193323Sedbool LLParser::ParseGlobalType(bool &IsConstant) {
421193323Sed  if (Lex.getKind() == lltok::kw_constant)
422193323Sed    IsConstant = true;
423193323Sed  else if (Lex.getKind() == lltok::kw_global)
424193323Sed    IsConstant = false;
425193323Sed  else {
426193323Sed    IsConstant = false;
427193323Sed    return TokError("expected 'global' or 'constant'");
428193323Sed  }
429193323Sed  Lex.Lex();
430193323Sed  return false;
431193323Sed}
432193323Sed
433198090Srdivacky/// ParseUnnamedGlobal:
434198090Srdivacky///   OptionalVisibility ALIAS ...
435198090Srdivacky///   OptionalLinkage OptionalVisibility ...   -> global variable
436198090Srdivacky///   GlobalID '=' OptionalVisibility ALIAS ...
437198090Srdivacky///   GlobalID '=' OptionalLinkage OptionalVisibility ...   -> global variable
438198090Srdivackybool LLParser::ParseUnnamedGlobal() {
439198090Srdivacky  unsigned VarID = NumberedVals.size();
440198090Srdivacky  std::string Name;
441198090Srdivacky  LocTy NameLoc = Lex.getLoc();
442198090Srdivacky
443198090Srdivacky  // Handle the GlobalID form.
444198090Srdivacky  if (Lex.getKind() == lltok::GlobalID) {
445198090Srdivacky    if (Lex.getUIntVal() != VarID)
446198090Srdivacky      return Error(Lex.getLoc(), "variable expected to be numbered '%" +
447198090Srdivacky                   utostr(VarID) + "'");
448198090Srdivacky    Lex.Lex(); // eat GlobalID;
449198090Srdivacky
450198090Srdivacky    if (ParseToken(lltok::equal, "expected '=' after name"))
451198090Srdivacky      return true;
452198090Srdivacky  }
453198090Srdivacky
454198090Srdivacky  bool HasLinkage;
455198090Srdivacky  unsigned Linkage, Visibility;
456198090Srdivacky  if (ParseOptionalLinkage(Linkage, HasLinkage) ||
457198090Srdivacky      ParseOptionalVisibility(Visibility))
458198090Srdivacky    return true;
459198090Srdivacky
460198090Srdivacky  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
461198090Srdivacky    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
462198090Srdivacky  return ParseAlias(Name, NameLoc, Visibility);
463198090Srdivacky}
464198090Srdivacky
465193323Sed/// ParseNamedGlobal:
466193323Sed///   GlobalVar '=' OptionalVisibility ALIAS ...
467193323Sed///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
468193323Sedbool LLParser::ParseNamedGlobal() {
469193323Sed  assert(Lex.getKind() == lltok::GlobalVar);
470193323Sed  LocTy NameLoc = Lex.getLoc();
471193323Sed  std::string Name = Lex.getStrVal();
472193323Sed  Lex.Lex();
473198090Srdivacky
474193323Sed  bool HasLinkage;
475193323Sed  unsigned Linkage, Visibility;
476193323Sed  if (ParseToken(lltok::equal, "expected '=' in global variable") ||
477193323Sed      ParseOptionalLinkage(Linkage, HasLinkage) ||
478193323Sed      ParseOptionalVisibility(Visibility))
479193323Sed    return true;
480198090Srdivacky
481193323Sed  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
482193323Sed    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
483193323Sed  return ParseAlias(Name, NameLoc, Visibility);
484193323Sed}
485193323Sed
486198090Srdivacky// MDString:
487198090Srdivacky//   ::= '!' STRINGCONSTANT
488201360Srdivackybool LLParser::ParseMDString(MDString *&Result) {
489198090Srdivacky  std::string Str;
490198090Srdivacky  if (ParseStringConstant(Str)) return true;
491201360Srdivacky  Result = MDString::get(Context, Str);
492198090Srdivacky  return false;
493198090Srdivacky}
494198090Srdivacky
495198090Srdivacky// MDNode:
496198090Srdivacky//   ::= '!' MDNodeNumber
497206083Srdivacky//
498206083Srdivacky/// This version of ParseMDNodeID returns the slot number and null in the case
499206083Srdivacky/// of a forward reference.
500206083Srdivackybool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
501206083Srdivacky  // !{ ..., !42, ... }
502206083Srdivacky  if (ParseUInt32(SlotNo)) return true;
503206083Srdivacky
504206083Srdivacky  // Check existing MDNode.
505206083Srdivacky  if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
506206083Srdivacky    Result = NumberedMetadata[SlotNo];
507206083Srdivacky  else
508206083Srdivacky    Result = 0;
509206083Srdivacky  return false;
510206083Srdivacky}
511206083Srdivacky
512201360Srdivackybool LLParser::ParseMDNodeID(MDNode *&Result) {
513198090Srdivacky  // !{ ..., !42, ... }
514198090Srdivacky  unsigned MID = 0;
515206083Srdivacky  if (ParseMDNodeID(Result, MID)) return true;
516198090Srdivacky
517206083Srdivacky  // If not a forward reference, just return it now.
518206083Srdivacky  if (Result) return false;
519198090Srdivacky
520206083Srdivacky  // Otherwise, create MDNode forward reference.
521212904Sdim  MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
522198090Srdivacky  ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
523201360Srdivacky
524201360Srdivacky  if (NumberedMetadata.size() <= MID)
525201360Srdivacky    NumberedMetadata.resize(MID+1);
526201360Srdivacky  NumberedMetadata[MID] = FwdNode;
527201360Srdivacky  Result = FwdNode;
528198090Srdivacky  return false;
529198090Srdivacky}
530198090Srdivacky
531201360Srdivacky/// ParseNamedMetadata:
532198090Srdivacky///   !foo = !{ !1, !2 }
533198090Srdivackybool LLParser::ParseNamedMetadata() {
534201360Srdivacky  assert(Lex.getKind() == lltok::MetadataVar);
535201360Srdivacky  std::string Name = Lex.getStrVal();
536198090Srdivacky  Lex.Lex();
537198090Srdivacky
538201360Srdivacky  if (ParseToken(lltok::equal, "expected '=' here") ||
539201360Srdivacky      ParseToken(lltok::exclaim, "Expected '!' here") ||
540201360Srdivacky      ParseToken(lltok::lbrace, "Expected '{' here"))
541198090Srdivacky    return true;
542198090Srdivacky
543212904Sdim  NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
544210299Sed  if (Lex.getKind() != lltok::rbrace)
545210299Sed    do {
546210299Sed      if (ParseToken(lltok::exclaim, "Expected '!' here"))
547210299Sed        return true;
548201360Srdivacky
549210299Sed      MDNode *N = 0;
550210299Sed      if (ParseMDNodeID(N)) return true;
551212904Sdim      NMD->addOperand(N);
552210299Sed    } while (EatIfPresent(lltok::comma));
553198090Srdivacky
554198090Srdivacky  if (ParseToken(lltok::rbrace, "expected end of metadata node"))
555198090Srdivacky    return true;
556198090Srdivacky
557198090Srdivacky  return false;
558198090Srdivacky}
559198090Srdivacky
560195340Sed/// ParseStandaloneMetadata:
561198090Srdivacky///   !42 = !{...}
562195340Sedbool LLParser::ParseStandaloneMetadata() {
563201360Srdivacky  assert(Lex.getKind() == lltok::exclaim);
564195340Sed  Lex.Lex();
565195340Sed  unsigned MetadataID = 0;
566195340Sed
567195340Sed  LocTy TyLoc;
568198090Srdivacky  PATypeHolder Ty(Type::getVoidTy(Context));
569198090Srdivacky  SmallVector<Value *, 16> Elts;
570201360Srdivacky  if (ParseUInt32(MetadataID) ||
571201360Srdivacky      ParseToken(lltok::equal, "expected '=' here") ||
572201360Srdivacky      ParseType(Ty, TyLoc) ||
573201360Srdivacky      ParseToken(lltok::exclaim, "Expected '!' here") ||
574201360Srdivacky      ParseToken(lltok::lbrace, "Expected '{' here") ||
575202375Srdivacky      ParseMDNodeVector(Elts, NULL) ||
576201360Srdivacky      ParseToken(lltok::rbrace, "expected end of metadata node"))
577198090Srdivacky    return true;
578198090Srdivacky
579198090Srdivacky  MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
580201360Srdivacky
581201360Srdivacky  // See if this was forward referenced, if so, handle it.
582201360Srdivacky  std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
583198090Srdivacky    FI = ForwardRefMDNodes.find(MetadataID);
584198090Srdivacky  if (FI != ForwardRefMDNodes.end()) {
585212904Sdim    MDNode *Temp = FI->second.first;
586212904Sdim    Temp->replaceAllUsesWith(Init);
587212904Sdim    MDNode::deleteTemporary(Temp);
588198090Srdivacky    ForwardRefMDNodes.erase(FI);
589201360Srdivacky
590201360Srdivacky    assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
591201360Srdivacky  } else {
592201360Srdivacky    if (MetadataID >= NumberedMetadata.size())
593201360Srdivacky      NumberedMetadata.resize(MetadataID+1);
594198090Srdivacky
595201360Srdivacky    if (NumberedMetadata[MetadataID] != 0)
596201360Srdivacky      return TokError("Metadata id is already used");
597201360Srdivacky    NumberedMetadata[MetadataID] = Init;
598200581Srdivacky  }
599200581Srdivacky
600200581Srdivacky  return false;
601200581Srdivacky}
602200581Srdivacky
603193323Sed/// ParseAlias:
604193323Sed///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
605193323Sed/// Aliasee
606193323Sed///   ::= TypeAndValue
607193323Sed///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
608198090Srdivacky///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
609193323Sed///
610193323Sed/// Everything through visibility has already been parsed.
611193323Sed///
612193323Sedbool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
613193323Sed                          unsigned Visibility) {
614193323Sed  assert(Lex.getKind() == lltok::kw_alias);
615193323Sed  Lex.Lex();
616193323Sed  unsigned Linkage;
617193323Sed  LocTy LinkageLoc = Lex.getLoc();
618193323Sed  if (ParseOptionalLinkage(Linkage))
619193323Sed    return true;
620193323Sed
621193323Sed  if (Linkage != GlobalValue::ExternalLinkage &&
622193323Sed      Linkage != GlobalValue::WeakAnyLinkage &&
623193323Sed      Linkage != GlobalValue::WeakODRLinkage &&
624193323Sed      Linkage != GlobalValue::InternalLinkage &&
625198090Srdivacky      Linkage != GlobalValue::PrivateLinkage &&
626210299Sed      Linkage != GlobalValue::LinkerPrivateLinkage &&
627212904Sdim      Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
628212904Sdim      Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
629193323Sed    return Error(LinkageLoc, "invalid linkage type for alias");
630198090Srdivacky
631193323Sed  Constant *Aliasee;
632193323Sed  LocTy AliaseeLoc = Lex.getLoc();
633193323Sed  if (Lex.getKind() != lltok::kw_bitcast &&
634193323Sed      Lex.getKind() != lltok::kw_getelementptr) {
635193323Sed    if (ParseGlobalTypeAndValue(Aliasee)) return true;
636193323Sed  } else {
637193323Sed    // The bitcast dest type is not present, it is implied by the dest type.
638193323Sed    ValID ID;
639193323Sed    if (ParseValID(ID)) return true;
640193323Sed    if (ID.Kind != ValID::t_Constant)
641193323Sed      return Error(AliaseeLoc, "invalid aliasee");
642193323Sed    Aliasee = ID.ConstantVal;
643193323Sed  }
644198090Srdivacky
645204642Srdivacky  if (!Aliasee->getType()->isPointerTy())
646193323Sed    return Error(AliaseeLoc, "alias must have pointer type");
647193323Sed
648193323Sed  // Okay, create the alias but do not insert it into the module yet.
649193323Sed  GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
650193323Sed                                    (GlobalValue::LinkageTypes)Linkage, Name,
651193323Sed                                    Aliasee);
652193323Sed  GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
653198090Srdivacky
654193323Sed  // See if this value already exists in the symbol table.  If so, it is either
655193323Sed  // a redefinition or a definition of a forward reference.
656198892Srdivacky  if (GlobalValue *Val = M->getNamedValue(Name)) {
657193323Sed    // See if this was a redefinition.  If so, there is no entry in
658193323Sed    // ForwardRefVals.
659193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
660193323Sed      I = ForwardRefVals.find(Name);
661193323Sed    if (I == ForwardRefVals.end())
662193323Sed      return Error(NameLoc, "redefinition of global named '@" + Name + "'");
663193323Sed
664193323Sed    // Otherwise, this was a definition of forward ref.  Verify that types
665193323Sed    // agree.
666193323Sed    if (Val->getType() != GA->getType())
667193323Sed      return Error(NameLoc,
668193323Sed              "forward reference and definition of alias have different types");
669198090Srdivacky
670193323Sed    // If they agree, just RAUW the old value with the alias and remove the
671193323Sed    // forward ref info.
672193323Sed    Val->replaceAllUsesWith(GA);
673193323Sed    Val->eraseFromParent();
674193323Sed    ForwardRefVals.erase(I);
675193323Sed  }
676198090Srdivacky
677193323Sed  // Insert into the module, we know its name won't collide now.
678193323Sed  M->getAliasList().push_back(GA);
679193323Sed  assert(GA->getNameStr() == Name && "Should not be a name conflict!");
680198090Srdivacky
681193323Sed  return false;
682193323Sed}
683193323Sed
684193323Sed/// ParseGlobal
685193323Sed///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
686193323Sed///       OptionalAddrSpace GlobalType Type Const
687193323Sed///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
688193323Sed///       OptionalAddrSpace GlobalType Type Const
689193323Sed///
690193323Sed/// Everything through visibility has been parsed already.
691193323Sed///
692193323Sedbool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
693193323Sed                           unsigned Linkage, bool HasLinkage,
694193323Sed                           unsigned Visibility) {
695193323Sed  unsigned AddrSpace;
696193323Sed  bool ThreadLocal, IsConstant;
697193323Sed  LocTy TyLoc;
698198090Srdivacky
699198090Srdivacky  PATypeHolder Ty(Type::getVoidTy(Context));
700193323Sed  if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
701193323Sed      ParseOptionalAddrSpace(AddrSpace) ||
702193323Sed      ParseGlobalType(IsConstant) ||
703193323Sed      ParseType(Ty, TyLoc))
704193323Sed    return true;
705198090Srdivacky
706193323Sed  // If the linkage is specified and is external, then no initializer is
707193323Sed  // present.
708193323Sed  Constant *Init = 0;
709193323Sed  if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
710193323Sed                      Linkage != GlobalValue::ExternalWeakLinkage &&
711193323Sed                      Linkage != GlobalValue::ExternalLinkage)) {
712193323Sed    if (ParseGlobalValue(Ty, Init))
713193323Sed      return true;
714193323Sed  }
715193323Sed
716204642Srdivacky  if (Ty->isFunctionTy() || Ty->isLabelTy())
717193323Sed    return Error(TyLoc, "invalid type for global variable");
718198090Srdivacky
719193323Sed  GlobalVariable *GV = 0;
720193323Sed
721193323Sed  // See if the global was forward referenced, if so, use the global.
722193323Sed  if (!Name.empty()) {
723198892Srdivacky    if (GlobalValue *GVal = M->getNamedValue(Name)) {
724198892Srdivacky      if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
725198892Srdivacky        return Error(NameLoc, "redefinition of global '@" + Name + "'");
726198892Srdivacky      GV = cast<GlobalVariable>(GVal);
727198892Srdivacky    }
728193323Sed  } else {
729193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
730193323Sed      I = ForwardRefValIDs.find(NumberedVals.size());
731193323Sed    if (I != ForwardRefValIDs.end()) {
732193323Sed      GV = cast<GlobalVariable>(I->second.first);
733193323Sed      ForwardRefValIDs.erase(I);
734193323Sed    }
735193323Sed  }
736193323Sed
737193323Sed  if (GV == 0) {
738198090Srdivacky    GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
739198090Srdivacky                            Name, 0, false, AddrSpace);
740193323Sed  } else {
741193323Sed    if (GV->getType()->getElementType() != Ty)
742193323Sed      return Error(TyLoc,
743193323Sed            "forward reference and definition of global have different types");
744198090Srdivacky
745193323Sed    // Move the forward-reference to the correct spot in the module.
746193323Sed    M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
747193323Sed  }
748193323Sed
749193323Sed  if (Name.empty())
750193323Sed    NumberedVals.push_back(GV);
751198090Srdivacky
752193323Sed  // Set the parsed properties on the global.
753193323Sed  if (Init)
754193323Sed    GV->setInitializer(Init);
755193323Sed  GV->setConstant(IsConstant);
756193323Sed  GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
757193323Sed  GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
758193323Sed  GV->setThreadLocal(ThreadLocal);
759198090Srdivacky
760193323Sed  // Parse attributes on the global.
761193323Sed  while (Lex.getKind() == lltok::comma) {
762193323Sed    Lex.Lex();
763198090Srdivacky
764193323Sed    if (Lex.getKind() == lltok::kw_section) {
765193323Sed      Lex.Lex();
766193323Sed      GV->setSection(Lex.getStrVal());
767193323Sed      if (ParseToken(lltok::StringConstant, "expected global section string"))
768193323Sed        return true;
769193323Sed    } else if (Lex.getKind() == lltok::kw_align) {
770193323Sed      unsigned Alignment;
771193323Sed      if (ParseOptionalAlignment(Alignment)) return true;
772193323Sed      GV->setAlignment(Alignment);
773193323Sed    } else {
774193323Sed      TokError("unknown global variable property!");
775193323Sed    }
776193323Sed  }
777198090Srdivacky
778193323Sed  return false;
779193323Sed}
780193323Sed
781193323Sed
782193323Sed//===----------------------------------------------------------------------===//
783193323Sed// GlobalValue Reference/Resolution Routines.
784193323Sed//===----------------------------------------------------------------------===//
785193323Sed
786193323Sed/// GetGlobalVal - Get a value with the specified name or ID, creating a
787193323Sed/// forward reference record if needed.  This can return null if the value
788193323Sed/// exists but does not have the right type.
789193323SedGlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
790193323Sed                                    LocTy Loc) {
791193323Sed  const PointerType *PTy = dyn_cast<PointerType>(Ty);
792193323Sed  if (PTy == 0) {
793193323Sed    Error(Loc, "global variable reference must have pointer type");
794193323Sed    return 0;
795193323Sed  }
796198090Srdivacky
797193323Sed  // Look this name up in the normal function symbol table.
798193323Sed  GlobalValue *Val =
799193323Sed    cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
800198090Srdivacky
801193323Sed  // If this is a forward reference for the value, see if we already created a
802193323Sed  // forward ref record.
803193323Sed  if (Val == 0) {
804193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
805193323Sed      I = ForwardRefVals.find(Name);
806193323Sed    if (I != ForwardRefVals.end())
807193323Sed      Val = I->second.first;
808193323Sed  }
809198090Srdivacky
810193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
811193323Sed  if (Val) {
812193323Sed    if (Val->getType() == Ty) return Val;
813193323Sed    Error(Loc, "'@" + Name + "' defined with type '" +
814193323Sed          Val->getType()->getDescription() + "'");
815193323Sed    return 0;
816193323Sed  }
817198090Srdivacky
818193323Sed  // Otherwise, create a new forward reference for this value and remember it.
819193323Sed  GlobalValue *FwdVal;
820193323Sed  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
821193323Sed    // Function types can return opaque but functions can't.
822204642Srdivacky    if (FT->getReturnType()->isOpaqueTy()) {
823193323Sed      Error(Loc, "function may not return opaque type");
824193323Sed      return 0;
825193323Sed    }
826198090Srdivacky
827193323Sed    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
828193323Sed  } else {
829198090Srdivacky    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
830198090Srdivacky                                GlobalValue::ExternalWeakLinkage, 0, Name);
831193323Sed  }
832198090Srdivacky
833193323Sed  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
834193323Sed  return FwdVal;
835193323Sed}
836193323Sed
837193323SedGlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
838193323Sed  const PointerType *PTy = dyn_cast<PointerType>(Ty);
839193323Sed  if (PTy == 0) {
840193323Sed    Error(Loc, "global variable reference must have pointer type");
841193323Sed    return 0;
842193323Sed  }
843198090Srdivacky
844193323Sed  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
845198090Srdivacky
846193323Sed  // If this is a forward reference for the value, see if we already created a
847193323Sed  // forward ref record.
848193323Sed  if (Val == 0) {
849193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
850193323Sed      I = ForwardRefValIDs.find(ID);
851193323Sed    if (I != ForwardRefValIDs.end())
852193323Sed      Val = I->second.first;
853193323Sed  }
854198090Srdivacky
855193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
856193323Sed  if (Val) {
857193323Sed    if (Val->getType() == Ty) return Val;
858193323Sed    Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
859193323Sed          Val->getType()->getDescription() + "'");
860193323Sed    return 0;
861193323Sed  }
862198090Srdivacky
863193323Sed  // Otherwise, create a new forward reference for this value and remember it.
864193323Sed  GlobalValue *FwdVal;
865193323Sed  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
866193323Sed    // Function types can return opaque but functions can't.
867204642Srdivacky    if (FT->getReturnType()->isOpaqueTy()) {
868193323Sed      Error(Loc, "function may not return opaque type");
869193323Sed      return 0;
870193323Sed    }
871193323Sed    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
872193323Sed  } else {
873198090Srdivacky    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
874198090Srdivacky                                GlobalValue::ExternalWeakLinkage, 0, "");
875193323Sed  }
876198090Srdivacky
877193323Sed  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
878193323Sed  return FwdVal;
879193323Sed}
880193323Sed
881193323Sed
882193323Sed//===----------------------------------------------------------------------===//
883193323Sed// Helper Routines.
884193323Sed//===----------------------------------------------------------------------===//
885193323Sed
886193323Sed/// ParseToken - If the current token has the specified kind, eat it and return
887193323Sed/// success.  Otherwise, emit the specified error and return failure.
888193323Sedbool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
889193323Sed  if (Lex.getKind() != T)
890193323Sed    return TokError(ErrMsg);
891193323Sed  Lex.Lex();
892193323Sed  return false;
893193323Sed}
894193323Sed
895193323Sed/// ParseStringConstant
896193323Sed///   ::= StringConstant
897193323Sedbool LLParser::ParseStringConstant(std::string &Result) {
898193323Sed  if (Lex.getKind() != lltok::StringConstant)
899193323Sed    return TokError("expected string constant");
900193323Sed  Result = Lex.getStrVal();
901193323Sed  Lex.Lex();
902193323Sed  return false;
903193323Sed}
904193323Sed
905193323Sed/// ParseUInt32
906193323Sed///   ::= uint32
907193323Sedbool LLParser::ParseUInt32(unsigned &Val) {
908193323Sed  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
909193323Sed    return TokError("expected integer");
910193323Sed  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
911193323Sed  if (Val64 != unsigned(Val64))
912193323Sed    return TokError("expected 32-bit integer (too large)");
913193323Sed  Val = Val64;
914193323Sed  Lex.Lex();
915193323Sed  return false;
916193323Sed}
917193323Sed
918193323Sed
919193323Sed/// ParseOptionalAddrSpace
920193323Sed///   := /*empty*/
921193323Sed///   := 'addrspace' '(' uint32 ')'
922193323Sedbool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
923193323Sed  AddrSpace = 0;
924193323Sed  if (!EatIfPresent(lltok::kw_addrspace))
925193323Sed    return false;
926193323Sed  return ParseToken(lltok::lparen, "expected '(' in address space") ||
927193323Sed         ParseUInt32(AddrSpace) ||
928193323Sed         ParseToken(lltok::rparen, "expected ')' in address space");
929198090Srdivacky}
930193323Sed
931193323Sed/// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
932193323Sed/// indicates what kind of attribute list this is: 0: function arg, 1: result,
933193323Sed/// 2: function attr.
934193323Sed/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
935193323Sedbool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
936193323Sed  Attrs = Attribute::None;
937193323Sed  LocTy AttrLoc = Lex.getLoc();
938198090Srdivacky
939193323Sed  while (1) {
940193323Sed    switch (Lex.getKind()) {
941193323Sed    case lltok::kw_sext:
942193323Sed    case lltok::kw_zext:
943193323Sed      // Treat these as signext/zeroext if they occur in the argument list after
944193323Sed      // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
945193323Sed      // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
946193323Sed      // expr.
947193323Sed      // FIXME: REMOVE THIS IN LLVM 3.0
948193323Sed      if (AttrKind == 3) {
949193323Sed        if (Lex.getKind() == lltok::kw_sext)
950193323Sed          Attrs |= Attribute::SExt;
951193323Sed        else
952193323Sed          Attrs |= Attribute::ZExt;
953193323Sed        break;
954193323Sed      }
955193323Sed      // FALL THROUGH.
956193323Sed    default:  // End of attributes.
957193323Sed      if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
958193323Sed        return Error(AttrLoc, "invalid use of function-only attribute");
959198090Srdivacky
960193323Sed      if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
961193323Sed        return Error(AttrLoc, "invalid use of parameter-only attribute");
962198090Srdivacky
963193323Sed      return false;
964193574Sed    case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
965193574Sed    case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
966193574Sed    case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
967193574Sed    case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
968193574Sed    case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
969193574Sed    case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
970193574Sed    case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
971193574Sed    case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
972193323Sed
973193574Sed    case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
974193574Sed    case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
975193574Sed    case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
976193574Sed    case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
977193574Sed    case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
978203954Srdivacky    case lltok::kw_inlinehint:      Attrs |= Attribute::InlineHint; break;
979193574Sed    case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
980193574Sed    case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
981193574Sed    case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
982193574Sed    case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
983193574Sed    case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
984193574Sed    case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
985198090Srdivacky    case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
986198090Srdivacky
987203954Srdivacky    case lltok::kw_alignstack: {
988203954Srdivacky      unsigned Alignment;
989203954Srdivacky      if (ParseOptionalStackAlignment(Alignment))
990203954Srdivacky        return true;
991203954Srdivacky      Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
992203954Srdivacky      continue;
993203954Srdivacky    }
994203954Srdivacky
995193323Sed    case lltok::kw_align: {
996193323Sed      unsigned Alignment;
997193323Sed      if (ParseOptionalAlignment(Alignment))
998193323Sed        return true;
999193323Sed      Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1000193323Sed      continue;
1001193323Sed    }
1002203954Srdivacky
1003193323Sed    }
1004193323Sed    Lex.Lex();
1005193323Sed  }
1006193323Sed}
1007193323Sed
1008193323Sed/// ParseOptionalLinkage
1009193323Sed///   ::= /*empty*/
1010193323Sed///   ::= 'private'
1011198090Srdivacky///   ::= 'linker_private'
1012210299Sed///   ::= 'linker_private_weak'
1013212904Sdim///   ::= 'linker_private_weak_def_auto'
1014193323Sed///   ::= 'internal'
1015193323Sed///   ::= 'weak'
1016193323Sed///   ::= 'weak_odr'
1017193323Sed///   ::= 'linkonce'
1018193323Sed///   ::= 'linkonce_odr'
1019210299Sed///   ::= 'available_externally'
1020193323Sed///   ::= 'appending'
1021193323Sed///   ::= 'dllexport'
1022193323Sed///   ::= 'common'
1023193323Sed///   ::= 'dllimport'
1024193323Sed///   ::= 'extern_weak'
1025193323Sed///   ::= 'external'
1026193323Sedbool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1027193323Sed  HasLinkage = false;
1028193323Sed  switch (Lex.getKind()) {
1029198090Srdivacky  default:                       Res=GlobalValue::ExternalLinkage; return false;
1030198090Srdivacky  case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1031198090Srdivacky  case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1032210299Sed  case lltok::kw_linker_private_weak:
1033210299Sed    Res = GlobalValue::LinkerPrivateWeakLinkage;
1034210299Sed    break;
1035212904Sdim  case lltok::kw_linker_private_weak_def_auto:
1036212904Sdim    Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1037212904Sdim    break;
1038198090Srdivacky  case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1039198090Srdivacky  case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1040198090Srdivacky  case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1041198090Srdivacky  case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1042198090Srdivacky  case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1043193323Sed  case lltok::kw_available_externally:
1044193323Sed    Res = GlobalValue::AvailableExternallyLinkage;
1045193323Sed    break;
1046198090Srdivacky  case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1047198090Srdivacky  case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
1048198090Srdivacky  case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1049198090Srdivacky  case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
1050198090Srdivacky  case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1051198090Srdivacky  case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1052193323Sed  }
1053193323Sed  Lex.Lex();
1054193323Sed  HasLinkage = true;
1055193323Sed  return false;
1056193323Sed}
1057193323Sed
1058193323Sed/// ParseOptionalVisibility
1059193323Sed///   ::= /*empty*/
1060193323Sed///   ::= 'default'
1061193323Sed///   ::= 'hidden'
1062193323Sed///   ::= 'protected'
1063198090Srdivacky///
1064193323Sedbool LLParser::ParseOptionalVisibility(unsigned &Res) {
1065193323Sed  switch (Lex.getKind()) {
1066193323Sed  default:                  Res = GlobalValue::DefaultVisibility; return false;
1067193323Sed  case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1068193323Sed  case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1069193323Sed  case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1070193323Sed  }
1071193323Sed  Lex.Lex();
1072193323Sed  return false;
1073193323Sed}
1074193323Sed
1075193323Sed/// ParseOptionalCallingConv
1076193323Sed///   ::= /*empty*/
1077193323Sed///   ::= 'ccc'
1078193323Sed///   ::= 'fastcc'
1079193323Sed///   ::= 'coldcc'
1080193323Sed///   ::= 'x86_stdcallcc'
1081193323Sed///   ::= 'x86_fastcallcc'
1082208599Srdivacky///   ::= 'x86_thiscallcc'
1083194612Sed///   ::= 'arm_apcscc'
1084194612Sed///   ::= 'arm_aapcscc'
1085194612Sed///   ::= 'arm_aapcs_vfpcc'
1086200581Srdivacky///   ::= 'msp430_intrcc'
1087193323Sed///   ::= 'cc' UINT
1088194612Sed///
1089198090Srdivackybool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1090193323Sed  switch (Lex.getKind()) {
1091193323Sed  default:                       CC = CallingConv::C; return false;
1092193323Sed  case lltok::kw_ccc:            CC = CallingConv::C; break;
1093193323Sed  case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1094193323Sed  case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1095193323Sed  case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1096193323Sed  case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1097208599Srdivacky  case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1098194612Sed  case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1099194612Sed  case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1100194612Sed  case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1101200581Srdivacky  case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1102198090Srdivacky  case lltok::kw_cc: {
1103198090Srdivacky      unsigned ArbitraryCC;
1104198090Srdivacky      Lex.Lex();
1105198090Srdivacky      if (ParseUInt32(ArbitraryCC)) {
1106198090Srdivacky        return true;
1107198090Srdivacky      } else
1108198090Srdivacky        CC = static_cast<CallingConv::ID>(ArbitraryCC);
1109198090Srdivacky        return false;
1110198090Srdivacky    }
1111198090Srdivacky    break;
1112193323Sed  }
1113198090Srdivacky
1114193323Sed  Lex.Lex();
1115193323Sed  return false;
1116193323Sed}
1117193323Sed
1118201360Srdivacky/// ParseInstructionMetadata
1119201360Srdivacky///   ::= !dbg !42 (',' !dbg !57)*
1120212904Sdimbool LLParser::ParseInstructionMetadata(Instruction *Inst,
1121212904Sdim                                        PerFunctionState *PFS) {
1122201360Srdivacky  do {
1123201360Srdivacky    if (Lex.getKind() != lltok::MetadataVar)
1124201360Srdivacky      return TokError("expected metadata after comma");
1125198090Srdivacky
1126201360Srdivacky    std::string Name = Lex.getStrVal();
1127212904Sdim    unsigned MDK = M->getMDKindID(Name.c_str());
1128201360Srdivacky    Lex.Lex();
1129198396Srdivacky
1130201360Srdivacky    MDNode *Node;
1131206083Srdivacky    unsigned NodeID;
1132206083Srdivacky    SMLoc Loc = Lex.getLoc();
1133212904Sdim
1134212904Sdim    if (ParseToken(lltok::exclaim, "expected '!' here"))
1135201360Srdivacky      return true;
1136198090Srdivacky
1137212904Sdim    // This code is similar to that of ParseMetadataValue, however it needs to
1138212904Sdim    // have special-case code for a forward reference; see the comments on
1139212904Sdim    // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1140212904Sdim    // at the top level here.
1141212904Sdim    if (Lex.getKind() == lltok::lbrace) {
1142212904Sdim      ValID ID;
1143212904Sdim      if (ParseMetadataListValue(ID, PFS))
1144212904Sdim        return true;
1145212904Sdim      assert(ID.Kind == ValID::t_MDNode);
1146212904Sdim      Inst->setMetadata(MDK, ID.MDNodeVal);
1147206083Srdivacky    } else {
1148212904Sdim      if (ParseMDNodeID(Node, NodeID))
1149212904Sdim        return true;
1150212904Sdim      if (Node) {
1151212904Sdim        // If we got the node, add it to the instruction.
1152212904Sdim        Inst->setMetadata(MDK, Node);
1153212904Sdim      } else {
1154212904Sdim        MDRef R = { Loc, MDK, NodeID };
1155212904Sdim        // Otherwise, remember that this should be resolved later.
1156212904Sdim        ForwardRefInstMetadata[Inst].push_back(R);
1157212904Sdim      }
1158206083Srdivacky    }
1159198090Srdivacky
1160201360Srdivacky    // If this is the end of the list, we're done.
1161201360Srdivacky  } while (EatIfPresent(lltok::comma));
1162198090Srdivacky  return false;
1163198090Srdivacky}
1164198090Srdivacky
1165193323Sed/// ParseOptionalAlignment
1166193323Sed///   ::= /* empty */
1167193323Sed///   ::= 'align' 4
1168193323Sedbool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1169193323Sed  Alignment = 0;
1170193323Sed  if (!EatIfPresent(lltok::kw_align))
1171193323Sed    return false;
1172193323Sed  LocTy AlignLoc = Lex.getLoc();
1173193323Sed  if (ParseUInt32(Alignment)) return true;
1174193323Sed  if (!isPowerOf2_32(Alignment))
1175193323Sed    return Error(AlignLoc, "alignment is not a power of two");
1176212904Sdim  if (Alignment > Value::MaximumAlignment)
1177212904Sdim    return Error(AlignLoc, "huge alignments are not supported yet");
1178193323Sed  return false;
1179193323Sed}
1180193323Sed
1181201360Srdivacky/// ParseOptionalCommaAlign
1182201360Srdivacky///   ::=
1183201360Srdivacky///   ::= ',' align 4
1184201360Srdivacky///
1185201360Srdivacky/// This returns with AteExtraComma set to true if it ate an excess comma at the
1186201360Srdivacky/// end.
1187201360Srdivackybool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1188201360Srdivacky                                       bool &AteExtraComma) {
1189201360Srdivacky  AteExtraComma = false;
1190201360Srdivacky  while (EatIfPresent(lltok::comma)) {
1191201360Srdivacky    // Metadata at the end is an early exit.
1192201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
1193201360Srdivacky      AteExtraComma = true;
1194201360Srdivacky      return false;
1195201360Srdivacky    }
1196201360Srdivacky
1197207618Srdivacky    if (Lex.getKind() != lltok::kw_align)
1198207618Srdivacky      return Error(Lex.getLoc(), "expected metadata or 'align'");
1199207618Srdivacky
1200212904Sdim    LocTy AlignLoc = Lex.getLoc();
1201207618Srdivacky    if (ParseOptionalAlignment(Alignment)) return true;
1202201360Srdivacky  }
1203198090Srdivacky
1204198090Srdivacky  return false;
1205193323Sed}
1206193323Sed
1207203954Srdivacky/// ParseOptionalStackAlignment
1208203954Srdivacky///   ::= /* empty */
1209203954Srdivacky///   ::= 'alignstack' '(' 4 ')'
1210203954Srdivackybool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1211203954Srdivacky  Alignment = 0;
1212203954Srdivacky  if (!EatIfPresent(lltok::kw_alignstack))
1213203954Srdivacky    return false;
1214203954Srdivacky  LocTy ParenLoc = Lex.getLoc();
1215203954Srdivacky  if (!EatIfPresent(lltok::lparen))
1216203954Srdivacky    return Error(ParenLoc, "expected '('");
1217203954Srdivacky  LocTy AlignLoc = Lex.getLoc();
1218203954Srdivacky  if (ParseUInt32(Alignment)) return true;
1219203954Srdivacky  ParenLoc = Lex.getLoc();
1220203954Srdivacky  if (!EatIfPresent(lltok::rparen))
1221203954Srdivacky    return Error(ParenLoc, "expected ')'");
1222203954Srdivacky  if (!isPowerOf2_32(Alignment))
1223203954Srdivacky    return Error(AlignLoc, "stack alignment is not a power of two");
1224203954Srdivacky  return false;
1225203954Srdivacky}
1226198090Srdivacky
1227201360Srdivacky/// ParseIndexList - This parses the index list for an insert/extractvalue
1228201360Srdivacky/// instruction.  This sets AteExtraComma in the case where we eat an extra
1229201360Srdivacky/// comma at the end of the line and find that it is followed by metadata.
1230201360Srdivacky/// Clients that don't allow metadata can call the version of this function that
1231201360Srdivacky/// only takes one argument.
1232201360Srdivacky///
1233193323Sed/// ParseIndexList
1234193323Sed///    ::=  (',' uint32)+
1235201360Srdivacky///
1236201360Srdivackybool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1237201360Srdivacky                              bool &AteExtraComma) {
1238201360Srdivacky  AteExtraComma = false;
1239201360Srdivacky
1240193323Sed  if (Lex.getKind() != lltok::comma)
1241193323Sed    return TokError("expected ',' as start of index list");
1242198090Srdivacky
1243193323Sed  while (EatIfPresent(lltok::comma)) {
1244201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
1245201360Srdivacky      AteExtraComma = true;
1246201360Srdivacky      return false;
1247201360Srdivacky    }
1248193323Sed    unsigned Idx;
1249193323Sed    if (ParseUInt32(Idx)) return true;
1250193323Sed    Indices.push_back(Idx);
1251193323Sed  }
1252198090Srdivacky
1253193323Sed  return false;
1254193323Sed}
1255193323Sed
1256193323Sed//===----------------------------------------------------------------------===//
1257193323Sed// Type Parsing.
1258193323Sed//===----------------------------------------------------------------------===//
1259193323Sed
1260193323Sed/// ParseType - Parse and resolve a full type.
1261193323Sedbool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1262193323Sed  LocTy TypeLoc = Lex.getLoc();
1263193323Sed  if (ParseTypeRec(Result)) return true;
1264198090Srdivacky
1265193323Sed  // Verify no unresolved uprefs.
1266193323Sed  if (!UpRefs.empty())
1267193323Sed    return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1268198090Srdivacky
1269198090Srdivacky  if (!AllowVoid && Result.get()->isVoidTy())
1270193323Sed    return Error(TypeLoc, "void type only allowed for function results");
1271198090Srdivacky
1272193323Sed  return false;
1273193323Sed}
1274193323Sed
1275193323Sed/// HandleUpRefs - Every time we finish a new layer of types, this function is
1276193323Sed/// called.  It loops through the UpRefs vector, which is a list of the
1277193323Sed/// currently active types.  For each type, if the up-reference is contained in
1278193323Sed/// the newly completed type, we decrement the level count.  When the level
1279193323Sed/// count reaches zero, the up-referenced type is the type that is passed in:
1280193323Sed/// thus we can complete the cycle.
1281193323Sed///
1282193323SedPATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1283193323Sed  // If Ty isn't abstract, or if there are no up-references in it, then there is
1284193323Sed  // nothing to resolve here.
1285193323Sed  if (!ty->isAbstract() || UpRefs.empty()) return ty;
1286198090Srdivacky
1287193323Sed  PATypeHolder Ty(ty);
1288193323Sed#if 0
1289201360Srdivacky  dbgs() << "Type '" << Ty->getDescription()
1290193323Sed         << "' newly formed.  Resolving upreferences.\n"
1291193323Sed         << UpRefs.size() << " upreferences active!\n";
1292193323Sed#endif
1293198090Srdivacky
1294193323Sed  // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1295193323Sed  // to zero), we resolve them all together before we resolve them to Ty.  At
1296193323Sed  // the end of the loop, if there is anything to resolve to Ty, it will be in
1297193323Sed  // this variable.
1298193323Sed  OpaqueType *TypeToResolve = 0;
1299198090Srdivacky
1300193323Sed  for (unsigned i = 0; i != UpRefs.size(); ++i) {
1301193323Sed    // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1302193323Sed    bool ContainsType =
1303193323Sed      std::find(Ty->subtype_begin(), Ty->subtype_end(),
1304193323Sed                UpRefs[i].LastContainedTy) != Ty->subtype_end();
1305198090Srdivacky
1306193323Sed#if 0
1307201360Srdivacky    dbgs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1308193323Sed           << UpRefs[i].LastContainedTy->getDescription() << ") = "
1309193323Sed           << (ContainsType ? "true" : "false")
1310193323Sed           << " level=" << UpRefs[i].NestingLevel << "\n";
1311193323Sed#endif
1312193323Sed    if (!ContainsType)
1313193323Sed      continue;
1314198090Srdivacky
1315193323Sed    // Decrement level of upreference
1316193323Sed    unsigned Level = --UpRefs[i].NestingLevel;
1317193323Sed    UpRefs[i].LastContainedTy = Ty;
1318198090Srdivacky
1319193323Sed    // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1320193323Sed    if (Level != 0)
1321193323Sed      continue;
1322198090Srdivacky
1323193323Sed#if 0
1324201360Srdivacky    dbgs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1325193323Sed#endif
1326193323Sed    if (!TypeToResolve)
1327193323Sed      TypeToResolve = UpRefs[i].UpRefTy;
1328193323Sed    else
1329193323Sed      UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1330193323Sed    UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1331193323Sed    --i;                                // Do not skip the next element.
1332193323Sed  }
1333198090Srdivacky
1334193323Sed  if (TypeToResolve)
1335193323Sed    TypeToResolve->refineAbstractTypeTo(Ty);
1336198090Srdivacky
1337193323Sed  return Ty;
1338193323Sed}
1339193323Sed
1340193323Sed
1341193323Sed/// ParseTypeRec - The recursive function used to process the internal
1342193323Sed/// implementation details of types.
1343193323Sedbool LLParser::ParseTypeRec(PATypeHolder &Result) {
1344193323Sed  switch (Lex.getKind()) {
1345193323Sed  default:
1346193323Sed    return TokError("expected type");
1347193323Sed  case lltok::Type:
1348193323Sed    // TypeRec ::= 'float' | 'void' (etc)
1349193323Sed    Result = Lex.getTyVal();
1350198090Srdivacky    Lex.Lex();
1351193323Sed    break;
1352193323Sed  case lltok::kw_opaque:
1353193323Sed    // TypeRec ::= 'opaque'
1354198090Srdivacky    Result = OpaqueType::get(Context);
1355193323Sed    Lex.Lex();
1356193323Sed    break;
1357193323Sed  case lltok::lbrace:
1358193323Sed    // TypeRec ::= '{' ... '}'
1359193323Sed    if (ParseStructType(Result, false))
1360193323Sed      return true;
1361193323Sed    break;
1362193323Sed  case lltok::lsquare:
1363193323Sed    // TypeRec ::= '[' ... ']'
1364193323Sed    Lex.Lex(); // eat the lsquare.
1365193323Sed    if (ParseArrayVectorType(Result, false))
1366193323Sed      return true;
1367193323Sed    break;
1368193323Sed  case lltok::less: // Either vector or packed struct.
1369193323Sed    // TypeRec ::= '<' ... '>'
1370193323Sed    Lex.Lex();
1371193323Sed    if (Lex.getKind() == lltok::lbrace) {
1372193323Sed      if (ParseStructType(Result, true) ||
1373193323Sed          ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1374193323Sed        return true;
1375193323Sed    } else if (ParseArrayVectorType(Result, true))
1376193323Sed      return true;
1377193323Sed    break;
1378193323Sed  case lltok::LocalVar:
1379193323Sed  case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1380193323Sed    // TypeRec ::= %foo
1381193323Sed    if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1382193323Sed      Result = T;
1383193323Sed    } else {
1384198090Srdivacky      Result = OpaqueType::get(Context);
1385193323Sed      ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1386193323Sed                                            std::make_pair(Result,
1387193323Sed                                                           Lex.getLoc())));
1388193323Sed      M->addTypeName(Lex.getStrVal(), Result.get());
1389193323Sed    }
1390193323Sed    Lex.Lex();
1391193323Sed    break;
1392198090Srdivacky
1393193323Sed  case lltok::LocalVarID:
1394193323Sed    // TypeRec ::= %4
1395193323Sed    if (Lex.getUIntVal() < NumberedTypes.size())
1396193323Sed      Result = NumberedTypes[Lex.getUIntVal()];
1397193323Sed    else {
1398193323Sed      std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1399193323Sed        I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1400193323Sed      if (I != ForwardRefTypeIDs.end())
1401193323Sed        Result = I->second.first;
1402193323Sed      else {
1403198090Srdivacky        Result = OpaqueType::get(Context);
1404193323Sed        ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1405193323Sed                                                std::make_pair(Result,
1406193323Sed                                                               Lex.getLoc())));
1407193323Sed      }
1408193323Sed    }
1409193323Sed    Lex.Lex();
1410193323Sed    break;
1411193323Sed  case lltok::backslash: {
1412193323Sed    // TypeRec ::= '\' 4
1413193323Sed    Lex.Lex();
1414193323Sed    unsigned Val;
1415193323Sed    if (ParseUInt32(Val)) return true;
1416198090Srdivacky    OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1417193323Sed    UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1418193323Sed    Result = OT;
1419193323Sed    break;
1420193323Sed  }
1421193323Sed  }
1422198090Srdivacky
1423198090Srdivacky  // Parse the type suffixes.
1424193323Sed  while (1) {
1425193323Sed    switch (Lex.getKind()) {
1426193323Sed    // End of type.
1427198090Srdivacky    default: return false;
1428193323Sed
1429193323Sed    // TypeRec ::= TypeRec '*'
1430193323Sed    case lltok::star:
1431198090Srdivacky      if (Result.get()->isLabelTy())
1432193323Sed        return TokError("basic block pointers are invalid");
1433198090Srdivacky      if (Result.get()->isVoidTy())
1434193323Sed        return TokError("pointers to void are invalid; use i8* instead");
1435193630Sed      if (!PointerType::isValidElementType(Result.get()))
1436193630Sed        return TokError("pointer to this type is invalid");
1437198090Srdivacky      Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1438193323Sed      Lex.Lex();
1439193323Sed      break;
1440193323Sed
1441193323Sed    // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1442193323Sed    case lltok::kw_addrspace: {
1443198090Srdivacky      if (Result.get()->isLabelTy())
1444193323Sed        return TokError("basic block pointers are invalid");
1445198090Srdivacky      if (Result.get()->isVoidTy())
1446193323Sed        return TokError("pointers to void are invalid; use i8* instead");
1447193630Sed      if (!PointerType::isValidElementType(Result.get()))
1448193630Sed        return TokError("pointer to this type is invalid");
1449193323Sed      unsigned AddrSpace;
1450193323Sed      if (ParseOptionalAddrSpace(AddrSpace) ||
1451193323Sed          ParseToken(lltok::star, "expected '*' in address space"))
1452193323Sed        return true;
1453193323Sed
1454198090Srdivacky      Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1455193323Sed      break;
1456193323Sed    }
1457198090Srdivacky
1458193323Sed    /// Types '(' ArgTypeListI ')' OptFuncAttrs
1459193323Sed    case lltok::lparen:
1460193323Sed      if (ParseFunctionType(Result))
1461193323Sed        return true;
1462193323Sed      break;
1463193323Sed    }
1464193323Sed  }
1465193323Sed}
1466193323Sed
1467193323Sed/// ParseParameterList
1468193323Sed///    ::= '(' ')'
1469193323Sed///    ::= '(' Arg (',' Arg)* ')'
1470193323Sed///  Arg
1471193323Sed///    ::= Type OptionalAttributes Value OptionalAttributes
1472193323Sedbool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1473193323Sed                                  PerFunctionState &PFS) {
1474193323Sed  if (ParseToken(lltok::lparen, "expected '(' in call"))
1475193323Sed    return true;
1476198090Srdivacky
1477193323Sed  while (Lex.getKind() != lltok::rparen) {
1478193323Sed    // If this isn't the first argument, we need a comma.
1479193323Sed    if (!ArgList.empty() &&
1480193323Sed        ParseToken(lltok::comma, "expected ',' in argument list"))
1481193323Sed      return true;
1482198090Srdivacky
1483193323Sed    // Parse the argument.
1484193323Sed    LocTy ArgLoc;
1485198090Srdivacky    PATypeHolder ArgTy(Type::getVoidTy(Context));
1486200581Srdivacky    unsigned ArgAttrs1 = Attribute::None;
1487200581Srdivacky    unsigned ArgAttrs2 = Attribute::None;
1488193323Sed    Value *V;
1489200581Srdivacky    if (ParseType(ArgTy, ArgLoc))
1490193323Sed      return true;
1491200581Srdivacky
1492201360Srdivacky    // Otherwise, handle normal operands.
1493201360Srdivacky    if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1494201360Srdivacky        ParseValue(ArgTy, V, PFS) ||
1495201360Srdivacky        // FIXME: Should not allow attributes after the argument, remove this
1496201360Srdivacky        // in LLVM 3.0.
1497201360Srdivacky        ParseOptionalAttrs(ArgAttrs2, 3))
1498201360Srdivacky      return true;
1499193323Sed    ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1500193323Sed  }
1501193323Sed
1502193323Sed  Lex.Lex();  // Lex the ')'.
1503193323Sed  return false;
1504193323Sed}
1505193323Sed
1506193323Sed
1507193323Sed
1508193323Sed/// ParseArgumentList - Parse the argument list for a function type or function
1509193323Sed/// prototype.  If 'inType' is true then we are parsing a FunctionType.
1510193323Sed///   ::= '(' ArgTypeListI ')'
1511193323Sed/// ArgTypeListI
1512193323Sed///   ::= /*empty*/
1513193323Sed///   ::= '...'
1514193323Sed///   ::= ArgTypeList ',' '...'
1515193323Sed///   ::= ArgType (',' ArgType)*
1516193323Sed///
1517193323Sedbool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1518193323Sed                                 bool &isVarArg, bool inType) {
1519193323Sed  isVarArg = false;
1520193323Sed  assert(Lex.getKind() == lltok::lparen);
1521193323Sed  Lex.Lex(); // eat the (.
1522198090Srdivacky
1523193323Sed  if (Lex.getKind() == lltok::rparen) {
1524193323Sed    // empty
1525193323Sed  } else if (Lex.getKind() == lltok::dotdotdot) {
1526193323Sed    isVarArg = true;
1527193323Sed    Lex.Lex();
1528193323Sed  } else {
1529193323Sed    LocTy TypeLoc = Lex.getLoc();
1530198090Srdivacky    PATypeHolder ArgTy(Type::getVoidTy(Context));
1531193323Sed    unsigned Attrs;
1532193323Sed    std::string Name;
1533198090Srdivacky
1534193323Sed    // If we're parsing a type, use ParseTypeRec, because we allow recursive
1535193323Sed    // types (such as a function returning a pointer to itself).  If parsing a
1536193323Sed    // function prototype, we require fully resolved types.
1537193323Sed    if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1538193323Sed        ParseOptionalAttrs(Attrs, 0)) return true;
1539198090Srdivacky
1540198090Srdivacky    if (ArgTy->isVoidTy())
1541193323Sed      return Error(TypeLoc, "argument can not have void type");
1542198090Srdivacky
1543193323Sed    if (Lex.getKind() == lltok::LocalVar ||
1544193323Sed        Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1545193323Sed      Name = Lex.getStrVal();
1546193323Sed      Lex.Lex();
1547193323Sed    }
1548193323Sed
1549193630Sed    if (!FunctionType::isValidArgumentType(ArgTy))
1550193323Sed      return Error(TypeLoc, "invalid type for function argument");
1551198090Srdivacky
1552193323Sed    ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1553198090Srdivacky
1554193323Sed    while (EatIfPresent(lltok::comma)) {
1555193323Sed      // Handle ... at end of arg list.
1556193323Sed      if (EatIfPresent(lltok::dotdotdot)) {
1557193323Sed        isVarArg = true;
1558193323Sed        break;
1559193323Sed      }
1560198090Srdivacky
1561193323Sed      // Otherwise must be an argument type.
1562193323Sed      TypeLoc = Lex.getLoc();
1563193323Sed      if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1564193323Sed          ParseOptionalAttrs(Attrs, 0)) return true;
1565193323Sed
1566198090Srdivacky      if (ArgTy->isVoidTy())
1567193323Sed        return Error(TypeLoc, "argument can not have void type");
1568193323Sed
1569193323Sed      if (Lex.getKind() == lltok::LocalVar ||
1570193323Sed          Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1571193323Sed        Name = Lex.getStrVal();
1572193323Sed        Lex.Lex();
1573193323Sed      } else {
1574193323Sed        Name = "";
1575193323Sed      }
1576193323Sed
1577204642Srdivacky      if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1578193323Sed        return Error(TypeLoc, "invalid type for function argument");
1579198090Srdivacky
1580193323Sed      ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1581193323Sed    }
1582193323Sed  }
1583198090Srdivacky
1584193323Sed  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1585193323Sed}
1586198090Srdivacky
1587193323Sed/// ParseFunctionType
1588193323Sed///  ::= Type ArgumentList OptionalAttrs
1589193323Sedbool LLParser::ParseFunctionType(PATypeHolder &Result) {
1590193323Sed  assert(Lex.getKind() == lltok::lparen);
1591193323Sed
1592193323Sed  if (!FunctionType::isValidReturnType(Result))
1593193323Sed    return TokError("invalid function return type");
1594198090Srdivacky
1595193323Sed  std::vector<ArgInfo> ArgList;
1596193323Sed  bool isVarArg;
1597193323Sed  unsigned Attrs;
1598193323Sed  if (ParseArgumentList(ArgList, isVarArg, true) ||
1599193323Sed      // FIXME: Allow, but ignore attributes on function types!
1600193323Sed      // FIXME: Remove in LLVM 3.0
1601193323Sed      ParseOptionalAttrs(Attrs, 2))
1602193323Sed    return true;
1603198090Srdivacky
1604193323Sed  // Reject names on the arguments lists.
1605193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1606193323Sed    if (!ArgList[i].Name.empty())
1607193323Sed      return Error(ArgList[i].Loc, "argument name invalid in function type");
1608193323Sed    if (!ArgList[i].Attrs != 0) {
1609193323Sed      // Allow but ignore attributes on function types; this permits
1610193323Sed      // auto-upgrade.
1611193323Sed      // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1612193323Sed    }
1613193323Sed  }
1614198090Srdivacky
1615193323Sed  std::vector<const Type*> ArgListTy;
1616193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1617193323Sed    ArgListTy.push_back(ArgList[i].Type);
1618198090Srdivacky
1619198090Srdivacky  Result = HandleUpRefs(FunctionType::get(Result.get(),
1620195340Sed                                                ArgListTy, isVarArg));
1621193323Sed  return false;
1622193323Sed}
1623193323Sed
1624193323Sed/// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1625193323Sed///   TypeRec
1626193323Sed///     ::= '{' '}'
1627193323Sed///     ::= '{' TypeRec (',' TypeRec)* '}'
1628193323Sed///     ::= '<' '{' '}' '>'
1629193323Sed///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1630193323Sedbool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1631193323Sed  assert(Lex.getKind() == lltok::lbrace);
1632193323Sed  Lex.Lex(); // Consume the '{'
1633198090Srdivacky
1634193323Sed  if (EatIfPresent(lltok::rbrace)) {
1635198090Srdivacky    Result = StructType::get(Context, Packed);
1636193323Sed    return false;
1637193323Sed  }
1638193323Sed
1639193323Sed  std::vector<PATypeHolder> ParamsList;
1640193323Sed  LocTy EltTyLoc = Lex.getLoc();
1641193323Sed  if (ParseTypeRec(Result)) return true;
1642193323Sed  ParamsList.push_back(Result);
1643198090Srdivacky
1644198090Srdivacky  if (Result->isVoidTy())
1645193323Sed    return Error(EltTyLoc, "struct element can not have void type");
1646193630Sed  if (!StructType::isValidElementType(Result))
1647193630Sed    return Error(EltTyLoc, "invalid element type for struct");
1648198090Srdivacky
1649193323Sed  while (EatIfPresent(lltok::comma)) {
1650193323Sed    EltTyLoc = Lex.getLoc();
1651193323Sed    if (ParseTypeRec(Result)) return true;
1652198090Srdivacky
1653198090Srdivacky    if (Result->isVoidTy())
1654193323Sed      return Error(EltTyLoc, "struct element can not have void type");
1655193630Sed    if (!StructType::isValidElementType(Result))
1656193630Sed      return Error(EltTyLoc, "invalid element type for struct");
1657198090Srdivacky
1658193323Sed    ParamsList.push_back(Result);
1659193323Sed  }
1660198090Srdivacky
1661193323Sed  if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1662193323Sed    return true;
1663198090Srdivacky
1664193323Sed  std::vector<const Type*> ParamsListTy;
1665193323Sed  for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1666193323Sed    ParamsListTy.push_back(ParamsList[i].get());
1667198090Srdivacky  Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1668193323Sed  return false;
1669193323Sed}
1670193323Sed
1671193323Sed/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1672193323Sed/// token has already been consumed.
1673198090Srdivacky///   TypeRec
1674193323Sed///     ::= '[' APSINTVAL 'x' Types ']'
1675193323Sed///     ::= '<' APSINTVAL 'x' Types '>'
1676193323Sedbool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1677193323Sed  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1678193323Sed      Lex.getAPSIntVal().getBitWidth() > 64)
1679193323Sed    return TokError("expected number in address space");
1680198090Srdivacky
1681193323Sed  LocTy SizeLoc = Lex.getLoc();
1682193323Sed  uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1683193323Sed  Lex.Lex();
1684198090Srdivacky
1685193323Sed  if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1686193323Sed      return true;
1687193323Sed
1688193323Sed  LocTy TypeLoc = Lex.getLoc();
1689198090Srdivacky  PATypeHolder EltTy(Type::getVoidTy(Context));
1690193323Sed  if (ParseTypeRec(EltTy)) return true;
1691198090Srdivacky
1692198090Srdivacky  if (EltTy->isVoidTy())
1693193323Sed    return Error(TypeLoc, "array and vector element type cannot be void");
1694193323Sed
1695193323Sed  if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1696193323Sed                 "expected end of sequential type"))
1697193323Sed    return true;
1698198090Srdivacky
1699193323Sed  if (isVector) {
1700193323Sed    if (Size == 0)
1701193323Sed      return Error(SizeLoc, "zero element vector is illegal");
1702193323Sed    if ((unsigned)Size != Size)
1703193323Sed      return Error(SizeLoc, "size too large for vector");
1704193630Sed    if (!VectorType::isValidElementType(EltTy))
1705193323Sed      return Error(TypeLoc, "vector element type must be fp or integer");
1706198090Srdivacky    Result = VectorType::get(EltTy, unsigned(Size));
1707193323Sed  } else {
1708193630Sed    if (!ArrayType::isValidElementType(EltTy))
1709193323Sed      return Error(TypeLoc, "invalid array element type");
1710198090Srdivacky    Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1711193323Sed  }
1712193323Sed  return false;
1713193323Sed}
1714193323Sed
1715193323Sed//===----------------------------------------------------------------------===//
1716193323Sed// Function Semantic Analysis.
1717193323Sed//===----------------------------------------------------------------------===//
1718193323Sed
1719198892SrdivackyLLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1720198892Srdivacky                                             int functionNumber)
1721198892Srdivacky  : P(p), F(f), FunctionNumber(functionNumber) {
1722193323Sed
1723193323Sed  // Insert unnamed arguments into the NumberedVals list.
1724193323Sed  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1725193323Sed       AI != E; ++AI)
1726193323Sed    if (!AI->hasName())
1727193323Sed      NumberedVals.push_back(AI);
1728193323Sed}
1729193323Sed
1730193323SedLLParser::PerFunctionState::~PerFunctionState() {
1731193323Sed  // If there were any forward referenced non-basicblock values, delete them.
1732193323Sed  for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1733193323Sed       I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1734193323Sed    if (!isa<BasicBlock>(I->second.first)) {
1735195340Sed      I->second.first->replaceAllUsesWith(
1736198090Srdivacky                           UndefValue::get(I->second.first->getType()));
1737193323Sed      delete I->second.first;
1738193323Sed      I->second.first = 0;
1739193323Sed    }
1740198090Srdivacky
1741193323Sed  for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1742193323Sed       I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1743193323Sed    if (!isa<BasicBlock>(I->second.first)) {
1744195340Sed      I->second.first->replaceAllUsesWith(
1745198090Srdivacky                           UndefValue::get(I->second.first->getType()));
1746193323Sed      delete I->second.first;
1747193323Sed      I->second.first = 0;
1748193323Sed    }
1749193323Sed}
1750193323Sed
1751198892Srdivackybool LLParser::PerFunctionState::FinishFunction() {
1752198892Srdivacky  // Check to see if someone took the address of labels in this block.
1753198892Srdivacky  if (!P.ForwardRefBlockAddresses.empty()) {
1754198892Srdivacky    ValID FunctionID;
1755198892Srdivacky    if (!F.getName().empty()) {
1756198892Srdivacky      FunctionID.Kind = ValID::t_GlobalName;
1757198892Srdivacky      FunctionID.StrVal = F.getName();
1758198892Srdivacky    } else {
1759198892Srdivacky      FunctionID.Kind = ValID::t_GlobalID;
1760198892Srdivacky      FunctionID.UIntVal = FunctionNumber;
1761198892Srdivacky    }
1762198892Srdivacky
1763198892Srdivacky    std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1764198892Srdivacky      FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1765198892Srdivacky    if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1766198892Srdivacky      // Resolve all these references.
1767198892Srdivacky      if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1768198892Srdivacky        return true;
1769198892Srdivacky
1770198892Srdivacky      P.ForwardRefBlockAddresses.erase(FRBAI);
1771198892Srdivacky    }
1772198892Srdivacky  }
1773198892Srdivacky
1774193323Sed  if (!ForwardRefVals.empty())
1775193323Sed    return P.Error(ForwardRefVals.begin()->second.second,
1776193323Sed                   "use of undefined value '%" + ForwardRefVals.begin()->first +
1777193323Sed                   "'");
1778193323Sed  if (!ForwardRefValIDs.empty())
1779193323Sed    return P.Error(ForwardRefValIDs.begin()->second.second,
1780193323Sed                   "use of undefined value '%" +
1781193323Sed                   utostr(ForwardRefValIDs.begin()->first) + "'");
1782193323Sed  return false;
1783193323Sed}
1784193323Sed
1785193323Sed
1786193323Sed/// GetVal - Get a value with the specified name or ID, creating a
1787193323Sed/// forward reference record if needed.  This can return null if the value
1788193323Sed/// exists but does not have the right type.
1789193323SedValue *LLParser::PerFunctionState::GetVal(const std::string &Name,
1790193323Sed                                          const Type *Ty, LocTy Loc) {
1791193323Sed  // Look this name up in the normal function symbol table.
1792193323Sed  Value *Val = F.getValueSymbolTable().lookup(Name);
1793198090Srdivacky
1794193323Sed  // If this is a forward reference for the value, see if we already created a
1795193323Sed  // forward ref record.
1796193323Sed  if (Val == 0) {
1797193323Sed    std::map<std::string, std::pair<Value*, LocTy> >::iterator
1798193323Sed      I = ForwardRefVals.find(Name);
1799193323Sed    if (I != ForwardRefVals.end())
1800193323Sed      Val = I->second.first;
1801193323Sed  }
1802198090Srdivacky
1803193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
1804193323Sed  if (Val) {
1805193323Sed    if (Val->getType() == Ty) return Val;
1806198090Srdivacky    if (Ty->isLabelTy())
1807193323Sed      P.Error(Loc, "'%" + Name + "' is not a basic block");
1808193323Sed    else
1809193323Sed      P.Error(Loc, "'%" + Name + "' defined with type '" +
1810193323Sed              Val->getType()->getDescription() + "'");
1811193323Sed    return 0;
1812193323Sed  }
1813198090Srdivacky
1814193323Sed  // Don't make placeholders with invalid type.
1815204642Srdivacky  if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1816193323Sed    P.Error(Loc, "invalid use of a non-first-class type");
1817193323Sed    return 0;
1818193323Sed  }
1819198090Srdivacky
1820193323Sed  // Otherwise, create a new forward reference for this value and remember it.
1821193323Sed  Value *FwdVal;
1822198090Srdivacky  if (Ty->isLabelTy())
1823198090Srdivacky    FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1824193323Sed  else
1825193323Sed    FwdVal = new Argument(Ty, Name);
1826198090Srdivacky
1827193323Sed  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1828193323Sed  return FwdVal;
1829193323Sed}
1830193323Sed
1831193323SedValue *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1832193323Sed                                          LocTy Loc) {
1833193323Sed  // Look this name up in the normal function symbol table.
1834193323Sed  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1835198090Srdivacky
1836193323Sed  // If this is a forward reference for the value, see if we already created a
1837193323Sed  // forward ref record.
1838193323Sed  if (Val == 0) {
1839193323Sed    std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1840193323Sed      I = ForwardRefValIDs.find(ID);
1841193323Sed    if (I != ForwardRefValIDs.end())
1842193323Sed      Val = I->second.first;
1843193323Sed  }
1844198090Srdivacky
1845193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
1846193323Sed  if (Val) {
1847193323Sed    if (Val->getType() == Ty) return Val;
1848198090Srdivacky    if (Ty->isLabelTy())
1849193323Sed      P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1850193323Sed    else
1851193323Sed      P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1852193323Sed              Val->getType()->getDescription() + "'");
1853193323Sed    return 0;
1854193323Sed  }
1855198090Srdivacky
1856204642Srdivacky  if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1857193323Sed    P.Error(Loc, "invalid use of a non-first-class type");
1858193323Sed    return 0;
1859193323Sed  }
1860198090Srdivacky
1861193323Sed  // Otherwise, create a new forward reference for this value and remember it.
1862193323Sed  Value *FwdVal;
1863198090Srdivacky  if (Ty->isLabelTy())
1864198090Srdivacky    FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1865193323Sed  else
1866193323Sed    FwdVal = new Argument(Ty);
1867198090Srdivacky
1868193323Sed  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1869193323Sed  return FwdVal;
1870193323Sed}
1871193323Sed
1872193323Sed/// SetInstName - After an instruction is parsed and inserted into its
1873193323Sed/// basic block, this installs its name.
1874193323Sedbool LLParser::PerFunctionState::SetInstName(int NameID,
1875193323Sed                                             const std::string &NameStr,
1876193323Sed                                             LocTy NameLoc, Instruction *Inst) {
1877193323Sed  // If this instruction has void type, it cannot have a name or ID specified.
1878198090Srdivacky  if (Inst->getType()->isVoidTy()) {
1879193323Sed    if (NameID != -1 || !NameStr.empty())
1880193323Sed      return P.Error(NameLoc, "instructions returning void cannot have a name");
1881193323Sed    return false;
1882193323Sed  }
1883198090Srdivacky
1884193323Sed  // If this was a numbered instruction, verify that the instruction is the
1885193323Sed  // expected value and resolve any forward references.
1886193323Sed  if (NameStr.empty()) {
1887193323Sed    // If neither a name nor an ID was specified, just use the next ID.
1888193323Sed    if (NameID == -1)
1889193323Sed      NameID = NumberedVals.size();
1890198090Srdivacky
1891193323Sed    if (unsigned(NameID) != NumberedVals.size())
1892193323Sed      return P.Error(NameLoc, "instruction expected to be numbered '%" +
1893193323Sed                     utostr(NumberedVals.size()) + "'");
1894198090Srdivacky
1895193323Sed    std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1896193323Sed      ForwardRefValIDs.find(NameID);
1897193323Sed    if (FI != ForwardRefValIDs.end()) {
1898193323Sed      if (FI->second.first->getType() != Inst->getType())
1899198090Srdivacky        return P.Error(NameLoc, "instruction forward referenced with type '" +
1900193323Sed                       FI->second.first->getType()->getDescription() + "'");
1901193323Sed      FI->second.first->replaceAllUsesWith(Inst);
1902198090Srdivacky      delete FI->second.first;
1903193323Sed      ForwardRefValIDs.erase(FI);
1904193323Sed    }
1905193323Sed
1906193323Sed    NumberedVals.push_back(Inst);
1907193323Sed    return false;
1908193323Sed  }
1909193323Sed
1910193323Sed  // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1911193323Sed  std::map<std::string, std::pair<Value*, LocTy> >::iterator
1912193323Sed    FI = ForwardRefVals.find(NameStr);
1913193323Sed  if (FI != ForwardRefVals.end()) {
1914193323Sed    if (FI->second.first->getType() != Inst->getType())
1915198090Srdivacky      return P.Error(NameLoc, "instruction forward referenced with type '" +
1916193323Sed                     FI->second.first->getType()->getDescription() + "'");
1917193323Sed    FI->second.first->replaceAllUsesWith(Inst);
1918198090Srdivacky    delete FI->second.first;
1919193323Sed    ForwardRefVals.erase(FI);
1920193323Sed  }
1921198090Srdivacky
1922193323Sed  // Set the name on the instruction.
1923193323Sed  Inst->setName(NameStr);
1924198090Srdivacky
1925193323Sed  if (Inst->getNameStr() != NameStr)
1926198090Srdivacky    return P.Error(NameLoc, "multiple definition of local value named '" +
1927193323Sed                   NameStr + "'");
1928193323Sed  return false;
1929193323Sed}
1930193323Sed
1931193323Sed/// GetBB - Get a basic block with the specified name or ID, creating a
1932193323Sed/// forward reference record if needed.
1933193323SedBasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1934193323Sed                                              LocTy Loc) {
1935198090Srdivacky  return cast_or_null<BasicBlock>(GetVal(Name,
1936198090Srdivacky                                        Type::getLabelTy(F.getContext()), Loc));
1937193323Sed}
1938193323Sed
1939193323SedBasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1940198090Srdivacky  return cast_or_null<BasicBlock>(GetVal(ID,
1941198090Srdivacky                                        Type::getLabelTy(F.getContext()), Loc));
1942193323Sed}
1943193323Sed
1944193323Sed/// DefineBB - Define the specified basic block, which is either named or
1945193323Sed/// unnamed.  If there is an error, this returns null otherwise it returns
1946193323Sed/// the block being defined.
1947193323SedBasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1948193323Sed                                                 LocTy Loc) {
1949193323Sed  BasicBlock *BB;
1950193323Sed  if (Name.empty())
1951193323Sed    BB = GetBB(NumberedVals.size(), Loc);
1952193323Sed  else
1953193323Sed    BB = GetBB(Name, Loc);
1954193323Sed  if (BB == 0) return 0; // Already diagnosed error.
1955198090Srdivacky
1956193323Sed  // Move the block to the end of the function.  Forward ref'd blocks are
1957193323Sed  // inserted wherever they happen to be referenced.
1958193323Sed  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1959198090Srdivacky
1960193323Sed  // Remove the block from forward ref sets.
1961193323Sed  if (Name.empty()) {
1962193323Sed    ForwardRefValIDs.erase(NumberedVals.size());
1963193323Sed    NumberedVals.push_back(BB);
1964193323Sed  } else {
1965193323Sed    // BB forward references are already in the function symbol table.
1966193323Sed    ForwardRefVals.erase(Name);
1967193323Sed  }
1968198090Srdivacky
1969193323Sed  return BB;
1970193323Sed}
1971193323Sed
1972193323Sed//===----------------------------------------------------------------------===//
1973193323Sed// Constants.
1974193323Sed//===----------------------------------------------------------------------===//
1975193323Sed
1976193323Sed/// ParseValID - Parse an abstract value that doesn't necessarily have a
1977193323Sed/// type implied.  For example, if we parse "4" we don't know what integer type
1978193323Sed/// it has.  The value will later be combined with its type and checked for
1979202375Srdivacky/// sanity.  PFS is used to convert function-local operands of metadata (since
1980202375Srdivacky/// metadata operands are not just parsed here but also converted to values).
1981202375Srdivacky/// PFS can be null when we are not parsing metadata values inside a function.
1982202375Srdivackybool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1983193323Sed  ID.Loc = Lex.getLoc();
1984193323Sed  switch (Lex.getKind()) {
1985193323Sed  default: return TokError("expected value token");
1986193323Sed  case lltok::GlobalID:  // @42
1987193323Sed    ID.UIntVal = Lex.getUIntVal();
1988193323Sed    ID.Kind = ValID::t_GlobalID;
1989193323Sed    break;
1990193323Sed  case lltok::GlobalVar:  // @foo
1991193323Sed    ID.StrVal = Lex.getStrVal();
1992193323Sed    ID.Kind = ValID::t_GlobalName;
1993193323Sed    break;
1994193323Sed  case lltok::LocalVarID:  // %42
1995193323Sed    ID.UIntVal = Lex.getUIntVal();
1996193323Sed    ID.Kind = ValID::t_LocalID;
1997193323Sed    break;
1998193323Sed  case lltok::LocalVar:  // %foo
1999193323Sed  case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
2000193323Sed    ID.StrVal = Lex.getStrVal();
2001193323Sed    ID.Kind = ValID::t_LocalName;
2002193323Sed    break;
2003210299Sed  case lltok::exclaim:   // !42, !{...}, or !"foo"
2004210299Sed    return ParseMetadataValue(ID, PFS);
2005193323Sed  case lltok::APSInt:
2006198090Srdivacky    ID.APSIntVal = Lex.getAPSIntVal();
2007193323Sed    ID.Kind = ValID::t_APSInt;
2008193323Sed    break;
2009193323Sed  case lltok::APFloat:
2010193323Sed    ID.APFloatVal = Lex.getAPFloatVal();
2011193323Sed    ID.Kind = ValID::t_APFloat;
2012193323Sed    break;
2013193323Sed  case lltok::kw_true:
2014198090Srdivacky    ID.ConstantVal = ConstantInt::getTrue(Context);
2015193323Sed    ID.Kind = ValID::t_Constant;
2016193323Sed    break;
2017193323Sed  case lltok::kw_false:
2018198090Srdivacky    ID.ConstantVal = ConstantInt::getFalse(Context);
2019193323Sed    ID.Kind = ValID::t_Constant;
2020193323Sed    break;
2021193323Sed  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2022193323Sed  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2023193323Sed  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2024198090Srdivacky
2025193323Sed  case lltok::lbrace: {
2026193323Sed    // ValID ::= '{' ConstVector '}'
2027193323Sed    Lex.Lex();
2028193323Sed    SmallVector<Constant*, 16> Elts;
2029193323Sed    if (ParseGlobalValueVector(Elts) ||
2030193323Sed        ParseToken(lltok::rbrace, "expected end of struct constant"))
2031193323Sed      return true;
2032198090Srdivacky
2033198090Srdivacky    ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2034198090Srdivacky                                         Elts.size(), false);
2035193323Sed    ID.Kind = ValID::t_Constant;
2036193323Sed    return false;
2037193323Sed  }
2038193323Sed  case lltok::less: {
2039193323Sed    // ValID ::= '<' ConstVector '>'         --> Vector.
2040193323Sed    // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2041193323Sed    Lex.Lex();
2042193323Sed    bool isPackedStruct = EatIfPresent(lltok::lbrace);
2043198090Srdivacky
2044193323Sed    SmallVector<Constant*, 16> Elts;
2045193323Sed    LocTy FirstEltLoc = Lex.getLoc();
2046193323Sed    if (ParseGlobalValueVector(Elts) ||
2047193323Sed        (isPackedStruct &&
2048193323Sed         ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2049193323Sed        ParseToken(lltok::greater, "expected end of constant"))
2050193323Sed      return true;
2051198090Srdivacky
2052193323Sed    if (isPackedStruct) {
2053195340Sed      ID.ConstantVal =
2054198090Srdivacky        ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2055193323Sed      ID.Kind = ValID::t_Constant;
2056193323Sed      return false;
2057193323Sed    }
2058198090Srdivacky
2059193323Sed    if (Elts.empty())
2060193323Sed      return Error(ID.Loc, "constant vector must not be empty");
2061193323Sed
2062203954Srdivacky    if (!Elts[0]->getType()->isIntegerTy() &&
2063203954Srdivacky        !Elts[0]->getType()->isFloatingPointTy())
2064193323Sed      return Error(FirstEltLoc,
2065193323Sed                   "vector elements must have integer or floating point type");
2066198090Srdivacky
2067193323Sed    // Verify that all the vector elements have the same type.
2068193323Sed    for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2069193323Sed      if (Elts[i]->getType() != Elts[0]->getType())
2070193323Sed        return Error(FirstEltLoc,
2071193323Sed                     "vector element #" + utostr(i) +
2072193323Sed                    " is not of type '" + Elts[0]->getType()->getDescription());
2073198090Srdivacky
2074198090Srdivacky    ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
2075193323Sed    ID.Kind = ValID::t_Constant;
2076193323Sed    return false;
2077193323Sed  }
2078193323Sed  case lltok::lsquare: {   // Array Constant
2079193323Sed    Lex.Lex();
2080193323Sed    SmallVector<Constant*, 16> Elts;
2081193323Sed    LocTy FirstEltLoc = Lex.getLoc();
2082193323Sed    if (ParseGlobalValueVector(Elts) ||
2083193323Sed        ParseToken(lltok::rsquare, "expected end of array constant"))
2084193323Sed      return true;
2085193323Sed
2086193323Sed    // Handle empty element.
2087193323Sed    if (Elts.empty()) {
2088193323Sed      // Use undef instead of an array because it's inconvenient to determine
2089193323Sed      // the element type at this point, there being no elements to examine.
2090193323Sed      ID.Kind = ValID::t_EmptyArray;
2091193323Sed      return false;
2092193323Sed    }
2093198090Srdivacky
2094193323Sed    if (!Elts[0]->getType()->isFirstClassType())
2095198090Srdivacky      return Error(FirstEltLoc, "invalid array element type: " +
2096193323Sed                   Elts[0]->getType()->getDescription());
2097198090Srdivacky
2098198090Srdivacky    ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2099198090Srdivacky
2100193323Sed    // Verify all elements are correct type!
2101193323Sed    for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2102193323Sed      if (Elts[i]->getType() != Elts[0]->getType())
2103193323Sed        return Error(FirstEltLoc,
2104193323Sed                     "array element #" + utostr(i) +
2105193323Sed                     " is not of type '" +Elts[0]->getType()->getDescription());
2106193323Sed    }
2107198090Srdivacky
2108198090Srdivacky    ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2109193323Sed    ID.Kind = ValID::t_Constant;
2110193323Sed    return false;
2111193323Sed  }
2112193323Sed  case lltok::kw_c:  // c "foo"
2113193323Sed    Lex.Lex();
2114198090Srdivacky    ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2115193323Sed    if (ParseToken(lltok::StringConstant, "expected string")) return true;
2116193323Sed    ID.Kind = ValID::t_Constant;
2117193323Sed    return false;
2118193323Sed
2119193323Sed  case lltok::kw_asm: {
2120198396Srdivacky    // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2121198396Srdivacky    bool HasSideEffect, AlignStack;
2122193323Sed    Lex.Lex();
2123193323Sed    if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2124198396Srdivacky        ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2125193323Sed        ParseStringConstant(ID.StrVal) ||
2126193323Sed        ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2127193323Sed        ParseToken(lltok::StringConstant, "expected constraint string"))
2128193323Sed      return true;
2129193323Sed    ID.StrVal2 = Lex.getStrVal();
2130199481Srdivacky    ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2131193323Sed    ID.Kind = ValID::t_InlineAsm;
2132193323Sed    return false;
2133193323Sed  }
2134198090Srdivacky
2135198892Srdivacky  case lltok::kw_blockaddress: {
2136198892Srdivacky    // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2137198892Srdivacky    Lex.Lex();
2138198892Srdivacky
2139198892Srdivacky    ValID Fn, Label;
2140198892Srdivacky    LocTy FnLoc, LabelLoc;
2141198892Srdivacky
2142198892Srdivacky    if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2143198892Srdivacky        ParseValID(Fn) ||
2144198892Srdivacky        ParseToken(lltok::comma, "expected comma in block address expression")||
2145198892Srdivacky        ParseValID(Label) ||
2146198892Srdivacky        ParseToken(lltok::rparen, "expected ')' in block address expression"))
2147198892Srdivacky      return true;
2148198892Srdivacky
2149198892Srdivacky    if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2150198892Srdivacky      return Error(Fn.Loc, "expected function name in blockaddress");
2151198892Srdivacky    if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2152198892Srdivacky      return Error(Label.Loc, "expected basic block name in blockaddress");
2153198892Srdivacky
2154198892Srdivacky    // Make a global variable as a placeholder for this reference.
2155198892Srdivacky    GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2156198892Srdivacky                                           false, GlobalValue::InternalLinkage,
2157198892Srdivacky                                                0, "");
2158198892Srdivacky    ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2159198892Srdivacky    ID.ConstantVal = FwdRef;
2160198892Srdivacky    ID.Kind = ValID::t_Constant;
2161198892Srdivacky    return false;
2162198892Srdivacky  }
2163198892Srdivacky
2164193323Sed  case lltok::kw_trunc:
2165193323Sed  case lltok::kw_zext:
2166193323Sed  case lltok::kw_sext:
2167193323Sed  case lltok::kw_fptrunc:
2168193323Sed  case lltok::kw_fpext:
2169193323Sed  case lltok::kw_bitcast:
2170193323Sed  case lltok::kw_uitofp:
2171193323Sed  case lltok::kw_sitofp:
2172193323Sed  case lltok::kw_fptoui:
2173198090Srdivacky  case lltok::kw_fptosi:
2174193323Sed  case lltok::kw_inttoptr:
2175198090Srdivacky  case lltok::kw_ptrtoint: {
2176193323Sed    unsigned Opc = Lex.getUIntVal();
2177198090Srdivacky    PATypeHolder DestTy(Type::getVoidTy(Context));
2178193323Sed    Constant *SrcVal;
2179193323Sed    Lex.Lex();
2180193323Sed    if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2181193323Sed        ParseGlobalTypeAndValue(SrcVal) ||
2182194612Sed        ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2183193323Sed        ParseType(DestTy) ||
2184193323Sed        ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2185193323Sed      return true;
2186193323Sed    if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2187193323Sed      return Error(ID.Loc, "invalid cast opcode for cast from '" +
2188193323Sed                   SrcVal->getType()->getDescription() + "' to '" +
2189193323Sed                   DestTy->getDescription() + "'");
2190198090Srdivacky    ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2191195340Sed                                                 SrcVal, DestTy);
2192193323Sed    ID.Kind = ValID::t_Constant;
2193193323Sed    return false;
2194193323Sed  }
2195193323Sed  case lltok::kw_extractvalue: {
2196193323Sed    Lex.Lex();
2197193323Sed    Constant *Val;
2198193323Sed    SmallVector<unsigned, 4> Indices;
2199193323Sed    if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2200193323Sed        ParseGlobalTypeAndValue(Val) ||
2201193323Sed        ParseIndexList(Indices) ||
2202193323Sed        ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2203193323Sed      return true;
2204198892Srdivacky
2205203954Srdivacky    if (!Val->getType()->isAggregateType())
2206203954Srdivacky      return Error(ID.Loc, "extractvalue operand must be aggregate type");
2207193323Sed    if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2208193323Sed                                          Indices.end()))
2209193323Sed      return Error(ID.Loc, "invalid indices for extractvalue");
2210193323Sed    ID.ConstantVal =
2211198090Srdivacky      ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2212193323Sed    ID.Kind = ValID::t_Constant;
2213193323Sed    return false;
2214193323Sed  }
2215193323Sed  case lltok::kw_insertvalue: {
2216193323Sed    Lex.Lex();
2217193323Sed    Constant *Val0, *Val1;
2218193323Sed    SmallVector<unsigned, 4> Indices;
2219193323Sed    if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2220193323Sed        ParseGlobalTypeAndValue(Val0) ||
2221193323Sed        ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2222193323Sed        ParseGlobalTypeAndValue(Val1) ||
2223193323Sed        ParseIndexList(Indices) ||
2224193323Sed        ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2225193323Sed      return true;
2226203954Srdivacky    if (!Val0->getType()->isAggregateType())
2227203954Srdivacky      return Error(ID.Loc, "insertvalue operand must be aggregate type");
2228193323Sed    if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2229193323Sed                                          Indices.end()))
2230193323Sed      return Error(ID.Loc, "invalid indices for insertvalue");
2231198090Srdivacky    ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2232195340Sed                       Indices.data(), Indices.size());
2233193323Sed    ID.Kind = ValID::t_Constant;
2234193323Sed    return false;
2235193323Sed  }
2236193323Sed  case lltok::kw_icmp:
2237198090Srdivacky  case lltok::kw_fcmp: {
2238193323Sed    unsigned PredVal, Opc = Lex.getUIntVal();
2239193323Sed    Constant *Val0, *Val1;
2240193323Sed    Lex.Lex();
2241193323Sed    if (ParseCmpPredicate(PredVal, Opc) ||
2242193323Sed        ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2243193323Sed        ParseGlobalTypeAndValue(Val0) ||
2244193323Sed        ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2245193323Sed        ParseGlobalTypeAndValue(Val1) ||
2246193323Sed        ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2247193323Sed      return true;
2248198090Srdivacky
2249193323Sed    if (Val0->getType() != Val1->getType())
2250193323Sed      return Error(ID.Loc, "compare operands must have the same type");
2251198090Srdivacky
2252193323Sed    CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2253198090Srdivacky
2254193323Sed    if (Opc == Instruction::FCmp) {
2255203954Srdivacky      if (!Val0->getType()->isFPOrFPVectorTy())
2256193323Sed        return Error(ID.Loc, "fcmp requires floating point operands");
2257198090Srdivacky      ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2258198090Srdivacky    } else {
2259198090Srdivacky      assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2260203954Srdivacky      if (!Val0->getType()->isIntOrIntVectorTy() &&
2261204642Srdivacky          !Val0->getType()->isPointerTy())
2262193323Sed        return Error(ID.Loc, "icmp requires pointer or integer operands");
2263198090Srdivacky      ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2264193323Sed    }
2265193323Sed    ID.Kind = ValID::t_Constant;
2266193323Sed    return false;
2267193323Sed  }
2268198090Srdivacky
2269193323Sed  // Binary Operators.
2270193323Sed  case lltok::kw_add:
2271193574Sed  case lltok::kw_fadd:
2272193323Sed  case lltok::kw_sub:
2273193574Sed  case lltok::kw_fsub:
2274193323Sed  case lltok::kw_mul:
2275193574Sed  case lltok::kw_fmul:
2276193323Sed  case lltok::kw_udiv:
2277193323Sed  case lltok::kw_sdiv:
2278193323Sed  case lltok::kw_fdiv:
2279193323Sed  case lltok::kw_urem:
2280193323Sed  case lltok::kw_srem:
2281193323Sed  case lltok::kw_frem: {
2282198090Srdivacky    bool NUW = false;
2283198090Srdivacky    bool NSW = false;
2284198090Srdivacky    bool Exact = false;
2285193323Sed    unsigned Opc = Lex.getUIntVal();
2286193323Sed    Constant *Val0, *Val1;
2287193323Sed    Lex.Lex();
2288198090Srdivacky    LocTy ModifierLoc = Lex.getLoc();
2289198090Srdivacky    if (Opc == Instruction::Add ||
2290198090Srdivacky        Opc == Instruction::Sub ||
2291198090Srdivacky        Opc == Instruction::Mul) {
2292198090Srdivacky      if (EatIfPresent(lltok::kw_nuw))
2293198090Srdivacky        NUW = true;
2294198090Srdivacky      if (EatIfPresent(lltok::kw_nsw)) {
2295198090Srdivacky        NSW = true;
2296198090Srdivacky        if (EatIfPresent(lltok::kw_nuw))
2297198090Srdivacky          NUW = true;
2298198090Srdivacky      }
2299198090Srdivacky    } else if (Opc == Instruction::SDiv) {
2300198090Srdivacky      if (EatIfPresent(lltok::kw_exact))
2301198090Srdivacky        Exact = true;
2302198090Srdivacky    }
2303193323Sed    if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2304193323Sed        ParseGlobalTypeAndValue(Val0) ||
2305193323Sed        ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2306193323Sed        ParseGlobalTypeAndValue(Val1) ||
2307193323Sed        ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2308193323Sed      return true;
2309193323Sed    if (Val0->getType() != Val1->getType())
2310193323Sed      return Error(ID.Loc, "operands of constexpr must have same type");
2311203954Srdivacky    if (!Val0->getType()->isIntOrIntVectorTy()) {
2312198090Srdivacky      if (NUW)
2313198090Srdivacky        return Error(ModifierLoc, "nuw only applies to integer operations");
2314198090Srdivacky      if (NSW)
2315198090Srdivacky        return Error(ModifierLoc, "nsw only applies to integer operations");
2316198090Srdivacky    }
2317207618Srdivacky    // Check that the type is valid for the operator.
2318207618Srdivacky    switch (Opc) {
2319207618Srdivacky    case Instruction::Add:
2320207618Srdivacky    case Instruction::Sub:
2321207618Srdivacky    case Instruction::Mul:
2322207618Srdivacky    case Instruction::UDiv:
2323207618Srdivacky    case Instruction::SDiv:
2324207618Srdivacky    case Instruction::URem:
2325207618Srdivacky    case Instruction::SRem:
2326207618Srdivacky      if (!Val0->getType()->isIntOrIntVectorTy())
2327207618Srdivacky        return Error(ID.Loc, "constexpr requires integer operands");
2328207618Srdivacky      break;
2329207618Srdivacky    case Instruction::FAdd:
2330207618Srdivacky    case Instruction::FSub:
2331207618Srdivacky    case Instruction::FMul:
2332207618Srdivacky    case Instruction::FDiv:
2333207618Srdivacky    case Instruction::FRem:
2334207618Srdivacky      if (!Val0->getType()->isFPOrFPVectorTy())
2335207618Srdivacky        return Error(ID.Loc, "constexpr requires fp operands");
2336207618Srdivacky      break;
2337207618Srdivacky    default: llvm_unreachable("Unknown binary operator!");
2338207618Srdivacky    }
2339198090Srdivacky    unsigned Flags = 0;
2340198090Srdivacky    if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2341198090Srdivacky    if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2342198090Srdivacky    if (Exact) Flags |= SDivOperator::IsExact;
2343198090Srdivacky    Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2344198090Srdivacky    ID.ConstantVal = C;
2345193323Sed    ID.Kind = ValID::t_Constant;
2346193323Sed    return false;
2347193323Sed  }
2348198090Srdivacky
2349193323Sed  // Logical Operations
2350193323Sed  case lltok::kw_shl:
2351193323Sed  case lltok::kw_lshr:
2352193323Sed  case lltok::kw_ashr:
2353193323Sed  case lltok::kw_and:
2354193323Sed  case lltok::kw_or:
2355193323Sed  case lltok::kw_xor: {
2356193323Sed    unsigned Opc = Lex.getUIntVal();
2357193323Sed    Constant *Val0, *Val1;
2358193323Sed    Lex.Lex();
2359193323Sed    if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2360193323Sed        ParseGlobalTypeAndValue(Val0) ||
2361193323Sed        ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2362193323Sed        ParseGlobalTypeAndValue(Val1) ||
2363193323Sed        ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2364193323Sed      return true;
2365193323Sed    if (Val0->getType() != Val1->getType())
2366193323Sed      return Error(ID.Loc, "operands of constexpr must have same type");
2367203954Srdivacky    if (!Val0->getType()->isIntOrIntVectorTy())
2368193323Sed      return Error(ID.Loc,
2369193323Sed                   "constexpr requires integer or integer vector operands");
2370198090Srdivacky    ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2371193323Sed    ID.Kind = ValID::t_Constant;
2372193323Sed    return false;
2373198090Srdivacky  }
2374198090Srdivacky
2375193323Sed  case lltok::kw_getelementptr:
2376193323Sed  case lltok::kw_shufflevector:
2377193323Sed  case lltok::kw_insertelement:
2378193323Sed  case lltok::kw_extractelement:
2379193323Sed  case lltok::kw_select: {
2380193323Sed    unsigned Opc = Lex.getUIntVal();
2381193323Sed    SmallVector<Constant*, 16> Elts;
2382198090Srdivacky    bool InBounds = false;
2383193323Sed    Lex.Lex();
2384198090Srdivacky    if (Opc == Instruction::GetElementPtr)
2385198090Srdivacky      InBounds = EatIfPresent(lltok::kw_inbounds);
2386193323Sed    if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2387193323Sed        ParseGlobalValueVector(Elts) ||
2388193323Sed        ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2389193323Sed      return true;
2390198090Srdivacky
2391193323Sed    if (Opc == Instruction::GetElementPtr) {
2392204642Srdivacky      if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2393193323Sed        return Error(ID.Loc, "getelementptr requires pointer operand");
2394198090Srdivacky
2395193323Sed      if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2396198090Srdivacky                                             (Value**)(Elts.data() + 1),
2397198090Srdivacky                                             Elts.size() - 1))
2398193323Sed        return Error(ID.Loc, "invalid indices for getelementptr");
2399198090Srdivacky      ID.ConstantVal = InBounds ?
2400198090Srdivacky        ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2401198090Srdivacky                                               Elts.data() + 1,
2402198090Srdivacky                                               Elts.size() - 1) :
2403198090Srdivacky        ConstantExpr::getGetElementPtr(Elts[0],
2404198090Srdivacky                                       Elts.data() + 1, Elts.size() - 1);
2405193323Sed    } else if (Opc == Instruction::Select) {
2406193323Sed      if (Elts.size() != 3)
2407193323Sed        return Error(ID.Loc, "expected three operands to select");
2408193323Sed      if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2409193323Sed                                                              Elts[2]))
2410193323Sed        return Error(ID.Loc, Reason);
2411198090Srdivacky      ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2412193323Sed    } else if (Opc == Instruction::ShuffleVector) {
2413193323Sed      if (Elts.size() != 3)
2414193323Sed        return Error(ID.Loc, "expected three operands to shufflevector");
2415193323Sed      if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2416193323Sed        return Error(ID.Loc, "invalid operands to shufflevector");
2417195340Sed      ID.ConstantVal =
2418198090Srdivacky                 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2419193323Sed    } else if (Opc == Instruction::ExtractElement) {
2420193323Sed      if (Elts.size() != 2)
2421193323Sed        return Error(ID.Loc, "expected two operands to extractelement");
2422193323Sed      if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2423193323Sed        return Error(ID.Loc, "invalid extractelement operands");
2424198090Srdivacky      ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2425193323Sed    } else {
2426193323Sed      assert(Opc == Instruction::InsertElement && "Unknown opcode");
2427193323Sed      if (Elts.size() != 3)
2428193323Sed      return Error(ID.Loc, "expected three operands to insertelement");
2429193323Sed      if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2430193323Sed        return Error(ID.Loc, "invalid insertelement operands");
2431195340Sed      ID.ConstantVal =
2432198090Srdivacky                 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2433193323Sed    }
2434198090Srdivacky
2435193323Sed    ID.Kind = ValID::t_Constant;
2436193323Sed    return false;
2437193323Sed  }
2438193323Sed  }
2439198090Srdivacky
2440193323Sed  Lex.Lex();
2441193323Sed  return false;
2442193323Sed}
2443193323Sed
2444193323Sed/// ParseGlobalValue - Parse a global value with the specified type.
2445202375Srdivackybool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2446202375Srdivacky  C = 0;
2447193323Sed  ValID ID;
2448202375Srdivacky  Value *V = NULL;
2449202375Srdivacky  bool Parsed = ParseValID(ID) ||
2450202375Srdivacky                ConvertValIDToValue(Ty, ID, V, NULL);
2451202375Srdivacky  if (V && !(C = dyn_cast<Constant>(V)))
2452202375Srdivacky    return Error(ID.Loc, "global values must be constants");
2453202375Srdivacky  return Parsed;
2454193323Sed}
2455193323Sed
2456202375Srdivackybool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2457202375Srdivacky  PATypeHolder Type(Type::getVoidTy(Context));
2458202375Srdivacky  return ParseType(Type) ||
2459202375Srdivacky         ParseGlobalValue(Type, V);
2460202375Srdivacky}
2461202375Srdivacky
2462202375Srdivacky/// ParseGlobalValueVector
2463202375Srdivacky///   ::= /*empty*/
2464202375Srdivacky///   ::= TypeAndValue (',' TypeAndValue)*
2465202375Srdivackybool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2466202375Srdivacky  // Empty list.
2467202375Srdivacky  if (Lex.getKind() == lltok::rbrace ||
2468202375Srdivacky      Lex.getKind() == lltok::rsquare ||
2469202375Srdivacky      Lex.getKind() == lltok::greater ||
2470202375Srdivacky      Lex.getKind() == lltok::rparen)
2471202375Srdivacky    return false;
2472202375Srdivacky
2473202375Srdivacky  Constant *C;
2474202375Srdivacky  if (ParseGlobalTypeAndValue(C)) return true;
2475202375Srdivacky  Elts.push_back(C);
2476202375Srdivacky
2477202375Srdivacky  while (EatIfPresent(lltok::comma)) {
2478202375Srdivacky    if (ParseGlobalTypeAndValue(C)) return true;
2479202375Srdivacky    Elts.push_back(C);
2480202375Srdivacky  }
2481202375Srdivacky
2482202375Srdivacky  return false;
2483202375Srdivacky}
2484202375Srdivacky
2485212904Sdimbool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2486212904Sdim  assert(Lex.getKind() == lltok::lbrace);
2487212904Sdim  Lex.Lex();
2488212904Sdim
2489212904Sdim  SmallVector<Value*, 16> Elts;
2490212904Sdim  if (ParseMDNodeVector(Elts, PFS) ||
2491212904Sdim      ParseToken(lltok::rbrace, "expected end of metadata node"))
2492212904Sdim    return true;
2493212904Sdim
2494212904Sdim  ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2495212904Sdim  ID.Kind = ValID::t_MDNode;
2496212904Sdim  return false;
2497212904Sdim}
2498212904Sdim
2499210299Sed/// ParseMetadataValue
2500210299Sed///  ::= !42
2501210299Sed///  ::= !{...}
2502210299Sed///  ::= !"string"
2503210299Sedbool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2504210299Sed  assert(Lex.getKind() == lltok::exclaim);
2505210299Sed  Lex.Lex();
2506202375Srdivacky
2507210299Sed  // MDNode:
2508210299Sed  // !{ ... }
2509212904Sdim  if (Lex.getKind() == lltok::lbrace)
2510212904Sdim    return ParseMetadataListValue(ID, PFS);
2511210299Sed
2512210299Sed  // Standalone metadata reference
2513210299Sed  // !42
2514210299Sed  if (Lex.getKind() == lltok::APSInt) {
2515210299Sed    if (ParseMDNodeID(ID.MDNodeVal)) return true;
2516210299Sed    ID.Kind = ValID::t_MDNode;
2517210299Sed    return false;
2518210299Sed  }
2519210299Sed
2520210299Sed  // MDString:
2521210299Sed  //   ::= '!' STRINGCONSTANT
2522210299Sed  if (ParseMDString(ID.MDStringVal)) return true;
2523210299Sed  ID.Kind = ValID::t_MDString;
2524210299Sed  return false;
2525210299Sed}
2526210299Sed
2527210299Sed
2528202375Srdivacky//===----------------------------------------------------------------------===//
2529202375Srdivacky// Function Parsing.
2530202375Srdivacky//===----------------------------------------------------------------------===//
2531202375Srdivacky
2532202375Srdivackybool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2533202375Srdivacky                                   PerFunctionState *PFS) {
2534204642Srdivacky  if (Ty->isFunctionTy())
2535193323Sed    return Error(ID.Loc, "functions are not values, refer to them as pointers");
2536198090Srdivacky
2537193323Sed  switch (ID.Kind) {
2538198090Srdivacky  default: llvm_unreachable("Unknown ValID!");
2539202375Srdivacky  case ValID::t_LocalID:
2540202375Srdivacky    if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2541202375Srdivacky    V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2542202375Srdivacky    return (V == 0);
2543202375Srdivacky  case ValID::t_LocalName:
2544202375Srdivacky    if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2545202375Srdivacky    V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2546202375Srdivacky    return (V == 0);
2547202375Srdivacky  case ValID::t_InlineAsm: {
2548202375Srdivacky    const PointerType *PTy = dyn_cast<PointerType>(Ty);
2549202375Srdivacky    const FunctionType *FTy =
2550202375Srdivacky      PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2551202375Srdivacky    if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2552202375Srdivacky      return Error(ID.Loc, "invalid type for inline asm constraint string");
2553202375Srdivacky    V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2554202375Srdivacky    return false;
2555202375Srdivacky  }
2556201360Srdivacky  case ValID::t_MDNode:
2557202375Srdivacky    if (!Ty->isMetadataTy())
2558202375Srdivacky      return Error(ID.Loc, "metadata value must have metadata type");
2559202375Srdivacky    V = ID.MDNodeVal;
2560202375Srdivacky    return false;
2561201360Srdivacky  case ValID::t_MDString:
2562202375Srdivacky    if (!Ty->isMetadataTy())
2563202375Srdivacky      return Error(ID.Loc, "metadata value must have metadata type");
2564202375Srdivacky    V = ID.MDStringVal;
2565202375Srdivacky    return false;
2566193323Sed  case ValID::t_GlobalName:
2567193323Sed    V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2568193323Sed    return V == 0;
2569193323Sed  case ValID::t_GlobalID:
2570193323Sed    V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2571193323Sed    return V == 0;
2572193323Sed  case ValID::t_APSInt:
2573204642Srdivacky    if (!Ty->isIntegerTy())
2574193323Sed      return Error(ID.Loc, "integer constant must have integer type");
2575193323Sed    ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2576198090Srdivacky    V = ConstantInt::get(Context, ID.APSIntVal);
2577193323Sed    return false;
2578193323Sed  case ValID::t_APFloat:
2579203954Srdivacky    if (!Ty->isFloatingPointTy() ||
2580193323Sed        !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2581193323Sed      return Error(ID.Loc, "floating point constant invalid for type");
2582198090Srdivacky
2583193323Sed    // The lexer has no type info, so builds all float and double FP constants
2584193323Sed    // as double.  Fix this here.  Long double does not need this.
2585193323Sed    if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2586198090Srdivacky        Ty->isFloatTy()) {
2587193323Sed      bool Ignored;
2588193323Sed      ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2589193323Sed                            &Ignored);
2590193323Sed    }
2591198090Srdivacky    V = ConstantFP::get(Context, ID.APFloatVal);
2592198090Srdivacky
2593193323Sed    if (V->getType() != Ty)
2594193323Sed      return Error(ID.Loc, "floating point constant does not have type '" +
2595193323Sed                   Ty->getDescription() + "'");
2596198090Srdivacky
2597193323Sed    return false;
2598193323Sed  case ValID::t_Null:
2599204642Srdivacky    if (!Ty->isPointerTy())
2600193323Sed      return Error(ID.Loc, "null must be a pointer type");
2601198090Srdivacky    V = ConstantPointerNull::get(cast<PointerType>(Ty));
2602193323Sed    return false;
2603193323Sed  case ValID::t_Undef:
2604193323Sed    // FIXME: LabelTy should not be a first-class type.
2605198090Srdivacky    if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2606204642Srdivacky        !Ty->isOpaqueTy())
2607193323Sed      return Error(ID.Loc, "invalid type for undef constant");
2608198090Srdivacky    V = UndefValue::get(Ty);
2609193323Sed    return false;
2610193323Sed  case ValID::t_EmptyArray:
2611204642Srdivacky    if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2612193323Sed      return Error(ID.Loc, "invalid empty array initializer");
2613198090Srdivacky    V = UndefValue::get(Ty);
2614193323Sed    return false;
2615193323Sed  case ValID::t_Zero:
2616193323Sed    // FIXME: LabelTy should not be a first-class type.
2617198090Srdivacky    if (!Ty->isFirstClassType() || Ty->isLabelTy())
2618193323Sed      return Error(ID.Loc, "invalid type for null constant");
2619198090Srdivacky    V = Constant::getNullValue(Ty);
2620193323Sed    return false;
2621193323Sed  case ValID::t_Constant:
2622212904Sdim    if (ID.ConstantVal->getType() != Ty)
2623193323Sed      return Error(ID.Loc, "constant expression type mismatch");
2624203954Srdivacky
2625193323Sed    V = ID.ConstantVal;
2626193323Sed    return false;
2627193323Sed  }
2628193323Sed}
2629198090Srdivacky
2630193323Sedbool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2631193323Sed  V = 0;
2632193323Sed  ValID ID;
2633202375Srdivacky  return ParseValID(ID, &PFS) ||
2634202375Srdivacky         ConvertValIDToValue(Ty, ID, V, &PFS);
2635193323Sed}
2636193323Sed
2637193323Sedbool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2638198090Srdivacky  PATypeHolder T(Type::getVoidTy(Context));
2639193323Sed  return ParseType(T) ||
2640193323Sed         ParseValue(T, V, PFS);
2641193323Sed}
2642193323Sed
2643198892Srdivackybool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2644198892Srdivacky                                      PerFunctionState &PFS) {
2645198892Srdivacky  Value *V;
2646198892Srdivacky  Loc = Lex.getLoc();
2647198892Srdivacky  if (ParseTypeAndValue(V, PFS)) return true;
2648198892Srdivacky  if (!isa<BasicBlock>(V))
2649198892Srdivacky    return Error(Loc, "expected a basic block");
2650198892Srdivacky  BB = cast<BasicBlock>(V);
2651198892Srdivacky  return false;
2652198892Srdivacky}
2653198892Srdivacky
2654198892Srdivacky
2655193323Sed/// FunctionHeader
2656193323Sed///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2657193323Sed///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2658193323Sed///       OptionalAlign OptGC
2659193323Sedbool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2660193323Sed  // Parse the linkage.
2661193323Sed  LocTy LinkageLoc = Lex.getLoc();
2662193323Sed  unsigned Linkage;
2663198090Srdivacky
2664198090Srdivacky  unsigned Visibility, RetAttrs;
2665198090Srdivacky  CallingConv::ID CC;
2666198090Srdivacky  PATypeHolder RetType(Type::getVoidTy(Context));
2667193323Sed  LocTy RetTypeLoc = Lex.getLoc();
2668193323Sed  if (ParseOptionalLinkage(Linkage) ||
2669193323Sed      ParseOptionalVisibility(Visibility) ||
2670193323Sed      ParseOptionalCallingConv(CC) ||
2671193323Sed      ParseOptionalAttrs(RetAttrs, 1) ||
2672193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2673193323Sed    return true;
2674193323Sed
2675193323Sed  // Verify that the linkage is ok.
2676193323Sed  switch ((GlobalValue::LinkageTypes)Linkage) {
2677193323Sed  case GlobalValue::ExternalLinkage:
2678193323Sed    break; // always ok.
2679193323Sed  case GlobalValue::DLLImportLinkage:
2680193323Sed  case GlobalValue::ExternalWeakLinkage:
2681193323Sed    if (isDefine)
2682193323Sed      return Error(LinkageLoc, "invalid linkage for function definition");
2683193323Sed    break;
2684193323Sed  case GlobalValue::PrivateLinkage:
2685198090Srdivacky  case GlobalValue::LinkerPrivateLinkage:
2686210299Sed  case GlobalValue::LinkerPrivateWeakLinkage:
2687212904Sdim  case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2688193323Sed  case GlobalValue::InternalLinkage:
2689193323Sed  case GlobalValue::AvailableExternallyLinkage:
2690193323Sed  case GlobalValue::LinkOnceAnyLinkage:
2691193323Sed  case GlobalValue::LinkOnceODRLinkage:
2692193323Sed  case GlobalValue::WeakAnyLinkage:
2693193323Sed  case GlobalValue::WeakODRLinkage:
2694193323Sed  case GlobalValue::DLLExportLinkage:
2695193323Sed    if (!isDefine)
2696193323Sed      return Error(LinkageLoc, "invalid linkage for function declaration");
2697193323Sed    break;
2698193323Sed  case GlobalValue::AppendingLinkage:
2699193323Sed  case GlobalValue::CommonLinkage:
2700193323Sed    return Error(LinkageLoc, "invalid function linkage type");
2701193323Sed  }
2702198090Srdivacky
2703193323Sed  if (!FunctionType::isValidReturnType(RetType) ||
2704204642Srdivacky      RetType->isOpaqueTy())
2705193323Sed    return Error(RetTypeLoc, "invalid function return type");
2706198090Srdivacky
2707193323Sed  LocTy NameLoc = Lex.getLoc();
2708193323Sed
2709193323Sed  std::string FunctionName;
2710193323Sed  if (Lex.getKind() == lltok::GlobalVar) {
2711193323Sed    FunctionName = Lex.getStrVal();
2712193323Sed  } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2713193323Sed    unsigned NameID = Lex.getUIntVal();
2714193323Sed
2715193323Sed    if (NameID != NumberedVals.size())
2716193323Sed      return TokError("function expected to be numbered '%" +
2717193323Sed                      utostr(NumberedVals.size()) + "'");
2718193323Sed  } else {
2719193323Sed    return TokError("expected function name");
2720193323Sed  }
2721198090Srdivacky
2722193323Sed  Lex.Lex();
2723198090Srdivacky
2724193323Sed  if (Lex.getKind() != lltok::lparen)
2725193323Sed    return TokError("expected '(' in function argument list");
2726198090Srdivacky
2727193323Sed  std::vector<ArgInfo> ArgList;
2728193323Sed  bool isVarArg;
2729193323Sed  unsigned FuncAttrs;
2730193323Sed  std::string Section;
2731193323Sed  unsigned Alignment;
2732193323Sed  std::string GC;
2733193323Sed
2734193323Sed  if (ParseArgumentList(ArgList, isVarArg, false) ||
2735193323Sed      ParseOptionalAttrs(FuncAttrs, 2) ||
2736193323Sed      (EatIfPresent(lltok::kw_section) &&
2737193323Sed       ParseStringConstant(Section)) ||
2738193323Sed      ParseOptionalAlignment(Alignment) ||
2739193323Sed      (EatIfPresent(lltok::kw_gc) &&
2740193323Sed       ParseStringConstant(GC)))
2741193323Sed    return true;
2742193323Sed
2743193323Sed  // If the alignment was parsed as an attribute, move to the alignment field.
2744193323Sed  if (FuncAttrs & Attribute::Alignment) {
2745193323Sed    Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2746193323Sed    FuncAttrs &= ~Attribute::Alignment;
2747193323Sed  }
2748198090Srdivacky
2749193323Sed  // Okay, if we got here, the function is syntactically valid.  Convert types
2750193323Sed  // and do semantic checks.
2751193323Sed  std::vector<const Type*> ParamTypeList;
2752193323Sed  SmallVector<AttributeWithIndex, 8> Attrs;
2753198090Srdivacky  // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2754193323Sed  // attributes.
2755193323Sed  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2756193323Sed  if (FuncAttrs & ObsoleteFuncAttrs) {
2757193323Sed    RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2758193323Sed    FuncAttrs &= ~ObsoleteFuncAttrs;
2759193323Sed  }
2760198090Srdivacky
2761193323Sed  if (RetAttrs != Attribute::None)
2762193323Sed    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2763198090Srdivacky
2764193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2765193323Sed    ParamTypeList.push_back(ArgList[i].Type);
2766193323Sed    if (ArgList[i].Attrs != Attribute::None)
2767193323Sed      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2768193323Sed  }
2769193323Sed
2770193323Sed  if (FuncAttrs != Attribute::None)
2771193323Sed    Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2772193323Sed
2773193323Sed  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2774198090Srdivacky
2775202375Srdivacky  if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2776198090Srdivacky    return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2777198090Srdivacky
2778195340Sed  const FunctionType *FT =
2779198090Srdivacky    FunctionType::get(RetType, ParamTypeList, isVarArg);
2780198090Srdivacky  const PointerType *PFT = PointerType::getUnqual(FT);
2781193323Sed
2782193323Sed  Fn = 0;
2783193323Sed  if (!FunctionName.empty()) {
2784193323Sed    // If this was a definition of a forward reference, remove the definition
2785193323Sed    // from the forward reference table and fill in the forward ref.
2786193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2787193323Sed      ForwardRefVals.find(FunctionName);
2788193323Sed    if (FRVI != ForwardRefVals.end()) {
2789193323Sed      Fn = M->getFunction(FunctionName);
2790207618Srdivacky      if (Fn->getType() != PFT)
2791207618Srdivacky        return Error(FRVI->second.second, "invalid forward reference to "
2792207618Srdivacky                     "function '" + FunctionName + "' with wrong type!");
2793207618Srdivacky
2794193323Sed      ForwardRefVals.erase(FRVI);
2795193323Sed    } else if ((Fn = M->getFunction(FunctionName))) {
2796193323Sed      // If this function already exists in the symbol table, then it is
2797193323Sed      // multiply defined.  We accept a few cases for old backwards compat.
2798193323Sed      // FIXME: Remove this stuff for LLVM 3.0.
2799193323Sed      if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2800193323Sed          (!Fn->isDeclaration() && isDefine)) {
2801193323Sed        // If the redefinition has different type or different attributes,
2802193323Sed        // reject it.  If both have bodies, reject it.
2803193323Sed        return Error(NameLoc, "invalid redefinition of function '" +
2804193323Sed                     FunctionName + "'");
2805193323Sed      } else if (Fn->isDeclaration()) {
2806193323Sed        // Make sure to strip off any argument names so we can't get conflicts.
2807193323Sed        for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2808193323Sed             AI != AE; ++AI)
2809193323Sed          AI->setName("");
2810193323Sed      }
2811198892Srdivacky    } else if (M->getNamedValue(FunctionName)) {
2812198892Srdivacky      return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2813193323Sed    }
2814198090Srdivacky
2815198090Srdivacky  } else {
2816193323Sed    // If this is a definition of a forward referenced function, make sure the
2817193323Sed    // types agree.
2818193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2819193323Sed      = ForwardRefValIDs.find(NumberedVals.size());
2820193323Sed    if (I != ForwardRefValIDs.end()) {
2821193323Sed      Fn = cast<Function>(I->second.first);
2822193323Sed      if (Fn->getType() != PFT)
2823193323Sed        return Error(NameLoc, "type of definition and forward reference of '@" +
2824193323Sed                     utostr(NumberedVals.size()) +"' disagree");
2825193323Sed      ForwardRefValIDs.erase(I);
2826193323Sed    }
2827193323Sed  }
2828193323Sed
2829193323Sed  if (Fn == 0)
2830193323Sed    Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2831193323Sed  else // Move the forward-reference to the correct spot in the module.
2832193323Sed    M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2833193323Sed
2834193323Sed  if (FunctionName.empty())
2835193323Sed    NumberedVals.push_back(Fn);
2836198090Srdivacky
2837193323Sed  Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2838193323Sed  Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2839193323Sed  Fn->setCallingConv(CC);
2840193323Sed  Fn->setAttributes(PAL);
2841193323Sed  Fn->setAlignment(Alignment);
2842193323Sed  Fn->setSection(Section);
2843193323Sed  if (!GC.empty()) Fn->setGC(GC.c_str());
2844198090Srdivacky
2845193323Sed  // Add all of the arguments we parsed to the function.
2846193323Sed  Function::arg_iterator ArgIt = Fn->arg_begin();
2847193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2848199989Srdivacky    // If we run out of arguments in the Function prototype, exit early.
2849199989Srdivacky    // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2850199989Srdivacky    if (ArgIt == Fn->arg_end()) break;
2851199989Srdivacky
2852193323Sed    // If the argument has a name, insert it into the argument symbol table.
2853193323Sed    if (ArgList[i].Name.empty()) continue;
2854198090Srdivacky
2855193323Sed    // Set the name, if it conflicted, it will be auto-renamed.
2856193323Sed    ArgIt->setName(ArgList[i].Name);
2857198090Srdivacky
2858193323Sed    if (ArgIt->getNameStr() != ArgList[i].Name)
2859193323Sed      return Error(ArgList[i].Loc, "redefinition of argument '%" +
2860193323Sed                   ArgList[i].Name + "'");
2861193323Sed  }
2862198090Srdivacky
2863193323Sed  return false;
2864193323Sed}
2865193323Sed
2866193323Sed
2867193323Sed/// ParseFunctionBody
2868193323Sed///   ::= '{' BasicBlock+ '}'
2869193323Sed///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2870193323Sed///
2871193323Sedbool LLParser::ParseFunctionBody(Function &Fn) {
2872193323Sed  if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2873193323Sed    return TokError("expected '{' in function body");
2874193323Sed  Lex.Lex();  // eat the {.
2875198090Srdivacky
2876198892Srdivacky  int FunctionNumber = -1;
2877198892Srdivacky  if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2878198892Srdivacky
2879198892Srdivacky  PerFunctionState PFS(*this, Fn, FunctionNumber);
2880198090Srdivacky
2881202375Srdivacky  // We need at least one basic block.
2882202375Srdivacky  if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2883202375Srdivacky    return TokError("function body requires at least one basic block");
2884202375Srdivacky
2885193323Sed  while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2886193323Sed    if (ParseBasicBlock(PFS)) return true;
2887198090Srdivacky
2888193323Sed  // Eat the }.
2889193323Sed  Lex.Lex();
2890198090Srdivacky
2891193323Sed  // Verify function is ok.
2892198892Srdivacky  return PFS.FinishFunction();
2893193323Sed}
2894193323Sed
2895193323Sed/// ParseBasicBlock
2896193323Sed///   ::= LabelStr? Instruction*
2897193323Sedbool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2898193323Sed  // If this basic block starts out with a name, remember it.
2899193323Sed  std::string Name;
2900193323Sed  LocTy NameLoc = Lex.getLoc();
2901193323Sed  if (Lex.getKind() == lltok::LabelStr) {
2902193323Sed    Name = Lex.getStrVal();
2903193323Sed    Lex.Lex();
2904193323Sed  }
2905198090Srdivacky
2906193323Sed  BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2907193323Sed  if (BB == 0) return true;
2908198090Srdivacky
2909193323Sed  std::string NameStr;
2910198090Srdivacky
2911193323Sed  // Parse the instructions in this block until we get a terminator.
2912193323Sed  Instruction *Inst;
2913201360Srdivacky  SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2914193323Sed  do {
2915193323Sed    // This instruction may have three possibilities for a name: a) none
2916193323Sed    // specified, b) name specified "%foo =", c) number specified: "%4 =".
2917193323Sed    LocTy NameLoc = Lex.getLoc();
2918193323Sed    int NameID = -1;
2919193323Sed    NameStr = "";
2920198090Srdivacky
2921193323Sed    if (Lex.getKind() == lltok::LocalVarID) {
2922193323Sed      NameID = Lex.getUIntVal();
2923193323Sed      Lex.Lex();
2924193323Sed      if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2925193323Sed        return true;
2926193323Sed    } else if (Lex.getKind() == lltok::LocalVar ||
2927193323Sed               // FIXME: REMOVE IN LLVM 3.0
2928193323Sed               Lex.getKind() == lltok::StringConstant) {
2929193323Sed      NameStr = Lex.getStrVal();
2930193323Sed      Lex.Lex();
2931193323Sed      if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2932193323Sed        return true;
2933193323Sed    }
2934198090Srdivacky
2935201360Srdivacky    switch (ParseInstruction(Inst, BB, PFS)) {
2936201360Srdivacky    default: assert(0 && "Unknown ParseInstruction result!");
2937201360Srdivacky    case InstError: return true;
2938201360Srdivacky    case InstNormal:
2939207618Srdivacky      BB->getInstList().push_back(Inst);
2940207618Srdivacky
2941201360Srdivacky      // With a normal result, we check to see if the instruction is followed by
2942201360Srdivacky      // a comma and metadata.
2943201360Srdivacky      if (EatIfPresent(lltok::comma))
2944212904Sdim        if (ParseInstructionMetadata(Inst, &PFS))
2945201360Srdivacky          return true;
2946201360Srdivacky      break;
2947201360Srdivacky    case InstExtraComma:
2948207618Srdivacky      BB->getInstList().push_back(Inst);
2949207618Srdivacky
2950201360Srdivacky      // If the instruction parser ate an extra comma at the end of it, it
2951201360Srdivacky      // *must* be followed by metadata.
2952212904Sdim      if (ParseInstructionMetadata(Inst, &PFS))
2953201360Srdivacky        return true;
2954201360Srdivacky      break;
2955201360Srdivacky    }
2956198090Srdivacky
2957193323Sed    // Set the name on the instruction.
2958193323Sed    if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2959193323Sed  } while (!isa<TerminatorInst>(Inst));
2960198090Srdivacky
2961193323Sed  return false;
2962193323Sed}
2963193323Sed
2964193323Sed//===----------------------------------------------------------------------===//
2965193323Sed// Instruction Parsing.
2966193323Sed//===----------------------------------------------------------------------===//
2967193323Sed
2968193323Sed/// ParseInstruction - Parse one of the many different instructions.
2969193323Sed///
2970201360Srdivackyint LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2971201360Srdivacky                               PerFunctionState &PFS) {
2972193323Sed  lltok::Kind Token = Lex.getKind();
2973193323Sed  if (Token == lltok::Eof)
2974193323Sed    return TokError("found end of file when expecting more instructions");
2975193323Sed  LocTy Loc = Lex.getLoc();
2976193323Sed  unsigned KeywordVal = Lex.getUIntVal();
2977193323Sed  Lex.Lex();  // Eat the keyword.
2978198090Srdivacky
2979193323Sed  switch (Token) {
2980193323Sed  default:                    return Error(Loc, "expected instruction opcode");
2981193323Sed  // Terminator Instructions.
2982198090Srdivacky  case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
2983198090Srdivacky  case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2984193323Sed  case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2985193323Sed  case lltok::kw_br:          return ParseBr(Inst, PFS);
2986193323Sed  case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2987198892Srdivacky  case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
2988193323Sed  case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2989193323Sed  // Binary Operators.
2990193323Sed  case lltok::kw_add:
2991193323Sed  case lltok::kw_sub:
2992198090Srdivacky  case lltok::kw_mul: {
2993198090Srdivacky    bool NUW = false;
2994198090Srdivacky    bool NSW = false;
2995198090Srdivacky    LocTy ModifierLoc = Lex.getLoc();
2996198090Srdivacky    if (EatIfPresent(lltok::kw_nuw))
2997198090Srdivacky      NUW = true;
2998198090Srdivacky    if (EatIfPresent(lltok::kw_nsw)) {
2999198090Srdivacky      NSW = true;
3000198090Srdivacky      if (EatIfPresent(lltok::kw_nuw))
3001198090Srdivacky        NUW = true;
3002198090Srdivacky    }
3003207618Srdivacky    bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3004198090Srdivacky    if (!Result) {
3005203954Srdivacky      if (!Inst->getType()->isIntOrIntVectorTy()) {
3006198090Srdivacky        if (NUW)
3007198090Srdivacky          return Error(ModifierLoc, "nuw only applies to integer operations");
3008198090Srdivacky        if (NSW)
3009198090Srdivacky          return Error(ModifierLoc, "nsw only applies to integer operations");
3010198090Srdivacky      }
3011198090Srdivacky      if (NUW)
3012198090Srdivacky        cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3013198090Srdivacky      if (NSW)
3014198090Srdivacky        cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3015198090Srdivacky    }
3016198090Srdivacky    return Result;
3017198090Srdivacky  }
3018193574Sed  case lltok::kw_fadd:
3019193574Sed  case lltok::kw_fsub:
3020193574Sed  case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3021193574Sed
3022198090Srdivacky  case lltok::kw_sdiv: {
3023198090Srdivacky    bool Exact = false;
3024198090Srdivacky    if (EatIfPresent(lltok::kw_exact))
3025198090Srdivacky      Exact = true;
3026198090Srdivacky    bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3027198090Srdivacky    if (!Result)
3028198090Srdivacky      if (Exact)
3029198090Srdivacky        cast<BinaryOperator>(Inst)->setIsExact(true);
3030198090Srdivacky    return Result;
3031198090Srdivacky  }
3032198090Srdivacky
3033193323Sed  case lltok::kw_udiv:
3034193323Sed  case lltok::kw_urem:
3035193323Sed  case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3036193323Sed  case lltok::kw_fdiv:
3037193323Sed  case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3038193323Sed  case lltok::kw_shl:
3039193323Sed  case lltok::kw_lshr:
3040193323Sed  case lltok::kw_ashr:
3041193323Sed  case lltok::kw_and:
3042193323Sed  case lltok::kw_or:
3043193323Sed  case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
3044193323Sed  case lltok::kw_icmp:
3045198090Srdivacky  case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
3046193323Sed  // Casts.
3047193323Sed  case lltok::kw_trunc:
3048193323Sed  case lltok::kw_zext:
3049193323Sed  case lltok::kw_sext:
3050193323Sed  case lltok::kw_fptrunc:
3051193323Sed  case lltok::kw_fpext:
3052193323Sed  case lltok::kw_bitcast:
3053193323Sed  case lltok::kw_uitofp:
3054193323Sed  case lltok::kw_sitofp:
3055193323Sed  case lltok::kw_fptoui:
3056198090Srdivacky  case lltok::kw_fptosi:
3057193323Sed  case lltok::kw_inttoptr:
3058193323Sed  case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
3059193323Sed  // Other.
3060193323Sed  case lltok::kw_select:         return ParseSelect(Inst, PFS);
3061193323Sed  case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
3062193323Sed  case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3063193323Sed  case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
3064193323Sed  case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
3065193323Sed  case lltok::kw_phi:            return ParsePHI(Inst, PFS);
3066193323Sed  case lltok::kw_call:           return ParseCall(Inst, PFS, false);
3067193323Sed  case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
3068193323Sed  // Memory.
3069198396Srdivacky  case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
3070198396Srdivacky  case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, BB, false);
3071198892Srdivacky  case lltok::kw_free:           return ParseFree(Inst, PFS, BB);
3072193323Sed  case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
3073193323Sed  case lltok::kw_store:          return ParseStore(Inst, PFS, false);
3074193323Sed  case lltok::kw_volatile:
3075193323Sed    if (EatIfPresent(lltok::kw_load))
3076193323Sed      return ParseLoad(Inst, PFS, true);
3077193323Sed    else if (EatIfPresent(lltok::kw_store))
3078193323Sed      return ParseStore(Inst, PFS, true);
3079193323Sed    else
3080193323Sed      return TokError("expected 'load' or 'store'");
3081193323Sed  case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
3082193323Sed  case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3083193323Sed  case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
3084193323Sed  case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
3085193323Sed  }
3086193323Sed}
3087193323Sed
3088193323Sed/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3089193323Sedbool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3090198090Srdivacky  if (Opc == Instruction::FCmp) {
3091193323Sed    switch (Lex.getKind()) {
3092193323Sed    default: TokError("expected fcmp predicate (e.g. 'oeq')");
3093193323Sed    case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3094193323Sed    case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3095193323Sed    case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3096193323Sed    case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3097193323Sed    case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3098193323Sed    case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3099193323Sed    case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3100193323Sed    case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3101193323Sed    case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3102193323Sed    case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3103193323Sed    case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3104193323Sed    case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3105193323Sed    case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3106193323Sed    case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3107193323Sed    case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3108193323Sed    case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3109193323Sed    }
3110193323Sed  } else {
3111193323Sed    switch (Lex.getKind()) {
3112193323Sed    default: TokError("expected icmp predicate (e.g. 'eq')");
3113193323Sed    case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
3114193323Sed    case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
3115193323Sed    case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3116193323Sed    case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3117193323Sed    case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3118193323Sed    case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3119193323Sed    case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3120193323Sed    case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3121193323Sed    case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3122193323Sed    case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3123193323Sed    }
3124193323Sed  }
3125193323Sed  Lex.Lex();
3126193323Sed  return false;
3127193323Sed}
3128193323Sed
3129193323Sed//===----------------------------------------------------------------------===//
3130193323Sed// Terminator Instructions.
3131193323Sed//===----------------------------------------------------------------------===//
3132193323Sed
3133193323Sed/// ParseRet - Parse a return instruction.
3134201360Srdivacky///   ::= 'ret' void (',' !dbg, !1)*
3135201360Srdivacky///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
3136201360Srdivacky///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  (',' !dbg, !1)*
3137198090Srdivacky///         [[obsolete: LLVM 3.0]]
3138201360Srdivackyint LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3139201360Srdivacky                       PerFunctionState &PFS) {
3140198090Srdivacky  PATypeHolder Ty(Type::getVoidTy(Context));
3141193323Sed  if (ParseType(Ty, true /*void allowed*/)) return true;
3142198090Srdivacky
3143198090Srdivacky  if (Ty->isVoidTy()) {
3144198090Srdivacky    Inst = ReturnInst::Create(Context);
3145193323Sed    return false;
3146193323Sed  }
3147198090Srdivacky
3148193323Sed  Value *RV;
3149193323Sed  if (ParseValue(Ty, RV, PFS)) return true;
3150198090Srdivacky
3151201360Srdivacky  bool ExtraComma = false;
3152198090Srdivacky  if (EatIfPresent(lltok::comma)) {
3153198090Srdivacky    // Parse optional custom metadata, e.g. !dbg
3154201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
3155201360Srdivacky      ExtraComma = true;
3156198090Srdivacky    } else {
3157198090Srdivacky      // The normal case is one return value.
3158201360Srdivacky      // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3159201360Srdivacky      // use of 'ret {i32,i32} {i32 1, i32 2}'
3160198090Srdivacky      SmallVector<Value*, 8> RVs;
3161193323Sed      RVs.push_back(RV);
3162193323Sed
3163198090Srdivacky      do {
3164198090Srdivacky        // If optional custom metadata, e.g. !dbg is seen then this is the
3165198090Srdivacky        // end of MRV.
3166201360Srdivacky        if (Lex.getKind() == lltok::MetadataVar)
3167198090Srdivacky          break;
3168198090Srdivacky        if (ParseTypeAndValue(RV, PFS)) return true;
3169198090Srdivacky        RVs.push_back(RV);
3170198090Srdivacky      } while (EatIfPresent(lltok::comma));
3171198090Srdivacky
3172198090Srdivacky      RV = UndefValue::get(PFS.getFunction().getReturnType());
3173198090Srdivacky      for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3174198090Srdivacky        Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3175198090Srdivacky        BB->getInstList().push_back(I);
3176198090Srdivacky        RV = I;
3177198090Srdivacky      }
3178193323Sed    }
3179193323Sed  }
3180198090Srdivacky
3181198090Srdivacky  Inst = ReturnInst::Create(Context, RV);
3182201360Srdivacky  return ExtraComma ? InstExtraComma : InstNormal;
3183193323Sed}
3184193323Sed
3185193323Sed
3186193323Sed/// ParseBr
3187193323Sed///   ::= 'br' TypeAndValue
3188193323Sed///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3189193323Sedbool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3190193323Sed  LocTy Loc, Loc2;
3191198892Srdivacky  Value *Op0;
3192198892Srdivacky  BasicBlock *Op1, *Op2;
3193193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3194198090Srdivacky
3195193323Sed  if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3196193323Sed    Inst = BranchInst::Create(BB);
3197193323Sed    return false;
3198193323Sed  }
3199198090Srdivacky
3200198090Srdivacky  if (Op0->getType() != Type::getInt1Ty(Context))
3201193323Sed    return Error(Loc, "branch condition must have 'i1' type");
3202198090Srdivacky
3203193323Sed  if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3204198892Srdivacky      ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3205193323Sed      ParseToken(lltok::comma, "expected ',' after true destination") ||
3206198892Srdivacky      ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3207193323Sed    return true;
3208198090Srdivacky
3209198892Srdivacky  Inst = BranchInst::Create(Op1, Op2, Op0);
3210193323Sed  return false;
3211193323Sed}
3212193323Sed
3213193323Sed/// ParseSwitch
3214193323Sed///  Instruction
3215193323Sed///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3216193323Sed///  JumpTable
3217193323Sed///    ::= (TypeAndValue ',' TypeAndValue)*
3218193323Sedbool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3219193323Sed  LocTy CondLoc, BBLoc;
3220198892Srdivacky  Value *Cond;
3221198892Srdivacky  BasicBlock *DefaultBB;
3222193323Sed  if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3223193323Sed      ParseToken(lltok::comma, "expected ',' after switch condition") ||
3224198892Srdivacky      ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3225193323Sed      ParseToken(lltok::lsquare, "expected '[' with switch table"))
3226193323Sed    return true;
3227193323Sed
3228204642Srdivacky  if (!Cond->getType()->isIntegerTy())
3229193323Sed    return Error(CondLoc, "switch condition must have integer type");
3230198090Srdivacky
3231193323Sed  // Parse the jump table pairs.
3232193323Sed  SmallPtrSet<Value*, 32> SeenCases;
3233193323Sed  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3234193323Sed  while (Lex.getKind() != lltok::rsquare) {
3235198892Srdivacky    Value *Constant;
3236198892Srdivacky    BasicBlock *DestBB;
3237198090Srdivacky
3238193323Sed    if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3239193323Sed        ParseToken(lltok::comma, "expected ',' after case value") ||
3240198892Srdivacky        ParseTypeAndBasicBlock(DestBB, PFS))
3241193323Sed      return true;
3242198892Srdivacky
3243193323Sed    if (!SeenCases.insert(Constant))
3244193323Sed      return Error(CondLoc, "duplicate case value in switch");
3245193323Sed    if (!isa<ConstantInt>(Constant))
3246193323Sed      return Error(CondLoc, "case value is not a constant integer");
3247198090Srdivacky
3248198892Srdivacky    Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3249193323Sed  }
3250198090Srdivacky
3251193323Sed  Lex.Lex();  // Eat the ']'.
3252198090Srdivacky
3253198892Srdivacky  SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3254193323Sed  for (unsigned i = 0, e = Table.size(); i != e; ++i)
3255193323Sed    SI->addCase(Table[i].first, Table[i].second);
3256193323Sed  Inst = SI;
3257193323Sed  return false;
3258193323Sed}
3259193323Sed
3260198892Srdivacky/// ParseIndirectBr
3261198892Srdivacky///  Instruction
3262198892Srdivacky///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3263198892Srdivackybool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3264198892Srdivacky  LocTy AddrLoc;
3265198892Srdivacky  Value *Address;
3266198892Srdivacky  if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3267198892Srdivacky      ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3268198892Srdivacky      ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3269198892Srdivacky    return true;
3270198892Srdivacky
3271204642Srdivacky  if (!Address->getType()->isPointerTy())
3272198892Srdivacky    return Error(AddrLoc, "indirectbr address must have pointer type");
3273198892Srdivacky
3274198892Srdivacky  // Parse the destination list.
3275198892Srdivacky  SmallVector<BasicBlock*, 16> DestList;
3276198892Srdivacky
3277198892Srdivacky  if (Lex.getKind() != lltok::rsquare) {
3278198892Srdivacky    BasicBlock *DestBB;
3279198892Srdivacky    if (ParseTypeAndBasicBlock(DestBB, PFS))
3280198892Srdivacky      return true;
3281198892Srdivacky    DestList.push_back(DestBB);
3282198892Srdivacky
3283198892Srdivacky    while (EatIfPresent(lltok::comma)) {
3284198892Srdivacky      if (ParseTypeAndBasicBlock(DestBB, PFS))
3285198892Srdivacky        return true;
3286198892Srdivacky      DestList.push_back(DestBB);
3287198892Srdivacky    }
3288198892Srdivacky  }
3289198892Srdivacky
3290198892Srdivacky  if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3291198892Srdivacky    return true;
3292198892Srdivacky
3293198892Srdivacky  IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3294198892Srdivacky  for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3295198892Srdivacky    IBI->addDestination(DestList[i]);
3296198892Srdivacky  Inst = IBI;
3297198892Srdivacky  return false;
3298198892Srdivacky}
3299198892Srdivacky
3300198892Srdivacky
3301193323Sed/// ParseInvoke
3302193323Sed///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3303193323Sed///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3304193323Sedbool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3305193323Sed  LocTy CallLoc = Lex.getLoc();
3306198090Srdivacky  unsigned RetAttrs, FnAttrs;
3307198090Srdivacky  CallingConv::ID CC;
3308198090Srdivacky  PATypeHolder RetType(Type::getVoidTy(Context));
3309193323Sed  LocTy RetTypeLoc;
3310193323Sed  ValID CalleeID;
3311193323Sed  SmallVector<ParamInfo, 16> ArgList;
3312193323Sed
3313198892Srdivacky  BasicBlock *NormalBB, *UnwindBB;
3314193323Sed  if (ParseOptionalCallingConv(CC) ||
3315193323Sed      ParseOptionalAttrs(RetAttrs, 1) ||
3316193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3317193323Sed      ParseValID(CalleeID) ||
3318193323Sed      ParseParameterList(ArgList, PFS) ||
3319193323Sed      ParseOptionalAttrs(FnAttrs, 2) ||
3320193323Sed      ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3321198892Srdivacky      ParseTypeAndBasicBlock(NormalBB, PFS) ||
3322193323Sed      ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3323198892Srdivacky      ParseTypeAndBasicBlock(UnwindBB, PFS))
3324193323Sed    return true;
3325198090Srdivacky
3326193323Sed  // If RetType is a non-function pointer type, then this is the short syntax
3327193323Sed  // for the call, which means that RetType is just the return type.  Infer the
3328193323Sed  // rest of the function argument types from the arguments that are present.
3329193323Sed  const PointerType *PFTy = 0;
3330193323Sed  const FunctionType *Ty = 0;
3331193323Sed  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3332193323Sed      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3333193323Sed    // Pull out the types of all of the arguments...
3334193323Sed    std::vector<const Type*> ParamTypes;
3335193323Sed    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3336193323Sed      ParamTypes.push_back(ArgList[i].V->getType());
3337198090Srdivacky
3338193323Sed    if (!FunctionType::isValidReturnType(RetType))
3339193323Sed      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3340198090Srdivacky
3341198090Srdivacky    Ty = FunctionType::get(RetType, ParamTypes, false);
3342198090Srdivacky    PFTy = PointerType::getUnqual(Ty);
3343193323Sed  }
3344198090Srdivacky
3345193323Sed  // Look up the callee.
3346193323Sed  Value *Callee;
3347202375Srdivacky  if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3348198090Srdivacky
3349193323Sed  // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3350193323Sed  // function attributes.
3351193323Sed  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3352193323Sed  if (FnAttrs & ObsoleteFuncAttrs) {
3353193323Sed    RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3354193323Sed    FnAttrs &= ~ObsoleteFuncAttrs;
3355193323Sed  }
3356198090Srdivacky
3357193323Sed  // Set up the Attributes for the function.
3358193323Sed  SmallVector<AttributeWithIndex, 8> Attrs;
3359193323Sed  if (RetAttrs != Attribute::None)
3360193323Sed    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3361198090Srdivacky
3362193323Sed  SmallVector<Value*, 8> Args;
3363198090Srdivacky
3364193323Sed  // Loop through FunctionType's arguments and ensure they are specified
3365193323Sed  // correctly.  Also, gather any parameter attributes.
3366193323Sed  FunctionType::param_iterator I = Ty->param_begin();
3367193323Sed  FunctionType::param_iterator E = Ty->param_end();
3368193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3369193323Sed    const Type *ExpectedTy = 0;
3370193323Sed    if (I != E) {
3371193323Sed      ExpectedTy = *I++;
3372193323Sed    } else if (!Ty->isVarArg()) {
3373193323Sed      return Error(ArgList[i].Loc, "too many arguments specified");
3374193323Sed    }
3375198090Srdivacky
3376193323Sed    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3377193323Sed      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3378193323Sed                   ExpectedTy->getDescription() + "'");
3379193323Sed    Args.push_back(ArgList[i].V);
3380193323Sed    if (ArgList[i].Attrs != Attribute::None)
3381193323Sed      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3382193323Sed  }
3383198090Srdivacky
3384193323Sed  if (I != E)
3385193323Sed    return Error(CallLoc, "not enough parameters specified for call");
3386198090Srdivacky
3387193323Sed  if (FnAttrs != Attribute::None)
3388193323Sed    Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3389198090Srdivacky
3390193323Sed  // Finish off the Attributes and check them
3391193323Sed  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3392198090Srdivacky
3393198892Srdivacky  InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3394193323Sed                                      Args.begin(), Args.end());
3395193323Sed  II->setCallingConv(CC);
3396193323Sed  II->setAttributes(PAL);
3397193323Sed  Inst = II;
3398193323Sed  return false;
3399193323Sed}
3400193323Sed
3401193323Sed
3402193323Sed
3403193323Sed//===----------------------------------------------------------------------===//
3404193323Sed// Binary Operators.
3405193323Sed//===----------------------------------------------------------------------===//
3406193323Sed
3407193323Sed/// ParseArithmetic
3408193323Sed///  ::= ArithmeticOps TypeAndValue ',' Value
3409193323Sed///
3410193323Sed/// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3411193323Sed/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3412193323Sedbool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3413193323Sed                               unsigned Opc, unsigned OperandType) {
3414193323Sed  LocTy Loc; Value *LHS, *RHS;
3415193323Sed  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3416193323Sed      ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3417193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3418193323Sed    return true;
3419193323Sed
3420193323Sed  bool Valid;
3421193323Sed  switch (OperandType) {
3422198090Srdivacky  default: llvm_unreachable("Unknown operand type!");
3423193323Sed  case 0: // int or FP.
3424203954Srdivacky    Valid = LHS->getType()->isIntOrIntVectorTy() ||
3425203954Srdivacky            LHS->getType()->isFPOrFPVectorTy();
3426193323Sed    break;
3427203954Srdivacky  case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3428203954Srdivacky  case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3429193323Sed  }
3430198090Srdivacky
3431193323Sed  if (!Valid)
3432193323Sed    return Error(Loc, "invalid operand type for instruction");
3433198090Srdivacky
3434193323Sed  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3435193323Sed  return false;
3436193323Sed}
3437193323Sed
3438193323Sed/// ParseLogical
3439193323Sed///  ::= ArithmeticOps TypeAndValue ',' Value {
3440193323Sedbool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3441193323Sed                            unsigned Opc) {
3442193323Sed  LocTy Loc; Value *LHS, *RHS;
3443193323Sed  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3444193323Sed      ParseToken(lltok::comma, "expected ',' in logical operation") ||
3445193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3446193323Sed    return true;
3447193323Sed
3448203954Srdivacky  if (!LHS->getType()->isIntOrIntVectorTy())
3449193323Sed    return Error(Loc,"instruction requires integer or integer vector operands");
3450193323Sed
3451193323Sed  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3452193323Sed  return false;
3453193323Sed}
3454193323Sed
3455193323Sed
3456193323Sed/// ParseCompare
3457193323Sed///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3458193323Sed///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3459193323Sedbool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3460193323Sed                            unsigned Opc) {
3461193323Sed  // Parse the integer/fp comparison predicate.
3462193323Sed  LocTy Loc;
3463193323Sed  unsigned Pred;
3464193323Sed  Value *LHS, *RHS;
3465193323Sed  if (ParseCmpPredicate(Pred, Opc) ||
3466193323Sed      ParseTypeAndValue(LHS, Loc, PFS) ||
3467193323Sed      ParseToken(lltok::comma, "expected ',' after compare value") ||
3468193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3469193323Sed    return true;
3470198090Srdivacky
3471193323Sed  if (Opc == Instruction::FCmp) {
3472203954Srdivacky    if (!LHS->getType()->isFPOrFPVectorTy())
3473193323Sed      return Error(Loc, "fcmp requires floating point operands");
3474193323Sed    Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3475198090Srdivacky  } else {
3476198090Srdivacky    assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3477203954Srdivacky    if (!LHS->getType()->isIntOrIntVectorTy() &&
3478204642Srdivacky        !LHS->getType()->isPointerTy())
3479193323Sed      return Error(Loc, "icmp requires integer operands");
3480193323Sed    Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3481193323Sed  }
3482193323Sed  return false;
3483193323Sed}
3484193323Sed
3485193323Sed//===----------------------------------------------------------------------===//
3486193323Sed// Other Instructions.
3487193323Sed//===----------------------------------------------------------------------===//
3488193323Sed
3489193323Sed
3490193323Sed/// ParseCast
3491193323Sed///   ::= CastOpc TypeAndValue 'to' Type
3492193323Sedbool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3493193323Sed                         unsigned Opc) {
3494193323Sed  LocTy Loc;  Value *Op;
3495198090Srdivacky  PATypeHolder DestTy(Type::getVoidTy(Context));
3496193323Sed  if (ParseTypeAndValue(Op, Loc, PFS) ||
3497193323Sed      ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3498193323Sed      ParseType(DestTy))
3499193323Sed    return true;
3500198090Srdivacky
3501193323Sed  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3502193323Sed    CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3503193323Sed    return Error(Loc, "invalid cast opcode for cast from '" +
3504193323Sed                 Op->getType()->getDescription() + "' to '" +
3505193323Sed                 DestTy->getDescription() + "'");
3506193323Sed  }
3507193323Sed  Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3508193323Sed  return false;
3509193323Sed}
3510193323Sed
3511193323Sed/// ParseSelect
3512193323Sed///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3513193323Sedbool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3514193323Sed  LocTy Loc;
3515193323Sed  Value *Op0, *Op1, *Op2;
3516193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3517193323Sed      ParseToken(lltok::comma, "expected ',' after select condition") ||
3518193323Sed      ParseTypeAndValue(Op1, PFS) ||
3519193323Sed      ParseToken(lltok::comma, "expected ',' after select value") ||
3520193323Sed      ParseTypeAndValue(Op2, PFS))
3521193323Sed    return true;
3522198090Srdivacky
3523193323Sed  if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3524193323Sed    return Error(Loc, Reason);
3525198090Srdivacky
3526193323Sed  Inst = SelectInst::Create(Op0, Op1, Op2);
3527193323Sed  return false;
3528193323Sed}
3529193323Sed
3530193323Sed/// ParseVA_Arg
3531193323Sed///   ::= 'va_arg' TypeAndValue ',' Type
3532193323Sedbool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3533193323Sed  Value *Op;
3534198090Srdivacky  PATypeHolder EltTy(Type::getVoidTy(Context));
3535193323Sed  LocTy TypeLoc;
3536193323Sed  if (ParseTypeAndValue(Op, PFS) ||
3537193323Sed      ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3538193323Sed      ParseType(EltTy, TypeLoc))
3539193323Sed    return true;
3540198090Srdivacky
3541193323Sed  if (!EltTy->isFirstClassType())
3542193323Sed    return Error(TypeLoc, "va_arg requires operand with first class type");
3543193323Sed
3544193323Sed  Inst = new VAArgInst(Op, EltTy);
3545193323Sed  return false;
3546193323Sed}
3547193323Sed
3548193323Sed/// ParseExtractElement
3549193323Sed///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3550193323Sedbool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3551193323Sed  LocTy Loc;
3552193323Sed  Value *Op0, *Op1;
3553193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3554193323Sed      ParseToken(lltok::comma, "expected ',' after extract value") ||
3555193323Sed      ParseTypeAndValue(Op1, PFS))
3556193323Sed    return true;
3557198090Srdivacky
3558193323Sed  if (!ExtractElementInst::isValidOperands(Op0, Op1))
3559193323Sed    return Error(Loc, "invalid extractelement operands");
3560198090Srdivacky
3561198090Srdivacky  Inst = ExtractElementInst::Create(Op0, Op1);
3562193323Sed  return false;
3563193323Sed}
3564193323Sed
3565193323Sed/// ParseInsertElement
3566193323Sed///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3567193323Sedbool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3568193323Sed  LocTy Loc;
3569193323Sed  Value *Op0, *Op1, *Op2;
3570193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3571193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3572193323Sed      ParseTypeAndValue(Op1, PFS) ||
3573193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3574193323Sed      ParseTypeAndValue(Op2, PFS))
3575193323Sed    return true;
3576198090Srdivacky
3577193323Sed  if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3578198090Srdivacky    return Error(Loc, "invalid insertelement operands");
3579198090Srdivacky
3580193323Sed  Inst = InsertElementInst::Create(Op0, Op1, Op2);
3581193323Sed  return false;
3582193323Sed}
3583193323Sed
3584193323Sed/// ParseShuffleVector
3585193323Sed///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3586193323Sedbool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3587193323Sed  LocTy Loc;
3588193323Sed  Value *Op0, *Op1, *Op2;
3589193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3590193323Sed      ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3591193323Sed      ParseTypeAndValue(Op1, PFS) ||
3592193323Sed      ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3593193323Sed      ParseTypeAndValue(Op2, PFS))
3594193323Sed    return true;
3595198090Srdivacky
3596193323Sed  if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3597193323Sed    return Error(Loc, "invalid extractelement operands");
3598198090Srdivacky
3599193323Sed  Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3600193323Sed  return false;
3601193323Sed}
3602193323Sed
3603193323Sed/// ParsePHI
3604198396Srdivacky///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3605201360Srdivackyint LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3606198090Srdivacky  PATypeHolder Ty(Type::getVoidTy(Context));
3607193323Sed  Value *Op0, *Op1;
3608193323Sed  LocTy TypeLoc = Lex.getLoc();
3609198090Srdivacky
3610193323Sed  if (ParseType(Ty) ||
3611193323Sed      ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3612193323Sed      ParseValue(Ty, Op0, PFS) ||
3613193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3614198090Srdivacky      ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3615193323Sed      ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3616193323Sed    return true;
3617198090Srdivacky
3618201360Srdivacky  bool AteExtraComma = false;
3619193323Sed  SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3620193323Sed  while (1) {
3621193323Sed    PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3622198090Srdivacky
3623193323Sed    if (!EatIfPresent(lltok::comma))
3624193323Sed      break;
3625193323Sed
3626201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
3627201360Srdivacky      AteExtraComma = true;
3628198396Srdivacky      break;
3629201360Srdivacky    }
3630198396Srdivacky
3631193323Sed    if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3632193323Sed        ParseValue(Ty, Op0, PFS) ||
3633193323Sed        ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3634198090Srdivacky        ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3635193323Sed        ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3636193323Sed      return true;
3637193323Sed  }
3638198090Srdivacky
3639193323Sed  if (!Ty->isFirstClassType())
3640193323Sed    return Error(TypeLoc, "phi node must have first class type");
3641193323Sed
3642193323Sed  PHINode *PN = PHINode::Create(Ty);
3643193323Sed  PN->reserveOperandSpace(PHIVals.size());
3644193323Sed  for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3645193323Sed    PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3646193323Sed  Inst = PN;
3647201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3648193323Sed}
3649193323Sed
3650193323Sed/// ParseCall
3651193323Sed///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3652193323Sed///       ParameterList OptionalAttrs
3653193323Sedbool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3654193323Sed                         bool isTail) {
3655198090Srdivacky  unsigned RetAttrs, FnAttrs;
3656198090Srdivacky  CallingConv::ID CC;
3657198090Srdivacky  PATypeHolder RetType(Type::getVoidTy(Context));
3658193323Sed  LocTy RetTypeLoc;
3659193323Sed  ValID CalleeID;
3660193323Sed  SmallVector<ParamInfo, 16> ArgList;
3661193323Sed  LocTy CallLoc = Lex.getLoc();
3662198090Srdivacky
3663193323Sed  if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3664193323Sed      ParseOptionalCallingConv(CC) ||
3665193323Sed      ParseOptionalAttrs(RetAttrs, 1) ||
3666193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3667193323Sed      ParseValID(CalleeID) ||
3668193323Sed      ParseParameterList(ArgList, PFS) ||
3669193323Sed      ParseOptionalAttrs(FnAttrs, 2))
3670193323Sed    return true;
3671198090Srdivacky
3672193323Sed  // If RetType is a non-function pointer type, then this is the short syntax
3673193323Sed  // for the call, which means that RetType is just the return type.  Infer the
3674193323Sed  // rest of the function argument types from the arguments that are present.
3675193323Sed  const PointerType *PFTy = 0;
3676193323Sed  const FunctionType *Ty = 0;
3677193323Sed  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3678193323Sed      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3679193323Sed    // Pull out the types of all of the arguments...
3680193323Sed    std::vector<const Type*> ParamTypes;
3681193323Sed    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3682193323Sed      ParamTypes.push_back(ArgList[i].V->getType());
3683198090Srdivacky
3684193323Sed    if (!FunctionType::isValidReturnType(RetType))
3685193323Sed      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3686198090Srdivacky
3687198090Srdivacky    Ty = FunctionType::get(RetType, ParamTypes, false);
3688198090Srdivacky    PFTy = PointerType::getUnqual(Ty);
3689193323Sed  }
3690198090Srdivacky
3691193323Sed  // Look up the callee.
3692193323Sed  Value *Callee;
3693202375Srdivacky  if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3694198090Srdivacky
3695193323Sed  // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3696193323Sed  // function attributes.
3697193323Sed  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3698193323Sed  if (FnAttrs & ObsoleteFuncAttrs) {
3699193323Sed    RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3700193323Sed    FnAttrs &= ~ObsoleteFuncAttrs;
3701193323Sed  }
3702193323Sed
3703193323Sed  // Set up the Attributes for the function.
3704193323Sed  SmallVector<AttributeWithIndex, 8> Attrs;
3705193323Sed  if (RetAttrs != Attribute::None)
3706193323Sed    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3707198090Srdivacky
3708193323Sed  SmallVector<Value*, 8> Args;
3709198090Srdivacky
3710193323Sed  // Loop through FunctionType's arguments and ensure they are specified
3711193323Sed  // correctly.  Also, gather any parameter attributes.
3712193323Sed  FunctionType::param_iterator I = Ty->param_begin();
3713193323Sed  FunctionType::param_iterator E = Ty->param_end();
3714193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3715193323Sed    const Type *ExpectedTy = 0;
3716193323Sed    if (I != E) {
3717193323Sed      ExpectedTy = *I++;
3718193323Sed    } else if (!Ty->isVarArg()) {
3719193323Sed      return Error(ArgList[i].Loc, "too many arguments specified");
3720193323Sed    }
3721198090Srdivacky
3722193323Sed    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3723193323Sed      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3724193323Sed                   ExpectedTy->getDescription() + "'");
3725193323Sed    Args.push_back(ArgList[i].V);
3726193323Sed    if (ArgList[i].Attrs != Attribute::None)
3727193323Sed      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3728193323Sed  }
3729198090Srdivacky
3730193323Sed  if (I != E)
3731193323Sed    return Error(CallLoc, "not enough parameters specified for call");
3732193323Sed
3733193323Sed  if (FnAttrs != Attribute::None)
3734193323Sed    Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3735193323Sed
3736193323Sed  // Finish off the Attributes and check them
3737193323Sed  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3738198090Srdivacky
3739193323Sed  CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3740193323Sed  CI->setTailCall(isTail);
3741193323Sed  CI->setCallingConv(CC);
3742193323Sed  CI->setAttributes(PAL);
3743193323Sed  Inst = CI;
3744193323Sed  return false;
3745193323Sed}
3746193323Sed
3747193323Sed//===----------------------------------------------------------------------===//
3748193323Sed// Memory Instructions.
3749193323Sed//===----------------------------------------------------------------------===//
3750193323Sed
3751193323Sed/// ParseAlloc
3752198090Srdivacky///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3753198090Srdivacky///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3754201360Srdivackyint LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3755201360Srdivacky                         BasicBlock* BB, bool isAlloca) {
3756198090Srdivacky  PATypeHolder Ty(Type::getVoidTy(Context));
3757193323Sed  Value *Size = 0;
3758195340Sed  LocTy SizeLoc;
3759193323Sed  unsigned Alignment = 0;
3760193323Sed  if (ParseType(Ty)) return true;
3761193323Sed
3762201360Srdivacky  bool AteExtraComma = false;
3763193323Sed  if (EatIfPresent(lltok::comma)) {
3764201360Srdivacky    if (Lex.getKind() == lltok::kw_align) {
3765201360Srdivacky      if (ParseOptionalAlignment(Alignment)) return true;
3766201360Srdivacky    } else if (Lex.getKind() == lltok::MetadataVar) {
3767201360Srdivacky      AteExtraComma = true;
3768198090Srdivacky    } else {
3769201360Srdivacky      if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3770201360Srdivacky          ParseOptionalCommaAlign(Alignment, AteExtraComma))
3771201360Srdivacky        return true;
3772193323Sed    }
3773193323Sed  }
3774193323Sed
3775210299Sed  if (Size && !Size->getType()->isIntegerTy())
3776210299Sed    return Error(SizeLoc, "element count must have integer type");
3777193323Sed
3778198396Srdivacky  if (isAlloca) {
3779193323Sed    Inst = new AllocaInst(Ty, Size, Alignment);
3780201360Srdivacky    return AteExtraComma ? InstExtraComma : InstNormal;
3781198396Srdivacky  }
3782198396Srdivacky
3783198396Srdivacky  // Autoupgrade old malloc instruction to malloc call.
3784198396Srdivacky  // FIXME: Remove in LLVM 3.0.
3785210299Sed  if (Size && !Size->getType()->isIntegerTy(32))
3786210299Sed    return Error(SizeLoc, "element count must be i32");
3787198396Srdivacky  const Type *IntPtrTy = Type::getInt32Ty(Context);
3788198953Srdivacky  Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3789198953Srdivacky  AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
3790198396Srdivacky  if (!MallocF)
3791198396Srdivacky    // Prototype malloc as "void *(int32)".
3792198396Srdivacky    // This function is renamed as "malloc" in ValidateEndOfModule().
3793198396Srdivacky    MallocF = cast<Function>(
3794198396Srdivacky       M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3795198953Srdivacky  Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
3796201360Srdivackyreturn AteExtraComma ? InstExtraComma : InstNormal;
3797193323Sed}
3798193323Sed
3799193323Sed/// ParseFree
3800193323Sed///   ::= 'free' TypeAndValue
3801198892Srdivackybool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3802198892Srdivacky                         BasicBlock* BB) {
3803193323Sed  Value *Val; LocTy Loc;
3804193323Sed  if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3805204642Srdivacky  if (!Val->getType()->isPointerTy())
3806193323Sed    return Error(Loc, "operand to free must be a pointer");
3807198892Srdivacky  Inst = CallInst::CreateFree(Val, BB);
3808193323Sed  return false;
3809193323Sed}
3810193323Sed
3811193323Sed/// ParseLoad
3812198090Srdivacky///   ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3813201360Srdivackyint LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3814201360Srdivacky                        bool isVolatile) {
3815193323Sed  Value *Val; LocTy Loc;
3816198090Srdivacky  unsigned Alignment = 0;
3817201360Srdivacky  bool AteExtraComma = false;
3818201360Srdivacky  if (ParseTypeAndValue(Val, Loc, PFS) ||
3819201360Srdivacky      ParseOptionalCommaAlign(Alignment, AteExtraComma))
3820201360Srdivacky    return true;
3821193323Sed
3822204642Srdivacky  if (!Val->getType()->isPointerTy() ||
3823193323Sed      !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3824193323Sed    return Error(Loc, "load operand must be a pointer to a first class type");
3825198090Srdivacky
3826193323Sed  Inst = new LoadInst(Val, "", isVolatile, Alignment);
3827201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3828193323Sed}
3829193323Sed
3830193323Sed/// ParseStore
3831194612Sed///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3832201360Srdivackyint LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3833201360Srdivacky                         bool isVolatile) {
3834193323Sed  Value *Val, *Ptr; LocTy Loc, PtrLoc;
3835198090Srdivacky  unsigned Alignment = 0;
3836201360Srdivacky  bool AteExtraComma = false;
3837193323Sed  if (ParseTypeAndValue(Val, Loc, PFS) ||
3838193323Sed      ParseToken(lltok::comma, "expected ',' after store operand") ||
3839201360Srdivacky      ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3840201360Srdivacky      ParseOptionalCommaAlign(Alignment, AteExtraComma))
3841193323Sed    return true;
3842198090Srdivacky
3843204642Srdivacky  if (!Ptr->getType()->isPointerTy())
3844193323Sed    return Error(PtrLoc, "store operand must be a pointer");
3845193323Sed  if (!Val->getType()->isFirstClassType())
3846193323Sed    return Error(Loc, "store operand must be a first class value");
3847193323Sed  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3848193323Sed    return Error(Loc, "stored value and pointer type do not match");
3849198090Srdivacky
3850193323Sed  Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3851201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3852193323Sed}
3853193323Sed
3854193323Sed/// ParseGetResult
3855194612Sed///   ::= 'getresult' TypeAndValue ',' i32
3856193323Sed/// FIXME: Remove support for getresult in LLVM 3.0
3857193323Sedbool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3858193323Sed  Value *Val; LocTy ValLoc, EltLoc;
3859193323Sed  unsigned Element;
3860193323Sed  if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3861193323Sed      ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3862193323Sed      ParseUInt32(Element, EltLoc))
3863193323Sed    return true;
3864198090Srdivacky
3865204642Srdivacky  if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
3866193323Sed    return Error(ValLoc, "getresult inst requires an aggregate operand");
3867193323Sed  if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3868193323Sed    return Error(EltLoc, "invalid getresult index for value");
3869193323Sed  Inst = ExtractValueInst::Create(Val, Element);
3870193323Sed  return false;
3871193323Sed}
3872193323Sed
3873193323Sed/// ParseGetElementPtr
3874198090Srdivacky///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3875201360Srdivackyint LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3876193323Sed  Value *Ptr, *Val; LocTy Loc, EltLoc;
3877198090Srdivacky
3878198090Srdivacky  bool InBounds = EatIfPresent(lltok::kw_inbounds);
3879198090Srdivacky
3880193323Sed  if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3881198090Srdivacky
3882204642Srdivacky  if (!Ptr->getType()->isPointerTy())
3883193323Sed    return Error(Loc, "base of getelementptr must be a pointer");
3884198090Srdivacky
3885193323Sed  SmallVector<Value*, 16> Indices;
3886201360Srdivacky  bool AteExtraComma = false;
3887193323Sed  while (EatIfPresent(lltok::comma)) {
3888201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
3889201360Srdivacky      AteExtraComma = true;
3890198090Srdivacky      break;
3891201360Srdivacky    }
3892193323Sed    if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3893204642Srdivacky    if (!Val->getType()->isIntegerTy())
3894193323Sed      return Error(EltLoc, "getelementptr index must be an integer");
3895193323Sed    Indices.push_back(Val);
3896193323Sed  }
3897198090Srdivacky
3898193323Sed  if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3899193323Sed                                         Indices.begin(), Indices.end()))
3900193323Sed    return Error(Loc, "invalid getelementptr indices");
3901193323Sed  Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3902198090Srdivacky  if (InBounds)
3903198090Srdivacky    cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3904201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3905193323Sed}
3906193323Sed
3907193323Sed/// ParseExtractValue
3908193323Sed///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3909201360Srdivackyint LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3910193323Sed  Value *Val; LocTy Loc;
3911193323Sed  SmallVector<unsigned, 4> Indices;
3912201360Srdivacky  bool AteExtraComma;
3913193323Sed  if (ParseTypeAndValue(Val, Loc, PFS) ||
3914201360Srdivacky      ParseIndexList(Indices, AteExtraComma))
3915193323Sed    return true;
3916193323Sed
3917203954Srdivacky  if (!Val->getType()->isAggregateType())
3918203954Srdivacky    return Error(Loc, "extractvalue operand must be aggregate type");
3919193323Sed
3920193323Sed  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3921193323Sed                                        Indices.end()))
3922193323Sed    return Error(Loc, "invalid indices for extractvalue");
3923193323Sed  Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3924201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3925193323Sed}
3926193323Sed
3927193323Sed/// ParseInsertValue
3928193323Sed///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3929201360Srdivackyint LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3930193323Sed  Value *Val0, *Val1; LocTy Loc0, Loc1;
3931193323Sed  SmallVector<unsigned, 4> Indices;
3932201360Srdivacky  bool AteExtraComma;
3933193323Sed  if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3934193323Sed      ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3935193323Sed      ParseTypeAndValue(Val1, Loc1, PFS) ||
3936201360Srdivacky      ParseIndexList(Indices, AteExtraComma))
3937193323Sed    return true;
3938201360Srdivacky
3939203954Srdivacky  if (!Val0->getType()->isAggregateType())
3940203954Srdivacky    return Error(Loc0, "insertvalue operand must be aggregate type");
3941198090Srdivacky
3942193323Sed  if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3943193323Sed                                        Indices.end()))
3944193323Sed    return Error(Loc0, "invalid indices for insertvalue");
3945193323Sed  Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3946201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3947193323Sed}
3948193323Sed
3949193323Sed//===----------------------------------------------------------------------===//
3950193323Sed// Embedded metadata.
3951193323Sed//===----------------------------------------------------------------------===//
3952193323Sed
3953193323Sed/// ParseMDNodeVector
3954193323Sed///   ::= Element (',' Element)*
3955193323Sed/// Element
3956193323Sed///   ::= 'null' | TypeAndValue
3957202375Srdivackybool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3958202375Srdivacky                                 PerFunctionState *PFS) {
3959210299Sed  // Check for an empty list.
3960210299Sed  if (Lex.getKind() == lltok::rbrace)
3961210299Sed    return false;
3962210299Sed
3963193323Sed  do {
3964201360Srdivacky    // Null is a special case since it is typeless.
3965201360Srdivacky    if (EatIfPresent(lltok::kw_null)) {
3966201360Srdivacky      Elts.push_back(0);
3967201360Srdivacky      continue;
3968201360Srdivacky    }
3969201360Srdivacky
3970198090Srdivacky    Value *V = 0;
3971201360Srdivacky    PATypeHolder Ty(Type::getVoidTy(Context));
3972201360Srdivacky    ValID ID;
3973202375Srdivacky    if (ParseType(Ty) || ParseValID(ID, PFS) ||
3974202375Srdivacky        ConvertValIDToValue(Ty, ID, V, PFS))
3975201360Srdivacky      return true;
3976201360Srdivacky
3977193323Sed    Elts.push_back(V);
3978193323Sed  } while (EatIfPresent(lltok::comma));
3979193323Sed
3980193323Sed  return false;
3981193323Sed}
3982