LLParser.cpp revision 249423
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"
15249423Sdim#include "llvm/ADT/SmallPtrSet.h"
16193323Sed#include "llvm/AutoUpgrade.h"
17249423Sdim#include "llvm/IR/CallingConv.h"
18249423Sdim#include "llvm/IR/Constants.h"
19249423Sdim#include "llvm/IR/DerivedTypes.h"
20249423Sdim#include "llvm/IR/InlineAsm.h"
21249423Sdim#include "llvm/IR/Instructions.h"
22249423Sdim#include "llvm/IR/Module.h"
23249423Sdim#include "llvm/IR/Operator.h"
24249423Sdim#include "llvm/IR/ValueSymbolTable.h"
25198090Srdivacky#include "llvm/Support/ErrorHandling.h"
26193323Sed#include "llvm/Support/raw_ostream.h"
27193323Sedusing namespace llvm;
28193323Sed
29226633Sdimstatic std::string getTypeString(Type *T) {
30224145Sdim  std::string Result;
31224145Sdim  raw_string_ostream Tmp(Result);
32224145Sdim  Tmp << *T;
33224145Sdim  return Tmp.str();
34224145Sdim}
35224145Sdim
36193323Sed/// Run: module ::= toplevelentity*
37193323Sedbool LLParser::Run() {
38193323Sed  // Prime the lexer.
39193323Sed  Lex.Lex();
40193323Sed
41193323Sed  return ParseTopLevelEntities() ||
42193323Sed         ValidateEndOfModule();
43193323Sed}
44193323Sed
45193323Sed/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
46193323Sed/// module.
47193323Sedbool LLParser::ValidateEndOfModule() {
48206083Srdivacky  // Handle any instruction metadata forward references.
49206083Srdivacky  if (!ForwardRefInstMetadata.empty()) {
50206083Srdivacky    for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51206083Srdivacky         I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
52206083Srdivacky         I != E; ++I) {
53206083Srdivacky      Instruction *Inst = I->first;
54206083Srdivacky      const std::vector<MDRef> &MDList = I->second;
55249423Sdim
56206083Srdivacky      for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57206083Srdivacky        unsigned SlotNo = MDList[i].MDSlot;
58249423Sdim
59206083Srdivacky        if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60206083Srdivacky          return Error(MDList[i].Loc, "use of undefined metadata '!" +
61218893Sdim                       Twine(SlotNo) + "'");
62206083Srdivacky        Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63206083Srdivacky      }
64206083Srdivacky    }
65206083Srdivacky    ForwardRefInstMetadata.clear();
66206083Srdivacky  }
67249423Sdim
68249423Sdim  // Handle any function attribute group forward references.
69249423Sdim  for (std::map<Value*, std::vector<unsigned> >::iterator
70249423Sdim         I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
71249423Sdim         I != E; ++I) {
72249423Sdim    Value *V = I->first;
73249423Sdim    std::vector<unsigned> &Vec = I->second;
74249423Sdim    AttrBuilder B;
75249423Sdim
76249423Sdim    for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
77249423Sdim         VI != VE; ++VI)
78249423Sdim      B.merge(NumberedAttrBuilders[*VI]);
79249423Sdim
80249423Sdim    if (Function *Fn = dyn_cast<Function>(V)) {
81249423Sdim      AttributeSet AS = Fn->getAttributes();
82249423Sdim      AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83249423Sdim      AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84249423Sdim                               AS.getFnAttributes());
85249423Sdim
86249423Sdim      FnAttrs.merge(B);
87249423Sdim
88249423Sdim      // If the alignment was parsed as an attribute, move to the alignment
89249423Sdim      // field.
90249423Sdim      if (FnAttrs.hasAlignmentAttr()) {
91249423Sdim        Fn->setAlignment(FnAttrs.getAlignment());
92249423Sdim        FnAttrs.removeAttribute(Attribute::Alignment);
93249423Sdim      }
94249423Sdim
95249423Sdim      AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96249423Sdim                            AttributeSet::get(Context,
97249423Sdim                                              AttributeSet::FunctionIndex,
98249423Sdim                                              FnAttrs));
99249423Sdim      Fn->setAttributes(AS);
100249423Sdim    } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101249423Sdim      AttributeSet AS = CI->getAttributes();
102249423Sdim      AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103249423Sdim      AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104249423Sdim                               AS.getFnAttributes());
105249423Sdim      FnAttrs.merge(B);
106249423Sdim      AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107249423Sdim                            AttributeSet::get(Context,
108249423Sdim                                              AttributeSet::FunctionIndex,
109249423Sdim                                              FnAttrs));
110249423Sdim      CI->setAttributes(AS);
111249423Sdim    } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112249423Sdim      AttributeSet AS = II->getAttributes();
113249423Sdim      AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114249423Sdim      AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115249423Sdim                               AS.getFnAttributes());
116249423Sdim      FnAttrs.merge(B);
117249423Sdim      AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118249423Sdim                            AttributeSet::get(Context,
119249423Sdim                                              AttributeSet::FunctionIndex,
120249423Sdim                                              FnAttrs));
121249423Sdim      II->setAttributes(AS);
122249423Sdim    } else {
123249423Sdim      llvm_unreachable("invalid object with forward attribute group reference");
124249423Sdim    }
125249423Sdim  }
126249423Sdim
127198892Srdivacky  // If there are entries in ForwardRefBlockAddresses at this point, they are
128198892Srdivacky  // references after the function was defined.  Resolve those now.
129198892Srdivacky  while (!ForwardRefBlockAddresses.empty()) {
130198892Srdivacky    // Okay, we are referencing an already-parsed function, resolve them now.
131198892Srdivacky    Function *TheFn = 0;
132198892Srdivacky    const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
133198892Srdivacky    if (Fn.Kind == ValID::t_GlobalName)
134198892Srdivacky      TheFn = M->getFunction(Fn.StrVal);
135198892Srdivacky    else if (Fn.UIntVal < NumberedVals.size())
136198892Srdivacky      TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
137249423Sdim
138198892Srdivacky    if (TheFn == 0)
139198892Srdivacky      return Error(Fn.Loc, "unknown function referenced by blockaddress");
140249423Sdim
141198892Srdivacky    // Resolve all these references.
142249423Sdim    if (ResolveForwardRefBlockAddresses(TheFn,
143198892Srdivacky                                      ForwardRefBlockAddresses.begin()->second,
144198892Srdivacky                                        0))
145198892Srdivacky      return true;
146249423Sdim
147198892Srdivacky    ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
148198892Srdivacky  }
149249423Sdim
150224145Sdim  for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
151224145Sdim    if (NumberedTypes[i].second.isValid())
152224145Sdim      return Error(NumberedTypes[i].second,
153224145Sdim                   "use of undefined type '%" + Twine(i) + "'");
154198090Srdivacky
155224145Sdim  for (StringMap<std::pair<Type*, LocTy> >::iterator I =
156224145Sdim       NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
157224145Sdim    if (I->second.second.isValid())
158224145Sdim      return Error(I->second.second,
159224145Sdim                   "use of undefined type named '" + I->getKey() + "'");
160224145Sdim
161193323Sed  if (!ForwardRefVals.empty())
162193323Sed    return Error(ForwardRefVals.begin()->second.second,
163193323Sed                 "use of undefined value '@" + ForwardRefVals.begin()->first +
164193323Sed                 "'");
165198090Srdivacky
166193323Sed  if (!ForwardRefValIDs.empty())
167193323Sed    return Error(ForwardRefValIDs.begin()->second.second,
168193323Sed                 "use of undefined value '@" +
169218893Sdim                 Twine(ForwardRefValIDs.begin()->first) + "'");
170198090Srdivacky
171198090Srdivacky  if (!ForwardRefMDNodes.empty())
172198090Srdivacky    return Error(ForwardRefMDNodes.begin()->second.second,
173198090Srdivacky                 "use of undefined metadata '!" +
174218893Sdim                 Twine(ForwardRefMDNodes.begin()->first) + "'");
175198090Srdivacky
176198090Srdivacky
177193323Sed  // Look for intrinsic functions and CallInst that need to be upgraded
178193323Sed  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
179193323Sed    UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
180198090Srdivacky
181193323Sed  return false;
182193323Sed}
183193323Sed
184249423Sdimbool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
185198892Srdivacky                             std::vector<std::pair<ValID, GlobalValue*> > &Refs,
186198892Srdivacky                                               PerFunctionState *PFS) {
187198892Srdivacky  // Loop over all the references, resolving them.
188198892Srdivacky  for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
189198892Srdivacky    BasicBlock *Res;
190198892Srdivacky    if (PFS) {
191198892Srdivacky      if (Refs[i].first.Kind == ValID::t_LocalName)
192198892Srdivacky        Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
193198892Srdivacky      else
194198892Srdivacky        Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
195198892Srdivacky    } else if (Refs[i].first.Kind == ValID::t_LocalID) {
196198892Srdivacky      return Error(Refs[i].first.Loc,
197198892Srdivacky       "cannot take address of numeric label after the function is defined");
198198892Srdivacky    } else {
199198892Srdivacky      Res = dyn_cast_or_null<BasicBlock>(
200198892Srdivacky                     TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
201198892Srdivacky    }
202249423Sdim
203198892Srdivacky    if (Res == 0)
204198892Srdivacky      return Error(Refs[i].first.Loc,
205198892Srdivacky                   "referenced value is not a basic block");
206249423Sdim
207198892Srdivacky    // Get the BlockAddress for this and update references to use it.
208198892Srdivacky    BlockAddress *BA = BlockAddress::get(TheFn, Res);
209198892Srdivacky    Refs[i].second->replaceAllUsesWith(BA);
210198892Srdivacky    Refs[i].second->eraseFromParent();
211198892Srdivacky  }
212198892Srdivacky  return false;
213198892Srdivacky}
214198892Srdivacky
215198892Srdivacky
216193323Sed//===----------------------------------------------------------------------===//
217193323Sed// Top-Level Entities
218193323Sed//===----------------------------------------------------------------------===//
219193323Sed
220193323Sedbool LLParser::ParseTopLevelEntities() {
221193323Sed  while (1) {
222193323Sed    switch (Lex.getKind()) {
223193323Sed    default:         return TokError("expected top-level entity");
224193323Sed    case lltok::Eof: return false;
225193323Sed    case lltok::kw_declare: if (ParseDeclare()) return true; break;
226193323Sed    case lltok::kw_define:  if (ParseDefine()) return true; break;
227193323Sed    case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
228193323Sed    case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
229193323Sed    case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
230198090Srdivacky    case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
231193323Sed    case lltok::LocalVar:   if (ParseNamedType()) return true; break;
232198090Srdivacky    case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
233193323Sed    case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
234201360Srdivacky    case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
235249423Sdim    case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
236193323Sed
237193323Sed    // The Global variable production with no name can have many different
238193323Sed    // optional leading prefixes, the production is:
239193323Sed    // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
240218893Sdim    //               OptionalAddrSpace OptionalUnNammedAddr
241218893Sdim    //               ('constant'|'global') ...
242210299Sed    case lltok::kw_private:             // OptionalLinkage
243210299Sed    case lltok::kw_linker_private:      // OptionalLinkage
244210299Sed    case lltok::kw_linker_private_weak: // OptionalLinkage
245243830Sdim    case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
246210299Sed    case lltok::kw_internal:            // OptionalLinkage
247210299Sed    case lltok::kw_weak:                // OptionalLinkage
248210299Sed    case lltok::kw_weak_odr:            // OptionalLinkage
249210299Sed    case lltok::kw_linkonce:            // OptionalLinkage
250210299Sed    case lltok::kw_linkonce_odr:        // OptionalLinkage
251243830Sdim    case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
252210299Sed    case lltok::kw_appending:           // OptionalLinkage
253210299Sed    case lltok::kw_dllexport:           // OptionalLinkage
254210299Sed    case lltok::kw_common:              // OptionalLinkage
255210299Sed    case lltok::kw_dllimport:           // OptionalLinkage
256210299Sed    case lltok::kw_extern_weak:         // OptionalLinkage
257210299Sed    case lltok::kw_external: {          // OptionalLinkage
258193323Sed      unsigned Linkage, Visibility;
259193323Sed      if (ParseOptionalLinkage(Linkage) ||
260193323Sed          ParseOptionalVisibility(Visibility) ||
261195340Sed          ParseGlobal("", SMLoc(), Linkage, true, Visibility))
262193323Sed        return true;
263193323Sed      break;
264193323Sed    }
265193323Sed    case lltok::kw_default:       // OptionalVisibility
266193323Sed    case lltok::kw_hidden:        // OptionalVisibility
267193323Sed    case lltok::kw_protected: {   // OptionalVisibility
268193323Sed      unsigned Visibility;
269193323Sed      if (ParseOptionalVisibility(Visibility) ||
270195340Sed          ParseGlobal("", SMLoc(), 0, false, Visibility))
271193323Sed        return true;
272193323Sed      break;
273193323Sed    }
274198090Srdivacky
275193323Sed    case lltok::kw_thread_local:  // OptionalThreadLocal
276193323Sed    case lltok::kw_addrspace:     // OptionalAddrSpace
277193323Sed    case lltok::kw_constant:      // GlobalType
278193323Sed    case lltok::kw_global:        // GlobalType
279195340Sed      if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
280193323Sed      break;
281249423Sdim
282249423Sdim    case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
283193323Sed    }
284193323Sed  }
285193323Sed}
286193323Sed
287193323Sed
288193323Sed/// toplevelentity
289193323Sed///   ::= 'module' 'asm' STRINGCONSTANT
290193323Sedbool LLParser::ParseModuleAsm() {
291193323Sed  assert(Lex.getKind() == lltok::kw_module);
292193323Sed  Lex.Lex();
293198090Srdivacky
294198090Srdivacky  std::string AsmStr;
295193323Sed  if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
296193323Sed      ParseStringConstant(AsmStr)) return true;
297198090Srdivacky
298221345Sdim  M->appendModuleInlineAsm(AsmStr);
299193323Sed  return false;
300193323Sed}
301193323Sed
302193323Sed/// toplevelentity
303193323Sed///   ::= 'target' 'triple' '=' STRINGCONSTANT
304193323Sed///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
305193323Sedbool LLParser::ParseTargetDefinition() {
306193323Sed  assert(Lex.getKind() == lltok::kw_target);
307193323Sed  std::string Str;
308193323Sed  switch (Lex.Lex()) {
309193323Sed  default: return TokError("unknown target property");
310193323Sed  case lltok::kw_triple:
311193323Sed    Lex.Lex();
312193323Sed    if (ParseToken(lltok::equal, "expected '=' after target triple") ||
313193323Sed        ParseStringConstant(Str))
314193323Sed      return true;
315193323Sed    M->setTargetTriple(Str);
316193323Sed    return false;
317193323Sed  case lltok::kw_datalayout:
318193323Sed    Lex.Lex();
319193323Sed    if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
320193323Sed        ParseStringConstant(Str))
321193323Sed      return true;
322193323Sed    M->setDataLayout(Str);
323193323Sed    return false;
324193323Sed  }
325193323Sed}
326193323Sed
327193323Sed/// toplevelentity
328193323Sed///   ::= 'deplibs' '=' '[' ']'
329193323Sed///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
330249423Sdim/// FIXME: Remove in 4.0. Currently parse, but ignore.
331193323Sedbool LLParser::ParseDepLibs() {
332193323Sed  assert(Lex.getKind() == lltok::kw_deplibs);
333193323Sed  Lex.Lex();
334193323Sed  if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
335193323Sed      ParseToken(lltok::lsquare, "expected '=' after deplibs"))
336193323Sed    return true;
337193323Sed
338193323Sed  if (EatIfPresent(lltok::rsquare))
339193323Sed    return false;
340198090Srdivacky
341249423Sdim  do {
342249423Sdim    std::string Str;
343193323Sed    if (ParseStringConstant(Str)) return true;
344249423Sdim  } while (EatIfPresent(lltok::comma));
345193323Sed
346193323Sed  return ParseToken(lltok::rsquare, "expected ']' at end of list");
347193323Sed}
348193323Sed
349198090Srdivacky/// ParseUnnamedType:
350198090Srdivacky///   ::= LocalVarID '=' 'type' type
351193323Sedbool LLParser::ParseUnnamedType() {
352193323Sed  LocTy TypeLoc = Lex.getLoc();
353224145Sdim  unsigned TypeID = Lex.getUIntVal();
354224145Sdim  Lex.Lex(); // eat LocalVarID;
355193323Sed
356224145Sdim  if (ParseToken(lltok::equal, "expected '=' after name") ||
357224145Sdim      ParseToken(lltok::kw_type, "expected 'type' after '='"))
358224145Sdim    return true;
359198090Srdivacky
360224145Sdim  if (TypeID >= NumberedTypes.size())
361224145Sdim    NumberedTypes.resize(TypeID+1);
362249423Sdim
363224145Sdim  Type *Result = 0;
364224145Sdim  if (ParseStructDefinition(TypeLoc, "",
365224145Sdim                            NumberedTypes[TypeID], Result)) return true;
366249423Sdim
367224145Sdim  if (!isa<StructType>(Result)) {
368224145Sdim    std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
369224145Sdim    if (Entry.first)
370224145Sdim      return Error(TypeLoc, "non-struct types may not be recursive");
371224145Sdim    Entry.first = Result;
372224145Sdim    Entry.second = SMLoc();
373193323Sed  }
374198090Srdivacky
375193323Sed  return false;
376193323Sed}
377193323Sed
378224145Sdim
379193323Sed/// toplevelentity
380193323Sed///   ::= LocalVar '=' 'type' type
381193323Sedbool LLParser::ParseNamedType() {
382193323Sed  std::string Name = Lex.getStrVal();
383193323Sed  LocTy NameLoc = Lex.getLoc();
384193323Sed  Lex.Lex();  // eat LocalVar.
385198090Srdivacky
386193323Sed  if (ParseToken(lltok::equal, "expected '=' after name") ||
387224145Sdim      ParseToken(lltok::kw_type, "expected 'type' after name"))
388193323Sed    return true;
389249423Sdim
390224145Sdim  Type *Result = 0;
391224145Sdim  if (ParseStructDefinition(NameLoc, Name,
392224145Sdim                            NamedTypes[Name], Result)) return true;
393249423Sdim
394224145Sdim  if (!isa<StructType>(Result)) {
395224145Sdim    std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
396224145Sdim    if (Entry.first)
397224145Sdim      return Error(NameLoc, "non-struct types may not be recursive");
398224145Sdim    Entry.first = Result;
399224145Sdim    Entry.second = SMLoc();
400193323Sed  }
401249423Sdim
402224145Sdim  return false;
403193323Sed}
404193323Sed
405193323Sed
406193323Sed/// toplevelentity
407193323Sed///   ::= 'declare' FunctionHeader
408193323Sedbool LLParser::ParseDeclare() {
409193323Sed  assert(Lex.getKind() == lltok::kw_declare);
410193323Sed  Lex.Lex();
411198090Srdivacky
412193323Sed  Function *F;
413193323Sed  return ParseFunctionHeader(F, false);
414193323Sed}
415193323Sed
416193323Sed/// toplevelentity
417193323Sed///   ::= 'define' FunctionHeader '{' ...
418193323Sedbool LLParser::ParseDefine() {
419193323Sed  assert(Lex.getKind() == lltok::kw_define);
420193323Sed  Lex.Lex();
421198090Srdivacky
422193323Sed  Function *F;
423193323Sed  return ParseFunctionHeader(F, true) ||
424193323Sed         ParseFunctionBody(*F);
425193323Sed}
426193323Sed
427193323Sed/// ParseGlobalType
428193323Sed///   ::= 'constant'
429193323Sed///   ::= 'global'
430193323Sedbool LLParser::ParseGlobalType(bool &IsConstant) {
431193323Sed  if (Lex.getKind() == lltok::kw_constant)
432193323Sed    IsConstant = true;
433193323Sed  else if (Lex.getKind() == lltok::kw_global)
434193323Sed    IsConstant = false;
435193323Sed  else {
436193323Sed    IsConstant = false;
437193323Sed    return TokError("expected 'global' or 'constant'");
438193323Sed  }
439193323Sed  Lex.Lex();
440193323Sed  return false;
441193323Sed}
442193323Sed
443198090Srdivacky/// ParseUnnamedGlobal:
444198090Srdivacky///   OptionalVisibility ALIAS ...
445198090Srdivacky///   OptionalLinkage OptionalVisibility ...   -> global variable
446198090Srdivacky///   GlobalID '=' OptionalVisibility ALIAS ...
447198090Srdivacky///   GlobalID '=' OptionalLinkage OptionalVisibility ...   -> global variable
448198090Srdivackybool LLParser::ParseUnnamedGlobal() {
449198090Srdivacky  unsigned VarID = NumberedVals.size();
450198090Srdivacky  std::string Name;
451198090Srdivacky  LocTy NameLoc = Lex.getLoc();
452198090Srdivacky
453198090Srdivacky  // Handle the GlobalID form.
454198090Srdivacky  if (Lex.getKind() == lltok::GlobalID) {
455198090Srdivacky    if (Lex.getUIntVal() != VarID)
456198090Srdivacky      return Error(Lex.getLoc(), "variable expected to be numbered '%" +
457218893Sdim                   Twine(VarID) + "'");
458198090Srdivacky    Lex.Lex(); // eat GlobalID;
459198090Srdivacky
460198090Srdivacky    if (ParseToken(lltok::equal, "expected '=' after name"))
461198090Srdivacky      return true;
462198090Srdivacky  }
463198090Srdivacky
464198090Srdivacky  bool HasLinkage;
465198090Srdivacky  unsigned Linkage, Visibility;
466198090Srdivacky  if (ParseOptionalLinkage(Linkage, HasLinkage) ||
467198090Srdivacky      ParseOptionalVisibility(Visibility))
468198090Srdivacky    return true;
469198090Srdivacky
470198090Srdivacky  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
471198090Srdivacky    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
472198090Srdivacky  return ParseAlias(Name, NameLoc, Visibility);
473198090Srdivacky}
474198090Srdivacky
475193323Sed/// ParseNamedGlobal:
476193323Sed///   GlobalVar '=' OptionalVisibility ALIAS ...
477193323Sed///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
478193323Sedbool LLParser::ParseNamedGlobal() {
479193323Sed  assert(Lex.getKind() == lltok::GlobalVar);
480193323Sed  LocTy NameLoc = Lex.getLoc();
481193323Sed  std::string Name = Lex.getStrVal();
482193323Sed  Lex.Lex();
483198090Srdivacky
484193323Sed  bool HasLinkage;
485193323Sed  unsigned Linkage, Visibility;
486193323Sed  if (ParseToken(lltok::equal, "expected '=' in global variable") ||
487193323Sed      ParseOptionalLinkage(Linkage, HasLinkage) ||
488193323Sed      ParseOptionalVisibility(Visibility))
489193323Sed    return true;
490198090Srdivacky
491193323Sed  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
492193323Sed    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
493193323Sed  return ParseAlias(Name, NameLoc, Visibility);
494193323Sed}
495193323Sed
496198090Srdivacky// MDString:
497198090Srdivacky//   ::= '!' STRINGCONSTANT
498201360Srdivackybool LLParser::ParseMDString(MDString *&Result) {
499198090Srdivacky  std::string Str;
500198090Srdivacky  if (ParseStringConstant(Str)) return true;
501201360Srdivacky  Result = MDString::get(Context, Str);
502198090Srdivacky  return false;
503198090Srdivacky}
504198090Srdivacky
505198090Srdivacky// MDNode:
506198090Srdivacky//   ::= '!' MDNodeNumber
507206083Srdivacky//
508206083Srdivacky/// This version of ParseMDNodeID returns the slot number and null in the case
509206083Srdivacky/// of a forward reference.
510206083Srdivackybool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
511206083Srdivacky  // !{ ..., !42, ... }
512206083Srdivacky  if (ParseUInt32(SlotNo)) return true;
513206083Srdivacky
514206083Srdivacky  // Check existing MDNode.
515206083Srdivacky  if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
516206083Srdivacky    Result = NumberedMetadata[SlotNo];
517206083Srdivacky  else
518206083Srdivacky    Result = 0;
519206083Srdivacky  return false;
520206083Srdivacky}
521206083Srdivacky
522201360Srdivackybool LLParser::ParseMDNodeID(MDNode *&Result) {
523198090Srdivacky  // !{ ..., !42, ... }
524198090Srdivacky  unsigned MID = 0;
525206083Srdivacky  if (ParseMDNodeID(Result, MID)) return true;
526198090Srdivacky
527206083Srdivacky  // If not a forward reference, just return it now.
528206083Srdivacky  if (Result) return false;
529198090Srdivacky
530206083Srdivacky  // Otherwise, create MDNode forward reference.
531221345Sdim  MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
532198090Srdivacky  ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
533249423Sdim
534201360Srdivacky  if (NumberedMetadata.size() <= MID)
535201360Srdivacky    NumberedMetadata.resize(MID+1);
536201360Srdivacky  NumberedMetadata[MID] = FwdNode;
537201360Srdivacky  Result = FwdNode;
538198090Srdivacky  return false;
539198090Srdivacky}
540198090Srdivacky
541201360Srdivacky/// ParseNamedMetadata:
542198090Srdivacky///   !foo = !{ !1, !2 }
543198090Srdivackybool LLParser::ParseNamedMetadata() {
544201360Srdivacky  assert(Lex.getKind() == lltok::MetadataVar);
545201360Srdivacky  std::string Name = Lex.getStrVal();
546198090Srdivacky  Lex.Lex();
547198090Srdivacky
548201360Srdivacky  if (ParseToken(lltok::equal, "expected '=' here") ||
549201360Srdivacky      ParseToken(lltok::exclaim, "Expected '!' here") ||
550201360Srdivacky      ParseToken(lltok::lbrace, "Expected '{' here"))
551198090Srdivacky    return true;
552198090Srdivacky
553212904Sdim  NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
554210299Sed  if (Lex.getKind() != lltok::rbrace)
555210299Sed    do {
556210299Sed      if (ParseToken(lltok::exclaim, "Expected '!' here"))
557210299Sed        return true;
558249423Sdim
559210299Sed      MDNode *N = 0;
560210299Sed      if (ParseMDNodeID(N)) return true;
561212904Sdim      NMD->addOperand(N);
562210299Sed    } while (EatIfPresent(lltok::comma));
563198090Srdivacky
564198090Srdivacky  if (ParseToken(lltok::rbrace, "expected end of metadata node"))
565198090Srdivacky    return true;
566198090Srdivacky
567198090Srdivacky  return false;
568198090Srdivacky}
569198090Srdivacky
570195340Sed/// ParseStandaloneMetadata:
571198090Srdivacky///   !42 = !{...}
572195340Sedbool LLParser::ParseStandaloneMetadata() {
573201360Srdivacky  assert(Lex.getKind() == lltok::exclaim);
574195340Sed  Lex.Lex();
575195340Sed  unsigned MetadataID = 0;
576195340Sed
577195340Sed  LocTy TyLoc;
578224145Sdim  Type *Ty = 0;
579198090Srdivacky  SmallVector<Value *, 16> Elts;
580201360Srdivacky  if (ParseUInt32(MetadataID) ||
581201360Srdivacky      ParseToken(lltok::equal, "expected '=' here") ||
582201360Srdivacky      ParseType(Ty, TyLoc) ||
583201360Srdivacky      ParseToken(lltok::exclaim, "Expected '!' here") ||
584201360Srdivacky      ParseToken(lltok::lbrace, "Expected '{' here") ||
585202375Srdivacky      ParseMDNodeVector(Elts, NULL) ||
586201360Srdivacky      ParseToken(lltok::rbrace, "expected end of metadata node"))
587198090Srdivacky    return true;
588198090Srdivacky
589221345Sdim  MDNode *Init = MDNode::get(Context, Elts);
590249423Sdim
591201360Srdivacky  // See if this was forward referenced, if so, handle it.
592201360Srdivacky  std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
593198090Srdivacky    FI = ForwardRefMDNodes.find(MetadataID);
594198090Srdivacky  if (FI != ForwardRefMDNodes.end()) {
595212904Sdim    MDNode *Temp = FI->second.first;
596212904Sdim    Temp->replaceAllUsesWith(Init);
597212904Sdim    MDNode::deleteTemporary(Temp);
598198090Srdivacky    ForwardRefMDNodes.erase(FI);
599249423Sdim
600201360Srdivacky    assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
601201360Srdivacky  } else {
602201360Srdivacky    if (MetadataID >= NumberedMetadata.size())
603201360Srdivacky      NumberedMetadata.resize(MetadataID+1);
604198090Srdivacky
605201360Srdivacky    if (NumberedMetadata[MetadataID] != 0)
606201360Srdivacky      return TokError("Metadata id is already used");
607201360Srdivacky    NumberedMetadata[MetadataID] = Init;
608200581Srdivacky  }
609200581Srdivacky
610200581Srdivacky  return false;
611200581Srdivacky}
612200581Srdivacky
613193323Sed/// ParseAlias:
614193323Sed///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
615193323Sed/// Aliasee
616193323Sed///   ::= TypeAndValue
617193323Sed///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
618198090Srdivacky///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
619193323Sed///
620193323Sed/// Everything through visibility has already been parsed.
621193323Sed///
622193323Sedbool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
623193323Sed                          unsigned Visibility) {
624193323Sed  assert(Lex.getKind() == lltok::kw_alias);
625193323Sed  Lex.Lex();
626193323Sed  unsigned Linkage;
627193323Sed  LocTy LinkageLoc = Lex.getLoc();
628193323Sed  if (ParseOptionalLinkage(Linkage))
629193323Sed    return true;
630193323Sed
631193323Sed  if (Linkage != GlobalValue::ExternalLinkage &&
632193323Sed      Linkage != GlobalValue::WeakAnyLinkage &&
633193323Sed      Linkage != GlobalValue::WeakODRLinkage &&
634193323Sed      Linkage != GlobalValue::InternalLinkage &&
635198090Srdivacky      Linkage != GlobalValue::PrivateLinkage &&
636210299Sed      Linkage != GlobalValue::LinkerPrivateLinkage &&
637243830Sdim      Linkage != GlobalValue::LinkerPrivateWeakLinkage)
638193323Sed    return Error(LinkageLoc, "invalid linkage type for alias");
639198090Srdivacky
640193323Sed  Constant *Aliasee;
641193323Sed  LocTy AliaseeLoc = Lex.getLoc();
642193323Sed  if (Lex.getKind() != lltok::kw_bitcast &&
643193323Sed      Lex.getKind() != lltok::kw_getelementptr) {
644193323Sed    if (ParseGlobalTypeAndValue(Aliasee)) return true;
645193323Sed  } else {
646193323Sed    // The bitcast dest type is not present, it is implied by the dest type.
647193323Sed    ValID ID;
648193323Sed    if (ParseValID(ID)) return true;
649193323Sed    if (ID.Kind != ValID::t_Constant)
650193323Sed      return Error(AliaseeLoc, "invalid aliasee");
651193323Sed    Aliasee = ID.ConstantVal;
652193323Sed  }
653198090Srdivacky
654204642Srdivacky  if (!Aliasee->getType()->isPointerTy())
655193323Sed    return Error(AliaseeLoc, "alias must have pointer type");
656193323Sed
657193323Sed  // Okay, create the alias but do not insert it into the module yet.
658193323Sed  GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
659193323Sed                                    (GlobalValue::LinkageTypes)Linkage, Name,
660193323Sed                                    Aliasee);
661193323Sed  GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
662198090Srdivacky
663193323Sed  // See if this value already exists in the symbol table.  If so, it is either
664193323Sed  // a redefinition or a definition of a forward reference.
665198892Srdivacky  if (GlobalValue *Val = M->getNamedValue(Name)) {
666193323Sed    // See if this was a redefinition.  If so, there is no entry in
667193323Sed    // ForwardRefVals.
668193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
669193323Sed      I = ForwardRefVals.find(Name);
670193323Sed    if (I == ForwardRefVals.end())
671193323Sed      return Error(NameLoc, "redefinition of global named '@" + Name + "'");
672193323Sed
673193323Sed    // Otherwise, this was a definition of forward ref.  Verify that types
674193323Sed    // agree.
675193323Sed    if (Val->getType() != GA->getType())
676193323Sed      return Error(NameLoc,
677193323Sed              "forward reference and definition of alias have different types");
678198090Srdivacky
679193323Sed    // If they agree, just RAUW the old value with the alias and remove the
680193323Sed    // forward ref info.
681193323Sed    Val->replaceAllUsesWith(GA);
682193323Sed    Val->eraseFromParent();
683193323Sed    ForwardRefVals.erase(I);
684193323Sed  }
685198090Srdivacky
686193323Sed  // Insert into the module, we know its name won't collide now.
687193323Sed  M->getAliasList().push_back(GA);
688218893Sdim  assert(GA->getName() == Name && "Should not be a name conflict!");
689198090Srdivacky
690193323Sed  return false;
691193323Sed}
692193323Sed
693193323Sed/// ParseGlobal
694193323Sed///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
695249423Sdim///       OptionalAddrSpace OptionalUnNammedAddr
696249423Sdim///       OptionalExternallyInitialized GlobalType Type Const
697193323Sed///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
698249423Sdim///       OptionalAddrSpace OptionalUnNammedAddr
699249423Sdim///       OptionalExternallyInitialized GlobalType Type Const
700193323Sed///
701193323Sed/// Everything through visibility has been parsed already.
702193323Sed///
703193323Sedbool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
704193323Sed                           unsigned Linkage, bool HasLinkage,
705193323Sed                           unsigned Visibility) {
706193323Sed  unsigned AddrSpace;
707249423Sdim  bool IsConstant, UnnamedAddr, IsExternallyInitialized;
708239462Sdim  GlobalVariable::ThreadLocalMode TLM;
709218893Sdim  LocTy UnnamedAddrLoc;
710249423Sdim  LocTy IsExternallyInitializedLoc;
711193323Sed  LocTy TyLoc;
712198090Srdivacky
713224145Sdim  Type *Ty = 0;
714239462Sdim  if (ParseOptionalThreadLocal(TLM) ||
715193323Sed      ParseOptionalAddrSpace(AddrSpace) ||
716218893Sdim      ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
717218893Sdim                         &UnnamedAddrLoc) ||
718249423Sdim      ParseOptionalToken(lltok::kw_externally_initialized,
719249423Sdim                         IsExternallyInitialized,
720249423Sdim                         &IsExternallyInitializedLoc) ||
721193323Sed      ParseGlobalType(IsConstant) ||
722193323Sed      ParseType(Ty, TyLoc))
723193323Sed    return true;
724198090Srdivacky
725193323Sed  // If the linkage is specified and is external, then no initializer is
726193323Sed  // present.
727193323Sed  Constant *Init = 0;
728193323Sed  if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
729193323Sed                      Linkage != GlobalValue::ExternalWeakLinkage &&
730193323Sed                      Linkage != GlobalValue::ExternalLinkage)) {
731193323Sed    if (ParseGlobalValue(Ty, Init))
732193323Sed      return true;
733193323Sed  }
734193323Sed
735204642Srdivacky  if (Ty->isFunctionTy() || Ty->isLabelTy())
736193323Sed    return Error(TyLoc, "invalid type for global variable");
737198090Srdivacky
738193323Sed  GlobalVariable *GV = 0;
739193323Sed
740193323Sed  // See if the global was forward referenced, if so, use the global.
741193323Sed  if (!Name.empty()) {
742198892Srdivacky    if (GlobalValue *GVal = M->getNamedValue(Name)) {
743198892Srdivacky      if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
744198892Srdivacky        return Error(NameLoc, "redefinition of global '@" + Name + "'");
745198892Srdivacky      GV = cast<GlobalVariable>(GVal);
746198892Srdivacky    }
747193323Sed  } else {
748193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
749193323Sed      I = ForwardRefValIDs.find(NumberedVals.size());
750193323Sed    if (I != ForwardRefValIDs.end()) {
751193323Sed      GV = cast<GlobalVariable>(I->second.first);
752193323Sed      ForwardRefValIDs.erase(I);
753193323Sed    }
754193323Sed  }
755193323Sed
756193323Sed  if (GV == 0) {
757198090Srdivacky    GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
758239462Sdim                            Name, 0, GlobalVariable::NotThreadLocal,
759239462Sdim                            AddrSpace);
760193323Sed  } else {
761193323Sed    if (GV->getType()->getElementType() != Ty)
762193323Sed      return Error(TyLoc,
763193323Sed            "forward reference and definition of global have different types");
764198090Srdivacky
765193323Sed    // Move the forward-reference to the correct spot in the module.
766193323Sed    M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
767193323Sed  }
768193323Sed
769193323Sed  if (Name.empty())
770193323Sed    NumberedVals.push_back(GV);
771198090Srdivacky
772193323Sed  // Set the parsed properties on the global.
773193323Sed  if (Init)
774193323Sed    GV->setInitializer(Init);
775193323Sed  GV->setConstant(IsConstant);
776193323Sed  GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
777193323Sed  GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
778249423Sdim  GV->setExternallyInitialized(IsExternallyInitialized);
779239462Sdim  GV->setThreadLocalMode(TLM);
780218893Sdim  GV->setUnnamedAddr(UnnamedAddr);
781198090Srdivacky
782193323Sed  // Parse attributes on the global.
783193323Sed  while (Lex.getKind() == lltok::comma) {
784193323Sed    Lex.Lex();
785198090Srdivacky
786193323Sed    if (Lex.getKind() == lltok::kw_section) {
787193323Sed      Lex.Lex();
788193323Sed      GV->setSection(Lex.getStrVal());
789193323Sed      if (ParseToken(lltok::StringConstant, "expected global section string"))
790193323Sed        return true;
791193323Sed    } else if (Lex.getKind() == lltok::kw_align) {
792193323Sed      unsigned Alignment;
793193323Sed      if (ParseOptionalAlignment(Alignment)) return true;
794193323Sed      GV->setAlignment(Alignment);
795193323Sed    } else {
796193323Sed      TokError("unknown global variable property!");
797193323Sed    }
798193323Sed  }
799198090Srdivacky
800193323Sed  return false;
801193323Sed}
802193323Sed
803249423Sdim/// ParseUnnamedAttrGrp
804249423Sdim///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
805249423Sdimbool LLParser::ParseUnnamedAttrGrp() {
806249423Sdim  assert(Lex.getKind() == lltok::kw_attributes);
807249423Sdim  LocTy AttrGrpLoc = Lex.getLoc();
808249423Sdim  Lex.Lex();
809193323Sed
810249423Sdim  assert(Lex.getKind() == lltok::AttrGrpID);
811249423Sdim  unsigned VarID = Lex.getUIntVal();
812249423Sdim  std::vector<unsigned> unused;
813249423Sdim  LocTy NoBuiltinLoc;
814249423Sdim  Lex.Lex();
815249423Sdim
816249423Sdim  if (ParseToken(lltok::equal, "expected '=' here") ||
817249423Sdim      ParseToken(lltok::lbrace, "expected '{' here") ||
818249423Sdim      ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
819249423Sdim                                 NoBuiltinLoc) ||
820249423Sdim      ParseToken(lltok::rbrace, "expected end of attribute group"))
821249423Sdim    return true;
822249423Sdim
823249423Sdim  if (!NumberedAttrBuilders[VarID].hasAttributes())
824249423Sdim    return Error(AttrGrpLoc, "attribute group has no attributes");
825249423Sdim
826249423Sdim  return false;
827249423Sdim}
828249423Sdim
829249423Sdim/// ParseFnAttributeValuePairs
830249423Sdim///   ::= <attr> | <attr> '=' <value>
831249423Sdimbool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
832249423Sdim                                          std::vector<unsigned> &FwdRefAttrGrps,
833249423Sdim                                          bool inAttrGrp, LocTy &NoBuiltinLoc) {
834249423Sdim  bool HaveError = false;
835249423Sdim
836249423Sdim  B.clear();
837249423Sdim
838249423Sdim  while (true) {
839249423Sdim    lltok::Kind Token = Lex.getKind();
840249423Sdim    if (Token == lltok::kw_nobuiltin)
841249423Sdim      NoBuiltinLoc = Lex.getLoc();
842249423Sdim    switch (Token) {
843249423Sdim    default:
844249423Sdim      if (!inAttrGrp) return HaveError;
845249423Sdim      return Error(Lex.getLoc(), "unterminated attribute group");
846249423Sdim    case lltok::rbrace:
847249423Sdim      // Finished.
848249423Sdim      return false;
849249423Sdim
850249423Sdim    case lltok::AttrGrpID: {
851249423Sdim      // Allow a function to reference an attribute group:
852249423Sdim      //
853249423Sdim      //   define void @foo() #1 { ... }
854249423Sdim      if (inAttrGrp)
855249423Sdim        HaveError |=
856249423Sdim          Error(Lex.getLoc(),
857249423Sdim              "cannot have an attribute group reference in an attribute group");
858249423Sdim
859249423Sdim      unsigned AttrGrpNum = Lex.getUIntVal();
860249423Sdim      if (inAttrGrp) break;
861249423Sdim
862249423Sdim      // Save the reference to the attribute group. We'll fill it in later.
863249423Sdim      FwdRefAttrGrps.push_back(AttrGrpNum);
864249423Sdim      break;
865249423Sdim    }
866249423Sdim    // Target-dependent attributes:
867249423Sdim    case lltok::StringConstant: {
868249423Sdim      std::string Attr = Lex.getStrVal();
869249423Sdim      Lex.Lex();
870249423Sdim      std::string Val;
871249423Sdim      if (EatIfPresent(lltok::equal) &&
872249423Sdim          ParseStringConstant(Val))
873249423Sdim        return true;
874249423Sdim
875249423Sdim      B.addAttribute(Attr, Val);
876249423Sdim      continue;
877249423Sdim    }
878249423Sdim
879249423Sdim    // Target-independent attributes:
880249423Sdim    case lltok::kw_align: {
881249423Sdim      // As a hack, we allow "align 2" on functions as a synonym for "alignstack
882249423Sdim      // 2".
883249423Sdim      unsigned Alignment;
884249423Sdim      if (inAttrGrp) {
885249423Sdim        Lex.Lex();
886249423Sdim        if (ParseToken(lltok::equal, "expected '=' here") ||
887249423Sdim            ParseUInt32(Alignment))
888249423Sdim          return true;
889249423Sdim      } else {
890249423Sdim        if (ParseOptionalAlignment(Alignment))
891249423Sdim          return true;
892249423Sdim      }
893249423Sdim      B.addAlignmentAttr(Alignment);
894249423Sdim      continue;
895249423Sdim    }
896249423Sdim    case lltok::kw_alignstack: {
897249423Sdim      unsigned Alignment;
898249423Sdim      if (inAttrGrp) {
899249423Sdim        Lex.Lex();
900249423Sdim        if (ParseToken(lltok::equal, "expected '=' here") ||
901249423Sdim            ParseUInt32(Alignment))
902249423Sdim          return true;
903249423Sdim      } else {
904249423Sdim        if (ParseOptionalStackAlignment(Alignment))
905249423Sdim          return true;
906249423Sdim      }
907249423Sdim      B.addStackAlignmentAttr(Alignment);
908249423Sdim      continue;
909249423Sdim    }
910249423Sdim    case lltok::kw_alwaysinline:      B.addAttribute(Attribute::AlwaysInline); break;
911249423Sdim    case lltok::kw_inlinehint:        B.addAttribute(Attribute::InlineHint); break;
912249423Sdim    case lltok::kw_minsize:           B.addAttribute(Attribute::MinSize); break;
913249423Sdim    case lltok::kw_naked:             B.addAttribute(Attribute::Naked); break;
914249423Sdim    case lltok::kw_nobuiltin:         B.addAttribute(Attribute::NoBuiltin); break;
915249423Sdim    case lltok::kw_noduplicate:       B.addAttribute(Attribute::NoDuplicate); break;
916249423Sdim    case lltok::kw_noimplicitfloat:   B.addAttribute(Attribute::NoImplicitFloat); break;
917249423Sdim    case lltok::kw_noinline:          B.addAttribute(Attribute::NoInline); break;
918249423Sdim    case lltok::kw_nonlazybind:       B.addAttribute(Attribute::NonLazyBind); break;
919249423Sdim    case lltok::kw_noredzone:         B.addAttribute(Attribute::NoRedZone); break;
920249423Sdim    case lltok::kw_noreturn:          B.addAttribute(Attribute::NoReturn); break;
921249423Sdim    case lltok::kw_nounwind:          B.addAttribute(Attribute::NoUnwind); break;
922249423Sdim    case lltok::kw_optsize:           B.addAttribute(Attribute::OptimizeForSize); break;
923249423Sdim    case lltok::kw_readnone:          B.addAttribute(Attribute::ReadNone); break;
924249423Sdim    case lltok::kw_readonly:          B.addAttribute(Attribute::ReadOnly); break;
925249423Sdim    case lltok::kw_returns_twice:     B.addAttribute(Attribute::ReturnsTwice); break;
926249423Sdim    case lltok::kw_ssp:               B.addAttribute(Attribute::StackProtect); break;
927249423Sdim    case lltok::kw_sspreq:            B.addAttribute(Attribute::StackProtectReq); break;
928249423Sdim    case lltok::kw_sspstrong:         B.addAttribute(Attribute::StackProtectStrong); break;
929249423Sdim    case lltok::kw_sanitize_address:  B.addAttribute(Attribute::SanitizeAddress); break;
930249423Sdim    case lltok::kw_sanitize_thread:   B.addAttribute(Attribute::SanitizeThread); break;
931249423Sdim    case lltok::kw_sanitize_memory:   B.addAttribute(Attribute::SanitizeMemory); break;
932249423Sdim    case lltok::kw_uwtable:           B.addAttribute(Attribute::UWTable); break;
933249423Sdim
934249423Sdim    // Error handling.
935249423Sdim    case lltok::kw_inreg:
936249423Sdim    case lltok::kw_signext:
937249423Sdim    case lltok::kw_zeroext:
938249423Sdim      HaveError |=
939249423Sdim        Error(Lex.getLoc(),
940249423Sdim              "invalid use of attribute on a function");
941249423Sdim      break;
942249423Sdim    case lltok::kw_byval:
943249423Sdim    case lltok::kw_nest:
944249423Sdim    case lltok::kw_noalias:
945249423Sdim    case lltok::kw_nocapture:
946249423Sdim    case lltok::kw_sret:
947249423Sdim      HaveError |=
948249423Sdim        Error(Lex.getLoc(),
949249423Sdim              "invalid use of parameter-only attribute on a function");
950249423Sdim      break;
951249423Sdim    }
952249423Sdim
953249423Sdim    Lex.Lex();
954249423Sdim  }
955249423Sdim}
956249423Sdim
957193323Sed//===----------------------------------------------------------------------===//
958193323Sed// GlobalValue Reference/Resolution Routines.
959193323Sed//===----------------------------------------------------------------------===//
960193323Sed
961193323Sed/// GetGlobalVal - Get a value with the specified name or ID, creating a
962193323Sed/// forward reference record if needed.  This can return null if the value
963193323Sed/// exists but does not have the right type.
964226633SdimGlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
965193323Sed                                    LocTy Loc) {
966226633Sdim  PointerType *PTy = dyn_cast<PointerType>(Ty);
967193323Sed  if (PTy == 0) {
968193323Sed    Error(Loc, "global variable reference must have pointer type");
969193323Sed    return 0;
970193323Sed  }
971198090Srdivacky
972193323Sed  // Look this name up in the normal function symbol table.
973193323Sed  GlobalValue *Val =
974193323Sed    cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
975198090Srdivacky
976193323Sed  // If this is a forward reference for the value, see if we already created a
977193323Sed  // forward ref record.
978193323Sed  if (Val == 0) {
979193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
980193323Sed      I = ForwardRefVals.find(Name);
981193323Sed    if (I != ForwardRefVals.end())
982193323Sed      Val = I->second.first;
983193323Sed  }
984198090Srdivacky
985193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
986193323Sed  if (Val) {
987193323Sed    if (Val->getType() == Ty) return Val;
988193323Sed    Error(Loc, "'@" + Name + "' defined with type '" +
989224145Sdim          getTypeString(Val->getType()) + "'");
990193323Sed    return 0;
991193323Sed  }
992198090Srdivacky
993193323Sed  // Otherwise, create a new forward reference for this value and remember it.
994193323Sed  GlobalValue *FwdVal;
995226633Sdim  if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
996193323Sed    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
997224145Sdim  else
998198090Srdivacky    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
999243830Sdim                                GlobalValue::ExternalWeakLinkage, 0, Name,
1000243830Sdim                                0, GlobalVariable::NotThreadLocal,
1001243830Sdim                                PTy->getAddressSpace());
1002198090Srdivacky
1003193323Sed  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1004193323Sed  return FwdVal;
1005193323Sed}
1006193323Sed
1007226633SdimGlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1008226633Sdim  PointerType *PTy = dyn_cast<PointerType>(Ty);
1009193323Sed  if (PTy == 0) {
1010193323Sed    Error(Loc, "global variable reference must have pointer type");
1011193323Sed    return 0;
1012193323Sed  }
1013198090Srdivacky
1014193323Sed  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1015198090Srdivacky
1016193323Sed  // If this is a forward reference for the value, see if we already created a
1017193323Sed  // forward ref record.
1018193323Sed  if (Val == 0) {
1019193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1020193323Sed      I = ForwardRefValIDs.find(ID);
1021193323Sed    if (I != ForwardRefValIDs.end())
1022193323Sed      Val = I->second.first;
1023193323Sed  }
1024198090Srdivacky
1025193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
1026193323Sed  if (Val) {
1027193323Sed    if (Val->getType() == Ty) return Val;
1028218893Sdim    Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1029224145Sdim          getTypeString(Val->getType()) + "'");
1030193323Sed    return 0;
1031193323Sed  }
1032198090Srdivacky
1033193323Sed  // Otherwise, create a new forward reference for this value and remember it.
1034193323Sed  GlobalValue *FwdVal;
1035226633Sdim  if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1036193323Sed    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1037224145Sdim  else
1038198090Srdivacky    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1039198090Srdivacky                                GlobalValue::ExternalWeakLinkage, 0, "");
1040198090Srdivacky
1041193323Sed  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1042193323Sed  return FwdVal;
1043193323Sed}
1044193323Sed
1045193323Sed
1046193323Sed//===----------------------------------------------------------------------===//
1047193323Sed// Helper Routines.
1048193323Sed//===----------------------------------------------------------------------===//
1049193323Sed
1050193323Sed/// ParseToken - If the current token has the specified kind, eat it and return
1051193323Sed/// success.  Otherwise, emit the specified error and return failure.
1052193323Sedbool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1053193323Sed  if (Lex.getKind() != T)
1054193323Sed    return TokError(ErrMsg);
1055193323Sed  Lex.Lex();
1056193323Sed  return false;
1057193323Sed}
1058193323Sed
1059193323Sed/// ParseStringConstant
1060193323Sed///   ::= StringConstant
1061193323Sedbool LLParser::ParseStringConstant(std::string &Result) {
1062193323Sed  if (Lex.getKind() != lltok::StringConstant)
1063193323Sed    return TokError("expected string constant");
1064193323Sed  Result = Lex.getStrVal();
1065193323Sed  Lex.Lex();
1066193323Sed  return false;
1067193323Sed}
1068193323Sed
1069193323Sed/// ParseUInt32
1070193323Sed///   ::= uint32
1071193323Sedbool LLParser::ParseUInt32(unsigned &Val) {
1072193323Sed  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1073193323Sed    return TokError("expected integer");
1074193323Sed  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1075193323Sed  if (Val64 != unsigned(Val64))
1076193323Sed    return TokError("expected 32-bit integer (too large)");
1077193323Sed  Val = Val64;
1078193323Sed  Lex.Lex();
1079193323Sed  return false;
1080193323Sed}
1081193323Sed
1082239462Sdim/// ParseTLSModel
1083239462Sdim///   := 'localdynamic'
1084239462Sdim///   := 'initialexec'
1085239462Sdim///   := 'localexec'
1086239462Sdimbool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1087239462Sdim  switch (Lex.getKind()) {
1088239462Sdim    default:
1089239462Sdim      return TokError("expected localdynamic, initialexec or localexec");
1090239462Sdim    case lltok::kw_localdynamic:
1091239462Sdim      TLM = GlobalVariable::LocalDynamicTLSModel;
1092239462Sdim      break;
1093239462Sdim    case lltok::kw_initialexec:
1094239462Sdim      TLM = GlobalVariable::InitialExecTLSModel;
1095239462Sdim      break;
1096239462Sdim    case lltok::kw_localexec:
1097239462Sdim      TLM = GlobalVariable::LocalExecTLSModel;
1098239462Sdim      break;
1099239462Sdim  }
1100193323Sed
1101239462Sdim  Lex.Lex();
1102239462Sdim  return false;
1103239462Sdim}
1104239462Sdim
1105239462Sdim/// ParseOptionalThreadLocal
1106239462Sdim///   := /*empty*/
1107239462Sdim///   := 'thread_local'
1108239462Sdim///   := 'thread_local' '(' tlsmodel ')'
1109239462Sdimbool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1110239462Sdim  TLM = GlobalVariable::NotThreadLocal;
1111239462Sdim  if (!EatIfPresent(lltok::kw_thread_local))
1112239462Sdim    return false;
1113239462Sdim
1114239462Sdim  TLM = GlobalVariable::GeneralDynamicTLSModel;
1115239462Sdim  if (Lex.getKind() == lltok::lparen) {
1116239462Sdim    Lex.Lex();
1117239462Sdim    return ParseTLSModel(TLM) ||
1118239462Sdim      ParseToken(lltok::rparen, "expected ')' after thread local model");
1119239462Sdim  }
1120239462Sdim  return false;
1121239462Sdim}
1122239462Sdim
1123193323Sed/// ParseOptionalAddrSpace
1124193323Sed///   := /*empty*/
1125193323Sed///   := 'addrspace' '(' uint32 ')'
1126193323Sedbool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1127193323Sed  AddrSpace = 0;
1128193323Sed  if (!EatIfPresent(lltok::kw_addrspace))
1129193323Sed    return false;
1130193323Sed  return ParseToken(lltok::lparen, "expected '(' in address space") ||
1131193323Sed         ParseUInt32(AddrSpace) ||
1132193323Sed         ParseToken(lltok::rparen, "expected ')' in address space");
1133198090Srdivacky}
1134193323Sed
1135249423Sdim/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1136249423Sdimbool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1137243830Sdim  bool HaveError = false;
1138198090Srdivacky
1139243830Sdim  B.clear();
1140243830Sdim
1141193323Sed  while (1) {
1142243830Sdim    lltok::Kind Token = Lex.getKind();
1143243830Sdim    switch (Token) {
1144193323Sed    default:  // End of attributes.
1145243830Sdim      return HaveError;
1146193323Sed    case lltok::kw_align: {
1147193323Sed      unsigned Alignment;
1148193323Sed      if (ParseOptionalAlignment(Alignment))
1149193323Sed        return true;
1150243830Sdim      B.addAlignmentAttr(Alignment);
1151193323Sed      continue;
1152193323Sed    }
1153249423Sdim    case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1154249423Sdim    case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1155249423Sdim    case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1156249423Sdim    case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1157249423Sdim    case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1158249423Sdim    case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1159249423Sdim    case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1160249423Sdim    case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1161203954Srdivacky
1162249423Sdim    case lltok::kw_alignstack:      case lltok::kw_nounwind:
1163249423Sdim    case lltok::kw_alwaysinline:    case lltok::kw_optsize:
1164249423Sdim    case lltok::kw_inlinehint:      case lltok::kw_readnone:
1165249423Sdim    case lltok::kw_minsize:         case lltok::kw_readonly:
1166249423Sdim    case lltok::kw_naked:           case lltok::kw_returns_twice:
1167249423Sdim    case lltok::kw_nobuiltin:       case lltok::kw_sanitize_address:
1168249423Sdim    case lltok::kw_noimplicitfloat: case lltok::kw_sanitize_memory:
1169249423Sdim    case lltok::kw_noinline:        case lltok::kw_sanitize_thread:
1170249423Sdim    case lltok::kw_nonlazybind:     case lltok::kw_ssp:
1171249423Sdim    case lltok::kw_noredzone:       case lltok::kw_sspreq:
1172249423Sdim    case lltok::kw_noreturn:        case lltok::kw_uwtable:
1173249423Sdim      HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1174249423Sdim      break;
1175193323Sed    }
1176243830Sdim
1177249423Sdim    Lex.Lex();
1178249423Sdim  }
1179249423Sdim}
1180249423Sdim
1181249423Sdim/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1182249423Sdimbool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1183249423Sdim  bool HaveError = false;
1184249423Sdim
1185249423Sdim  B.clear();
1186249423Sdim
1187249423Sdim  while (1) {
1188249423Sdim    lltok::Kind Token = Lex.getKind();
1189243830Sdim    switch (Token) {
1190249423Sdim    default:  // End of attributes.
1191249423Sdim      return HaveError;
1192249423Sdim    case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1193249423Sdim    case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1194249423Sdim    case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1195249423Sdim    case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1196243830Sdim
1197249423Sdim    // Error handling.
1198249423Sdim    case lltok::kw_sret:  case lltok::kw_nocapture:
1199249423Sdim    case lltok::kw_byval: case lltok::kw_nest:
1200249423Sdim      HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1201243830Sdim      break;
1202243830Sdim
1203249423Sdim    case lltok::kw_align:                 case lltok::kw_noreturn:
1204249423Sdim    case lltok::kw_alignstack:            case lltok::kw_nounwind:
1205249423Sdim    case lltok::kw_alwaysinline:          case lltok::kw_optsize:
1206249423Sdim    case lltok::kw_inlinehint:            case lltok::kw_readnone:
1207249423Sdim    case lltok::kw_minsize:               case lltok::kw_readonly:
1208249423Sdim    case lltok::kw_naked:                 case lltok::kw_returns_twice:
1209249423Sdim    case lltok::kw_nobuiltin:             case lltok::kw_sanitize_address:
1210249423Sdim    case lltok::kw_noduplicate:           case lltok::kw_sanitize_memory:
1211249423Sdim    case lltok::kw_noimplicitfloat:       case lltok::kw_sanitize_thread:
1212249423Sdim    case lltok::kw_noinline:              case lltok::kw_ssp:
1213249423Sdim    case lltok::kw_nonlazybind:           case lltok::kw_sspreq:
1214249423Sdim    case lltok::kw_noredzone:             case lltok::kw_sspstrong:
1215249423Sdim                                          case lltok::kw_uwtable:
1216249423Sdim      HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1217243830Sdim      break;
1218243830Sdim    }
1219243830Sdim
1220193323Sed    Lex.Lex();
1221193323Sed  }
1222193323Sed}
1223193323Sed
1224193323Sed/// ParseOptionalLinkage
1225193323Sed///   ::= /*empty*/
1226193323Sed///   ::= 'private'
1227198090Srdivacky///   ::= 'linker_private'
1228210299Sed///   ::= 'linker_private_weak'
1229193323Sed///   ::= 'internal'
1230193323Sed///   ::= 'weak'
1231193323Sed///   ::= 'weak_odr'
1232193323Sed///   ::= 'linkonce'
1233193323Sed///   ::= 'linkonce_odr'
1234243830Sdim///   ::= 'linkonce_odr_auto_hide'
1235210299Sed///   ::= 'available_externally'
1236193323Sed///   ::= 'appending'
1237193323Sed///   ::= 'dllexport'
1238193323Sed///   ::= 'common'
1239193323Sed///   ::= 'dllimport'
1240193323Sed///   ::= 'extern_weak'
1241193323Sed///   ::= 'external'
1242193323Sedbool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1243193323Sed  HasLinkage = false;
1244193323Sed  switch (Lex.getKind()) {
1245198090Srdivacky  default:                       Res=GlobalValue::ExternalLinkage; return false;
1246198090Srdivacky  case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1247198090Srdivacky  case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1248210299Sed  case lltok::kw_linker_private_weak:
1249210299Sed    Res = GlobalValue::LinkerPrivateWeakLinkage;
1250210299Sed    break;
1251198090Srdivacky  case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1252198090Srdivacky  case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1253198090Srdivacky  case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1254198090Srdivacky  case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1255198090Srdivacky  case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1256243830Sdim  case lltok::kw_linkonce_odr_auto_hide:
1257243830Sdim  case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1258243830Sdim    Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1259243830Sdim    break;
1260193323Sed  case lltok::kw_available_externally:
1261193323Sed    Res = GlobalValue::AvailableExternallyLinkage;
1262193323Sed    break;
1263198090Srdivacky  case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1264198090Srdivacky  case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
1265198090Srdivacky  case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1266198090Srdivacky  case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
1267198090Srdivacky  case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1268198090Srdivacky  case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1269193323Sed  }
1270193323Sed  Lex.Lex();
1271193323Sed  HasLinkage = true;
1272193323Sed  return false;
1273193323Sed}
1274193323Sed
1275193323Sed/// ParseOptionalVisibility
1276193323Sed///   ::= /*empty*/
1277193323Sed///   ::= 'default'
1278193323Sed///   ::= 'hidden'
1279193323Sed///   ::= 'protected'
1280198090Srdivacky///
1281193323Sedbool LLParser::ParseOptionalVisibility(unsigned &Res) {
1282193323Sed  switch (Lex.getKind()) {
1283193323Sed  default:                  Res = GlobalValue::DefaultVisibility; return false;
1284193323Sed  case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1285193323Sed  case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1286193323Sed  case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1287193323Sed  }
1288193323Sed  Lex.Lex();
1289193323Sed  return false;
1290193323Sed}
1291193323Sed
1292193323Sed/// ParseOptionalCallingConv
1293193323Sed///   ::= /*empty*/
1294193323Sed///   ::= 'ccc'
1295193323Sed///   ::= 'fastcc'
1296243830Sdim///   ::= 'kw_intel_ocl_bicc'
1297193323Sed///   ::= 'coldcc'
1298193323Sed///   ::= 'x86_stdcallcc'
1299193323Sed///   ::= 'x86_fastcallcc'
1300208599Srdivacky///   ::= 'x86_thiscallcc'
1301194612Sed///   ::= 'arm_apcscc'
1302194612Sed///   ::= 'arm_aapcscc'
1303194612Sed///   ::= 'arm_aapcs_vfpcc'
1304200581Srdivacky///   ::= 'msp430_intrcc'
1305218893Sdim///   ::= 'ptx_kernel'
1306218893Sdim///   ::= 'ptx_device'
1307243830Sdim///   ::= 'spir_func'
1308243830Sdim///   ::= 'spir_kernel'
1309193323Sed///   ::= 'cc' UINT
1310194612Sed///
1311198090Srdivackybool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1312193323Sed  switch (Lex.getKind()) {
1313193323Sed  default:                       CC = CallingConv::C; return false;
1314193323Sed  case lltok::kw_ccc:            CC = CallingConv::C; break;
1315193323Sed  case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1316193323Sed  case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1317193323Sed  case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1318193323Sed  case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1319208599Srdivacky  case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1320194612Sed  case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1321194612Sed  case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1322194612Sed  case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1323200581Srdivacky  case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1324218893Sdim  case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1325218893Sdim  case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1326243830Sdim  case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1327243830Sdim  case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1328243830Sdim  case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1329198090Srdivacky  case lltok::kw_cc: {
1330198090Srdivacky      unsigned ArbitraryCC;
1331198090Srdivacky      Lex.Lex();
1332234353Sdim      if (ParseUInt32(ArbitraryCC))
1333198090Srdivacky        return true;
1334234353Sdim      CC = static_cast<CallingConv::ID>(ArbitraryCC);
1335234353Sdim      return false;
1336198090Srdivacky    }
1337193323Sed  }
1338198090Srdivacky
1339193323Sed  Lex.Lex();
1340193323Sed  return false;
1341193323Sed}
1342193323Sed
1343201360Srdivacky/// ParseInstructionMetadata
1344201360Srdivacky///   ::= !dbg !42 (',' !dbg !57)*
1345212904Sdimbool LLParser::ParseInstructionMetadata(Instruction *Inst,
1346212904Sdim                                        PerFunctionState *PFS) {
1347201360Srdivacky  do {
1348201360Srdivacky    if (Lex.getKind() != lltok::MetadataVar)
1349201360Srdivacky      return TokError("expected metadata after comma");
1350198090Srdivacky
1351201360Srdivacky    std::string Name = Lex.getStrVal();
1352234353Sdim    unsigned MDK = M->getMDKindID(Name);
1353201360Srdivacky    Lex.Lex();
1354198396Srdivacky
1355201360Srdivacky    MDNode *Node;
1356206083Srdivacky    SMLoc Loc = Lex.getLoc();
1357212904Sdim
1358212904Sdim    if (ParseToken(lltok::exclaim, "expected '!' here"))
1359201360Srdivacky      return true;
1360198090Srdivacky
1361212904Sdim    // This code is similar to that of ParseMetadataValue, however it needs to
1362212904Sdim    // have special-case code for a forward reference; see the comments on
1363212904Sdim    // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1364212904Sdim    // at the top level here.
1365212904Sdim    if (Lex.getKind() == lltok::lbrace) {
1366212904Sdim      ValID ID;
1367212904Sdim      if (ParseMetadataListValue(ID, PFS))
1368212904Sdim        return true;
1369212904Sdim      assert(ID.Kind == ValID::t_MDNode);
1370212904Sdim      Inst->setMetadata(MDK, ID.MDNodeVal);
1371206083Srdivacky    } else {
1372218893Sdim      unsigned NodeID = 0;
1373212904Sdim      if (ParseMDNodeID(Node, NodeID))
1374212904Sdim        return true;
1375212904Sdim      if (Node) {
1376212904Sdim        // If we got the node, add it to the instruction.
1377212904Sdim        Inst->setMetadata(MDK, Node);
1378212904Sdim      } else {
1379212904Sdim        MDRef R = { Loc, MDK, NodeID };
1380212904Sdim        // Otherwise, remember that this should be resolved later.
1381212904Sdim        ForwardRefInstMetadata[Inst].push_back(R);
1382212904Sdim      }
1383206083Srdivacky    }
1384198090Srdivacky
1385201360Srdivacky    // If this is the end of the list, we're done.
1386201360Srdivacky  } while (EatIfPresent(lltok::comma));
1387198090Srdivacky  return false;
1388198090Srdivacky}
1389198090Srdivacky
1390193323Sed/// ParseOptionalAlignment
1391193323Sed///   ::= /* empty */
1392193323Sed///   ::= 'align' 4
1393193323Sedbool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1394193323Sed  Alignment = 0;
1395193323Sed  if (!EatIfPresent(lltok::kw_align))
1396193323Sed    return false;
1397193323Sed  LocTy AlignLoc = Lex.getLoc();
1398193323Sed  if (ParseUInt32(Alignment)) return true;
1399193323Sed  if (!isPowerOf2_32(Alignment))
1400193323Sed    return Error(AlignLoc, "alignment is not a power of two");
1401212904Sdim  if (Alignment > Value::MaximumAlignment)
1402212904Sdim    return Error(AlignLoc, "huge alignments are not supported yet");
1403193323Sed  return false;
1404193323Sed}
1405193323Sed
1406201360Srdivacky/// ParseOptionalCommaAlign
1407249423Sdim///   ::=
1408201360Srdivacky///   ::= ',' align 4
1409201360Srdivacky///
1410201360Srdivacky/// This returns with AteExtraComma set to true if it ate an excess comma at the
1411201360Srdivacky/// end.
1412201360Srdivackybool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1413201360Srdivacky                                       bool &AteExtraComma) {
1414201360Srdivacky  AteExtraComma = false;
1415201360Srdivacky  while (EatIfPresent(lltok::comma)) {
1416201360Srdivacky    // Metadata at the end is an early exit.
1417201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
1418201360Srdivacky      AteExtraComma = true;
1419201360Srdivacky      return false;
1420201360Srdivacky    }
1421249423Sdim
1422207618Srdivacky    if (Lex.getKind() != lltok::kw_align)
1423207618Srdivacky      return Error(Lex.getLoc(), "expected metadata or 'align'");
1424218893Sdim
1425207618Srdivacky    if (ParseOptionalAlignment(Alignment)) return true;
1426201360Srdivacky  }
1427198090Srdivacky
1428198090Srdivacky  return false;
1429193323Sed}
1430193323Sed
1431226633Sdim/// ParseScopeAndOrdering
1432226633Sdim///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1433226633Sdim///   else: ::=
1434226633Sdim///
1435226633Sdim/// This sets Scope and Ordering to the parsed values.
1436226633Sdimbool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1437226633Sdim                                     AtomicOrdering &Ordering) {
1438226633Sdim  if (!isAtomic)
1439226633Sdim    return false;
1440226633Sdim
1441226633Sdim  Scope = CrossThread;
1442226633Sdim  if (EatIfPresent(lltok::kw_singlethread))
1443226633Sdim    Scope = SingleThread;
1444226633Sdim  switch (Lex.getKind()) {
1445226633Sdim  default: return TokError("Expected ordering on atomic instruction");
1446226633Sdim  case lltok::kw_unordered: Ordering = Unordered; break;
1447226633Sdim  case lltok::kw_monotonic: Ordering = Monotonic; break;
1448226633Sdim  case lltok::kw_acquire: Ordering = Acquire; break;
1449226633Sdim  case lltok::kw_release: Ordering = Release; break;
1450226633Sdim  case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1451226633Sdim  case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1452226633Sdim  }
1453226633Sdim  Lex.Lex();
1454226633Sdim  return false;
1455226633Sdim}
1456226633Sdim
1457203954Srdivacky/// ParseOptionalStackAlignment
1458203954Srdivacky///   ::= /* empty */
1459203954Srdivacky///   ::= 'alignstack' '(' 4 ')'
1460203954Srdivackybool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1461203954Srdivacky  Alignment = 0;
1462203954Srdivacky  if (!EatIfPresent(lltok::kw_alignstack))
1463203954Srdivacky    return false;
1464203954Srdivacky  LocTy ParenLoc = Lex.getLoc();
1465203954Srdivacky  if (!EatIfPresent(lltok::lparen))
1466203954Srdivacky    return Error(ParenLoc, "expected '('");
1467203954Srdivacky  LocTy AlignLoc = Lex.getLoc();
1468203954Srdivacky  if (ParseUInt32(Alignment)) return true;
1469203954Srdivacky  ParenLoc = Lex.getLoc();
1470203954Srdivacky  if (!EatIfPresent(lltok::rparen))
1471203954Srdivacky    return Error(ParenLoc, "expected ')'");
1472203954Srdivacky  if (!isPowerOf2_32(Alignment))
1473203954Srdivacky    return Error(AlignLoc, "stack alignment is not a power of two");
1474203954Srdivacky  return false;
1475203954Srdivacky}
1476198090Srdivacky
1477201360Srdivacky/// ParseIndexList - This parses the index list for an insert/extractvalue
1478201360Srdivacky/// instruction.  This sets AteExtraComma in the case where we eat an extra
1479201360Srdivacky/// comma at the end of the line and find that it is followed by metadata.
1480201360Srdivacky/// Clients that don't allow metadata can call the version of this function that
1481201360Srdivacky/// only takes one argument.
1482201360Srdivacky///
1483193323Sed/// ParseIndexList
1484193323Sed///    ::=  (',' uint32)+
1485201360Srdivacky///
1486201360Srdivackybool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1487201360Srdivacky                              bool &AteExtraComma) {
1488201360Srdivacky  AteExtraComma = false;
1489249423Sdim
1490193323Sed  if (Lex.getKind() != lltok::comma)
1491193323Sed    return TokError("expected ',' as start of index list");
1492198090Srdivacky
1493193323Sed  while (EatIfPresent(lltok::comma)) {
1494201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
1495201360Srdivacky      AteExtraComma = true;
1496201360Srdivacky      return false;
1497201360Srdivacky    }
1498218893Sdim    unsigned Idx = 0;
1499193323Sed    if (ParseUInt32(Idx)) return true;
1500193323Sed    Indices.push_back(Idx);
1501193323Sed  }
1502198090Srdivacky
1503193323Sed  return false;
1504193323Sed}
1505193323Sed
1506193323Sed//===----------------------------------------------------------------------===//
1507193323Sed// Type Parsing.
1508193323Sed//===----------------------------------------------------------------------===//
1509193323Sed
1510224145Sdim/// ParseType - Parse a type.
1511224145Sdimbool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1512224145Sdim  SMLoc TypeLoc = Lex.getLoc();
1513193323Sed  switch (Lex.getKind()) {
1514193323Sed  default:
1515193323Sed    return TokError("expected type");
1516193323Sed  case lltok::Type:
1517224145Sdim    // Type ::= 'float' | 'void' (etc)
1518193323Sed    Result = Lex.getTyVal();
1519198090Srdivacky    Lex.Lex();
1520193323Sed    break;
1521193323Sed  case lltok::lbrace:
1522224145Sdim    // Type ::= StructType
1523224145Sdim    if (ParseAnonStructType(Result, false))
1524193323Sed      return true;
1525193323Sed    break;
1526193323Sed  case lltok::lsquare:
1527224145Sdim    // Type ::= '[' ... ']'
1528193323Sed    Lex.Lex(); // eat the lsquare.
1529193323Sed    if (ParseArrayVectorType(Result, false))
1530193323Sed      return true;
1531193323Sed    break;
1532193323Sed  case lltok::less: // Either vector or packed struct.
1533224145Sdim    // Type ::= '<' ... '>'
1534193323Sed    Lex.Lex();
1535193323Sed    if (Lex.getKind() == lltok::lbrace) {
1536224145Sdim      if (ParseAnonStructType(Result, true) ||
1537193323Sed          ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1538193323Sed        return true;
1539193323Sed    } else if (ParseArrayVectorType(Result, true))
1540193323Sed      return true;
1541193323Sed    break;
1542224145Sdim  case lltok::LocalVar: {
1543224145Sdim    // Type ::= %foo
1544224145Sdim    std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1545249423Sdim
1546224145Sdim    // If the type hasn't been defined yet, create a forward definition and
1547224145Sdim    // remember where that forward def'n was seen (in case it never is defined).
1548224145Sdim    if (Entry.first == 0) {
1549226633Sdim      Entry.first = StructType::create(Context, Lex.getStrVal());
1550224145Sdim      Entry.second = Lex.getLoc();
1551193323Sed    }
1552224145Sdim    Result = Entry.first;
1553193323Sed    Lex.Lex();
1554193323Sed    break;
1555224145Sdim  }
1556198090Srdivacky
1557224145Sdim  case lltok::LocalVarID: {
1558224145Sdim    // Type ::= %4
1559224145Sdim    if (Lex.getUIntVal() >= NumberedTypes.size())
1560224145Sdim      NumberedTypes.resize(Lex.getUIntVal()+1);
1561224145Sdim    std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1562249423Sdim
1563224145Sdim    // If the type hasn't been defined yet, create a forward definition and
1564224145Sdim    // remember where that forward def'n was seen (in case it never is defined).
1565224145Sdim    if (Entry.first == 0) {
1566226633Sdim      Entry.first = StructType::create(Context);
1567224145Sdim      Entry.second = Lex.getLoc();
1568193323Sed    }
1569224145Sdim    Result = Entry.first;
1570193323Sed    Lex.Lex();
1571193323Sed    break;
1572193323Sed  }
1573193323Sed  }
1574198090Srdivacky
1575198090Srdivacky  // Parse the type suffixes.
1576193323Sed  while (1) {
1577193323Sed    switch (Lex.getKind()) {
1578193323Sed    // End of type.
1579224145Sdim    default:
1580224145Sdim      if (!AllowVoid && Result->isVoidTy())
1581224145Sdim        return Error(TypeLoc, "void type only allowed for function results");
1582224145Sdim      return false;
1583193323Sed
1584224145Sdim    // Type ::= Type '*'
1585193323Sed    case lltok::star:
1586224145Sdim      if (Result->isLabelTy())
1587193323Sed        return TokError("basic block pointers are invalid");
1588224145Sdim      if (Result->isVoidTy())
1589224145Sdim        return TokError("pointers to void are invalid - use i8* instead");
1590224145Sdim      if (!PointerType::isValidElementType(Result))
1591193630Sed        return TokError("pointer to this type is invalid");
1592224145Sdim      Result = PointerType::getUnqual(Result);
1593193323Sed      Lex.Lex();
1594193323Sed      break;
1595193323Sed
1596224145Sdim    // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1597193323Sed    case lltok::kw_addrspace: {
1598224145Sdim      if (Result->isLabelTy())
1599193323Sed        return TokError("basic block pointers are invalid");
1600224145Sdim      if (Result->isVoidTy())
1601193323Sed        return TokError("pointers to void are invalid; use i8* instead");
1602224145Sdim      if (!PointerType::isValidElementType(Result))
1603193630Sed        return TokError("pointer to this type is invalid");
1604193323Sed      unsigned AddrSpace;
1605193323Sed      if (ParseOptionalAddrSpace(AddrSpace) ||
1606193323Sed          ParseToken(lltok::star, "expected '*' in address space"))
1607193323Sed        return true;
1608193323Sed
1609224145Sdim      Result = PointerType::get(Result, AddrSpace);
1610193323Sed      break;
1611193323Sed    }
1612198090Srdivacky
1613193323Sed    /// Types '(' ArgTypeListI ')' OptFuncAttrs
1614193323Sed    case lltok::lparen:
1615193323Sed      if (ParseFunctionType(Result))
1616193323Sed        return true;
1617193323Sed      break;
1618193323Sed    }
1619193323Sed  }
1620193323Sed}
1621193323Sed
1622193323Sed/// ParseParameterList
1623193323Sed///    ::= '(' ')'
1624193323Sed///    ::= '(' Arg (',' Arg)* ')'
1625193323Sed///  Arg
1626193323Sed///    ::= Type OptionalAttributes Value OptionalAttributes
1627193323Sedbool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1628193323Sed                                  PerFunctionState &PFS) {
1629193323Sed  if (ParseToken(lltok::lparen, "expected '(' in call"))
1630193323Sed    return true;
1631198090Srdivacky
1632249423Sdim  unsigned AttrIndex = 1;
1633193323Sed  while (Lex.getKind() != lltok::rparen) {
1634193323Sed    // If this isn't the first argument, we need a comma.
1635193323Sed    if (!ArgList.empty() &&
1636193323Sed        ParseToken(lltok::comma, "expected ',' in argument list"))
1637193323Sed      return true;
1638198090Srdivacky
1639193323Sed    // Parse the argument.
1640193323Sed    LocTy ArgLoc;
1641224145Sdim    Type *ArgTy = 0;
1642243830Sdim    AttrBuilder ArgAttrs;
1643193323Sed    Value *V;
1644200581Srdivacky    if (ParseType(ArgTy, ArgLoc))
1645193323Sed      return true;
1646200581Srdivacky
1647201360Srdivacky    // Otherwise, handle normal operands.
1648249423Sdim    if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1649201360Srdivacky      return true;
1650249423Sdim    ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1651249423Sdim                                                             AttrIndex++,
1652249423Sdim                                                             ArgAttrs)));
1653193323Sed  }
1654193323Sed
1655193323Sed  Lex.Lex();  // Lex the ')'.
1656193323Sed  return false;
1657193323Sed}
1658193323Sed
1659193323Sed
1660193323Sed
1661193323Sed/// ParseArgumentList - Parse the argument list for a function type or function
1662224145Sdim/// prototype.
1663193323Sed///   ::= '(' ArgTypeListI ')'
1664193323Sed/// ArgTypeListI
1665193323Sed///   ::= /*empty*/
1666193323Sed///   ::= '...'
1667193323Sed///   ::= ArgTypeList ',' '...'
1668193323Sed///   ::= ArgType (',' ArgType)*
1669193323Sed///
1670224145Sdimbool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1671224145Sdim                                 bool &isVarArg){
1672193323Sed  isVarArg = false;
1673193323Sed  assert(Lex.getKind() == lltok::lparen);
1674193323Sed  Lex.Lex(); // eat the (.
1675198090Srdivacky
1676193323Sed  if (Lex.getKind() == lltok::rparen) {
1677193323Sed    // empty
1678193323Sed  } else if (Lex.getKind() == lltok::dotdotdot) {
1679193323Sed    isVarArg = true;
1680193323Sed    Lex.Lex();
1681193323Sed  } else {
1682193323Sed    LocTy TypeLoc = Lex.getLoc();
1683224145Sdim    Type *ArgTy = 0;
1684243830Sdim    AttrBuilder Attrs;
1685193323Sed    std::string Name;
1686198090Srdivacky
1687224145Sdim    if (ParseType(ArgTy) ||
1688249423Sdim        ParseOptionalParamAttrs(Attrs)) return true;
1689198090Srdivacky
1690198090Srdivacky    if (ArgTy->isVoidTy())
1691193323Sed      return Error(TypeLoc, "argument can not have void type");
1692198090Srdivacky
1693224145Sdim    if (Lex.getKind() == lltok::LocalVar) {
1694193323Sed      Name = Lex.getStrVal();
1695193323Sed      Lex.Lex();
1696193323Sed    }
1697193323Sed
1698193630Sed    if (!FunctionType::isValidArgumentType(ArgTy))
1699193323Sed      return Error(TypeLoc, "invalid type for function argument");
1700198090Srdivacky
1701249423Sdim    unsigned AttrIndex = 1;
1702243830Sdim    ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1703249423Sdim                              AttributeSet::get(ArgTy->getContext(),
1704249423Sdim                                                AttrIndex++, Attrs), Name));
1705198090Srdivacky
1706193323Sed    while (EatIfPresent(lltok::comma)) {
1707193323Sed      // Handle ... at end of arg list.
1708193323Sed      if (EatIfPresent(lltok::dotdotdot)) {
1709193323Sed        isVarArg = true;
1710193323Sed        break;
1711193323Sed      }
1712198090Srdivacky
1713193323Sed      // Otherwise must be an argument type.
1714193323Sed      TypeLoc = Lex.getLoc();
1715249423Sdim      if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1716193323Sed
1717198090Srdivacky      if (ArgTy->isVoidTy())
1718193323Sed        return Error(TypeLoc, "argument can not have void type");
1719193323Sed
1720224145Sdim      if (Lex.getKind() == lltok::LocalVar) {
1721193323Sed        Name = Lex.getStrVal();
1722193323Sed        Lex.Lex();
1723193323Sed      } else {
1724193323Sed        Name = "";
1725193323Sed      }
1726193323Sed
1727224145Sdim      if (!ArgTy->isFirstClassType())
1728193323Sed        return Error(TypeLoc, "invalid type for function argument");
1729198090Srdivacky
1730243830Sdim      ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1731249423Sdim                                AttributeSet::get(ArgTy->getContext(),
1732249423Sdim                                                  AttrIndex++, Attrs),
1733243830Sdim                                Name));
1734193323Sed    }
1735193323Sed  }
1736198090Srdivacky
1737193323Sed  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1738193323Sed}
1739198090Srdivacky
1740193323Sed/// ParseFunctionType
1741193323Sed///  ::= Type ArgumentList OptionalAttrs
1742224145Sdimbool LLParser::ParseFunctionType(Type *&Result) {
1743193323Sed  assert(Lex.getKind() == lltok::lparen);
1744193323Sed
1745193323Sed  if (!FunctionType::isValidReturnType(Result))
1746193323Sed    return TokError("invalid function return type");
1747198090Srdivacky
1748224145Sdim  SmallVector<ArgInfo, 8> ArgList;
1749193323Sed  bool isVarArg;
1750224145Sdim  if (ParseArgumentList(ArgList, isVarArg))
1751193323Sed    return true;
1752198090Srdivacky
1753193323Sed  // Reject names on the arguments lists.
1754193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1755193323Sed    if (!ArgList[i].Name.empty())
1756193323Sed      return Error(ArgList[i].Loc, "argument name invalid in function type");
1757249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1))
1758224145Sdim      return Error(ArgList[i].Loc,
1759224145Sdim                   "argument attributes invalid in function type");
1760193323Sed  }
1761198090Srdivacky
1762224145Sdim  SmallVector<Type*, 16> ArgListTy;
1763193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1764224145Sdim    ArgListTy.push_back(ArgList[i].Ty);
1765198090Srdivacky
1766224145Sdim  Result = FunctionType::get(Result, ArgListTy, isVarArg);
1767193323Sed  return false;
1768193323Sed}
1769193323Sed
1770224145Sdim/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1771224145Sdim/// other structs.
1772224145Sdimbool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1773224145Sdim  SmallVector<Type*, 8> Elts;
1774224145Sdim  if (ParseStructBody(Elts)) return true;
1775249423Sdim
1776224145Sdim  Result = StructType::get(Context, Elts, Packed);
1777224145Sdim  return false;
1778224145Sdim}
1779224145Sdim
1780224145Sdim/// ParseStructDefinition - Parse a struct in a 'type' definition.
1781224145Sdimbool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1782224145Sdim                                     std::pair<Type*, LocTy> &Entry,
1783224145Sdim                                     Type *&ResultTy) {
1784224145Sdim  // If the type was already defined, diagnose the redefinition.
1785224145Sdim  if (Entry.first && !Entry.second.isValid())
1786224145Sdim    return Error(TypeLoc, "redefinition of type");
1787249423Sdim
1788224145Sdim  // If we have opaque, just return without filling in the definition for the
1789224145Sdim  // struct.  This counts as a definition as far as the .ll file goes.
1790224145Sdim  if (EatIfPresent(lltok::kw_opaque)) {
1791224145Sdim    // This type is being defined, so clear the location to indicate this.
1792224145Sdim    Entry.second = SMLoc();
1793249423Sdim
1794224145Sdim    // If this type number has never been uttered, create it.
1795224145Sdim    if (Entry.first == 0)
1796226633Sdim      Entry.first = StructType::create(Context, Name);
1797224145Sdim    ResultTy = Entry.first;
1798224145Sdim    return false;
1799224145Sdim  }
1800249423Sdim
1801224145Sdim  // If the type starts with '<', then it is either a packed struct or a vector.
1802224145Sdim  bool isPacked = EatIfPresent(lltok::less);
1803224145Sdim
1804224145Sdim  // If we don't have a struct, then we have a random type alias, which we
1805224145Sdim  // accept for compatibility with old files.  These types are not allowed to be
1806224145Sdim  // forward referenced and not allowed to be recursive.
1807224145Sdim  if (Lex.getKind() != lltok::lbrace) {
1808224145Sdim    if (Entry.first)
1809224145Sdim      return Error(TypeLoc, "forward references to non-struct type");
1810249423Sdim
1811224145Sdim    ResultTy = 0;
1812224145Sdim    if (isPacked)
1813224145Sdim      return ParseArrayVectorType(ResultTy, true);
1814224145Sdim    return ParseType(ResultTy);
1815224145Sdim  }
1816249423Sdim
1817224145Sdim  // This type is being defined, so clear the location to indicate this.
1818224145Sdim  Entry.second = SMLoc();
1819249423Sdim
1820224145Sdim  // If this type number has never been uttered, create it.
1821224145Sdim  if (Entry.first == 0)
1822226633Sdim    Entry.first = StructType::create(Context, Name);
1823249423Sdim
1824224145Sdim  StructType *STy = cast<StructType>(Entry.first);
1825249423Sdim
1826224145Sdim  SmallVector<Type*, 8> Body;
1827224145Sdim  if (ParseStructBody(Body) ||
1828224145Sdim      (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1829224145Sdim    return true;
1830249423Sdim
1831224145Sdim  STy->setBody(Body, isPacked);
1832224145Sdim  ResultTy = STy;
1833224145Sdim  return false;
1834224145Sdim}
1835224145Sdim
1836224145Sdim
1837193323Sed/// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1838224145Sdim///   StructType
1839193323Sed///     ::= '{' '}'
1840224145Sdim///     ::= '{' Type (',' Type)* '}'
1841193323Sed///     ::= '<' '{' '}' '>'
1842224145Sdim///     ::= '<' '{' Type (',' Type)* '}' '>'
1843224145Sdimbool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1844193323Sed  assert(Lex.getKind() == lltok::lbrace);
1845193323Sed  Lex.Lex(); // Consume the '{'
1846198090Srdivacky
1847224145Sdim  // Handle the empty struct.
1848224145Sdim  if (EatIfPresent(lltok::rbrace))
1849193323Sed    return false;
1850193323Sed
1851193323Sed  LocTy EltTyLoc = Lex.getLoc();
1852224145Sdim  Type *Ty = 0;
1853224145Sdim  if (ParseType(Ty)) return true;
1854224145Sdim  Body.push_back(Ty);
1855198090Srdivacky
1856224145Sdim  if (!StructType::isValidElementType(Ty))
1857193630Sed    return Error(EltTyLoc, "invalid element type for struct");
1858198090Srdivacky
1859193323Sed  while (EatIfPresent(lltok::comma)) {
1860193323Sed    EltTyLoc = Lex.getLoc();
1861224145Sdim    if (ParseType(Ty)) return true;
1862198090Srdivacky
1863224145Sdim    if (!StructType::isValidElementType(Ty))
1864193630Sed      return Error(EltTyLoc, "invalid element type for struct");
1865198090Srdivacky
1866224145Sdim    Body.push_back(Ty);
1867193323Sed  }
1868198090Srdivacky
1869224145Sdim  return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1870193323Sed}
1871193323Sed
1872193323Sed/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1873193323Sed/// token has already been consumed.
1874224145Sdim///   Type
1875193323Sed///     ::= '[' APSINTVAL 'x' Types ']'
1876193323Sed///     ::= '<' APSINTVAL 'x' Types '>'
1877224145Sdimbool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1878193323Sed  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1879193323Sed      Lex.getAPSIntVal().getBitWidth() > 64)
1880193323Sed    return TokError("expected number in address space");
1881198090Srdivacky
1882193323Sed  LocTy SizeLoc = Lex.getLoc();
1883193323Sed  uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1884193323Sed  Lex.Lex();
1885198090Srdivacky
1886193323Sed  if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1887193323Sed      return true;
1888193323Sed
1889193323Sed  LocTy TypeLoc = Lex.getLoc();
1890224145Sdim  Type *EltTy = 0;
1891224145Sdim  if (ParseType(EltTy)) return true;
1892198090Srdivacky
1893193323Sed  if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1894193323Sed                 "expected end of sequential type"))
1895193323Sed    return true;
1896198090Srdivacky
1897193323Sed  if (isVector) {
1898193323Sed    if (Size == 0)
1899193323Sed      return Error(SizeLoc, "zero element vector is illegal");
1900193323Sed    if ((unsigned)Size != Size)
1901193323Sed      return Error(SizeLoc, "size too large for vector");
1902193630Sed    if (!VectorType::isValidElementType(EltTy))
1903249423Sdim      return Error(TypeLoc, "invalid vector element type");
1904198090Srdivacky    Result = VectorType::get(EltTy, unsigned(Size));
1905193323Sed  } else {
1906193630Sed    if (!ArrayType::isValidElementType(EltTy))
1907193323Sed      return Error(TypeLoc, "invalid array element type");
1908224145Sdim    Result = ArrayType::get(EltTy, Size);
1909193323Sed  }
1910193323Sed  return false;
1911193323Sed}
1912193323Sed
1913193323Sed//===----------------------------------------------------------------------===//
1914193323Sed// Function Semantic Analysis.
1915193323Sed//===----------------------------------------------------------------------===//
1916193323Sed
1917198892SrdivackyLLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1918198892Srdivacky                                             int functionNumber)
1919198892Srdivacky  : P(p), F(f), FunctionNumber(functionNumber) {
1920193323Sed
1921193323Sed  // Insert unnamed arguments into the NumberedVals list.
1922193323Sed  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1923193323Sed       AI != E; ++AI)
1924193323Sed    if (!AI->hasName())
1925193323Sed      NumberedVals.push_back(AI);
1926193323Sed}
1927193323Sed
1928193323SedLLParser::PerFunctionState::~PerFunctionState() {
1929193323Sed  // If there were any forward referenced non-basicblock values, delete them.
1930193323Sed  for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1931193323Sed       I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1932193323Sed    if (!isa<BasicBlock>(I->second.first)) {
1933195340Sed      I->second.first->replaceAllUsesWith(
1934198090Srdivacky                           UndefValue::get(I->second.first->getType()));
1935193323Sed      delete I->second.first;
1936193323Sed      I->second.first = 0;
1937193323Sed    }
1938198090Srdivacky
1939193323Sed  for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1940193323Sed       I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1941193323Sed    if (!isa<BasicBlock>(I->second.first)) {
1942195340Sed      I->second.first->replaceAllUsesWith(
1943198090Srdivacky                           UndefValue::get(I->second.first->getType()));
1944193323Sed      delete I->second.first;
1945193323Sed      I->second.first = 0;
1946193323Sed    }
1947193323Sed}
1948193323Sed
1949198892Srdivackybool LLParser::PerFunctionState::FinishFunction() {
1950198892Srdivacky  // Check to see if someone took the address of labels in this block.
1951198892Srdivacky  if (!P.ForwardRefBlockAddresses.empty()) {
1952198892Srdivacky    ValID FunctionID;
1953198892Srdivacky    if (!F.getName().empty()) {
1954198892Srdivacky      FunctionID.Kind = ValID::t_GlobalName;
1955198892Srdivacky      FunctionID.StrVal = F.getName();
1956198892Srdivacky    } else {
1957198892Srdivacky      FunctionID.Kind = ValID::t_GlobalID;
1958198892Srdivacky      FunctionID.UIntVal = FunctionNumber;
1959198892Srdivacky    }
1960249423Sdim
1961198892Srdivacky    std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1962198892Srdivacky      FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1963198892Srdivacky    if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1964198892Srdivacky      // Resolve all these references.
1965198892Srdivacky      if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1966198892Srdivacky        return true;
1967249423Sdim
1968198892Srdivacky      P.ForwardRefBlockAddresses.erase(FRBAI);
1969198892Srdivacky    }
1970198892Srdivacky  }
1971249423Sdim
1972193323Sed  if (!ForwardRefVals.empty())
1973193323Sed    return P.Error(ForwardRefVals.begin()->second.second,
1974193323Sed                   "use of undefined value '%" + ForwardRefVals.begin()->first +
1975193323Sed                   "'");
1976193323Sed  if (!ForwardRefValIDs.empty())
1977193323Sed    return P.Error(ForwardRefValIDs.begin()->second.second,
1978193323Sed                   "use of undefined value '%" +
1979218893Sdim                   Twine(ForwardRefValIDs.begin()->first) + "'");
1980193323Sed  return false;
1981193323Sed}
1982193323Sed
1983193323Sed
1984193323Sed/// GetVal - Get a value with the specified name or ID, creating a
1985193323Sed/// forward reference record if needed.  This can return null if the value
1986193323Sed/// exists but does not have the right type.
1987193323SedValue *LLParser::PerFunctionState::GetVal(const std::string &Name,
1988226633Sdim                                          Type *Ty, LocTy Loc) {
1989193323Sed  // Look this name up in the normal function symbol table.
1990193323Sed  Value *Val = F.getValueSymbolTable().lookup(Name);
1991198090Srdivacky
1992193323Sed  // If this is a forward reference for the value, see if we already created a
1993193323Sed  // forward ref record.
1994193323Sed  if (Val == 0) {
1995193323Sed    std::map<std::string, std::pair<Value*, LocTy> >::iterator
1996193323Sed      I = ForwardRefVals.find(Name);
1997193323Sed    if (I != ForwardRefVals.end())
1998193323Sed      Val = I->second.first;
1999193323Sed  }
2000198090Srdivacky
2001193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
2002193323Sed  if (Val) {
2003193323Sed    if (Val->getType() == Ty) return Val;
2004198090Srdivacky    if (Ty->isLabelTy())
2005193323Sed      P.Error(Loc, "'%" + Name + "' is not a basic block");
2006193323Sed    else
2007193323Sed      P.Error(Loc, "'%" + Name + "' defined with type '" +
2008224145Sdim              getTypeString(Val->getType()) + "'");
2009193323Sed    return 0;
2010193323Sed  }
2011198090Srdivacky
2012193323Sed  // Don't make placeholders with invalid type.
2013224145Sdim  if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2014193323Sed    P.Error(Loc, "invalid use of a non-first-class type");
2015193323Sed    return 0;
2016193323Sed  }
2017198090Srdivacky
2018193323Sed  // Otherwise, create a new forward reference for this value and remember it.
2019193323Sed  Value *FwdVal;
2020198090Srdivacky  if (Ty->isLabelTy())
2021198090Srdivacky    FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2022193323Sed  else
2023193323Sed    FwdVal = new Argument(Ty, Name);
2024198090Srdivacky
2025193323Sed  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2026193323Sed  return FwdVal;
2027193323Sed}
2028193323Sed
2029226633SdimValue *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2030193323Sed                                          LocTy Loc) {
2031193323Sed  // Look this name up in the normal function symbol table.
2032193323Sed  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2033198090Srdivacky
2034193323Sed  // If this is a forward reference for the value, see if we already created a
2035193323Sed  // forward ref record.
2036193323Sed  if (Val == 0) {
2037193323Sed    std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2038193323Sed      I = ForwardRefValIDs.find(ID);
2039193323Sed    if (I != ForwardRefValIDs.end())
2040193323Sed      Val = I->second.first;
2041193323Sed  }
2042198090Srdivacky
2043193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
2044193323Sed  if (Val) {
2045193323Sed    if (Val->getType() == Ty) return Val;
2046198090Srdivacky    if (Ty->isLabelTy())
2047218893Sdim      P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2048193323Sed    else
2049218893Sdim      P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2050224145Sdim              getTypeString(Val->getType()) + "'");
2051193323Sed    return 0;
2052193323Sed  }
2053198090Srdivacky
2054224145Sdim  if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2055193323Sed    P.Error(Loc, "invalid use of a non-first-class type");
2056193323Sed    return 0;
2057193323Sed  }
2058198090Srdivacky
2059193323Sed  // Otherwise, create a new forward reference for this value and remember it.
2060193323Sed  Value *FwdVal;
2061198090Srdivacky  if (Ty->isLabelTy())
2062198090Srdivacky    FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2063193323Sed  else
2064193323Sed    FwdVal = new Argument(Ty);
2065198090Srdivacky
2066193323Sed  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2067193323Sed  return FwdVal;
2068193323Sed}
2069193323Sed
2070193323Sed/// SetInstName - After an instruction is parsed and inserted into its
2071193323Sed/// basic block, this installs its name.
2072193323Sedbool LLParser::PerFunctionState::SetInstName(int NameID,
2073193323Sed                                             const std::string &NameStr,
2074193323Sed                                             LocTy NameLoc, Instruction *Inst) {
2075193323Sed  // If this instruction has void type, it cannot have a name or ID specified.
2076198090Srdivacky  if (Inst->getType()->isVoidTy()) {
2077193323Sed    if (NameID != -1 || !NameStr.empty())
2078193323Sed      return P.Error(NameLoc, "instructions returning void cannot have a name");
2079193323Sed    return false;
2080193323Sed  }
2081198090Srdivacky
2082193323Sed  // If this was a numbered instruction, verify that the instruction is the
2083193323Sed  // expected value and resolve any forward references.
2084193323Sed  if (NameStr.empty()) {
2085193323Sed    // If neither a name nor an ID was specified, just use the next ID.
2086193323Sed    if (NameID == -1)
2087193323Sed      NameID = NumberedVals.size();
2088198090Srdivacky
2089193323Sed    if (unsigned(NameID) != NumberedVals.size())
2090193323Sed      return P.Error(NameLoc, "instruction expected to be numbered '%" +
2091218893Sdim                     Twine(NumberedVals.size()) + "'");
2092198090Srdivacky
2093193323Sed    std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2094193323Sed      ForwardRefValIDs.find(NameID);
2095193323Sed    if (FI != ForwardRefValIDs.end()) {
2096193323Sed      if (FI->second.first->getType() != Inst->getType())
2097198090Srdivacky        return P.Error(NameLoc, "instruction forward referenced with type '" +
2098224145Sdim                       getTypeString(FI->second.first->getType()) + "'");
2099193323Sed      FI->second.first->replaceAllUsesWith(Inst);
2100198090Srdivacky      delete FI->second.first;
2101193323Sed      ForwardRefValIDs.erase(FI);
2102193323Sed    }
2103193323Sed
2104193323Sed    NumberedVals.push_back(Inst);
2105193323Sed    return false;
2106193323Sed  }
2107193323Sed
2108193323Sed  // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2109193323Sed  std::map<std::string, std::pair<Value*, LocTy> >::iterator
2110193323Sed    FI = ForwardRefVals.find(NameStr);
2111193323Sed  if (FI != ForwardRefVals.end()) {
2112193323Sed    if (FI->second.first->getType() != Inst->getType())
2113198090Srdivacky      return P.Error(NameLoc, "instruction forward referenced with type '" +
2114224145Sdim                     getTypeString(FI->second.first->getType()) + "'");
2115193323Sed    FI->second.first->replaceAllUsesWith(Inst);
2116198090Srdivacky    delete FI->second.first;
2117193323Sed    ForwardRefVals.erase(FI);
2118193323Sed  }
2119198090Srdivacky
2120193323Sed  // Set the name on the instruction.
2121193323Sed  Inst->setName(NameStr);
2122198090Srdivacky
2123218893Sdim  if (Inst->getName() != NameStr)
2124198090Srdivacky    return P.Error(NameLoc, "multiple definition of local value named '" +
2125193323Sed                   NameStr + "'");
2126193323Sed  return false;
2127193323Sed}
2128193323Sed
2129193323Sed/// GetBB - Get a basic block with the specified name or ID, creating a
2130193323Sed/// forward reference record if needed.
2131193323SedBasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2132193323Sed                                              LocTy Loc) {
2133198090Srdivacky  return cast_or_null<BasicBlock>(GetVal(Name,
2134198090Srdivacky                                        Type::getLabelTy(F.getContext()), Loc));
2135193323Sed}
2136193323Sed
2137193323SedBasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2138198090Srdivacky  return cast_or_null<BasicBlock>(GetVal(ID,
2139198090Srdivacky                                        Type::getLabelTy(F.getContext()), Loc));
2140193323Sed}
2141193323Sed
2142193323Sed/// DefineBB - Define the specified basic block, which is either named or
2143193323Sed/// unnamed.  If there is an error, this returns null otherwise it returns
2144193323Sed/// the block being defined.
2145193323SedBasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2146193323Sed                                                 LocTy Loc) {
2147193323Sed  BasicBlock *BB;
2148193323Sed  if (Name.empty())
2149193323Sed    BB = GetBB(NumberedVals.size(), Loc);
2150193323Sed  else
2151193323Sed    BB = GetBB(Name, Loc);
2152193323Sed  if (BB == 0) return 0; // Already diagnosed error.
2153198090Srdivacky
2154193323Sed  // Move the block to the end of the function.  Forward ref'd blocks are
2155193323Sed  // inserted wherever they happen to be referenced.
2156193323Sed  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2157198090Srdivacky
2158193323Sed  // Remove the block from forward ref sets.
2159193323Sed  if (Name.empty()) {
2160193323Sed    ForwardRefValIDs.erase(NumberedVals.size());
2161193323Sed    NumberedVals.push_back(BB);
2162193323Sed  } else {
2163193323Sed    // BB forward references are already in the function symbol table.
2164193323Sed    ForwardRefVals.erase(Name);
2165193323Sed  }
2166198090Srdivacky
2167193323Sed  return BB;
2168193323Sed}
2169193323Sed
2170193323Sed//===----------------------------------------------------------------------===//
2171193323Sed// Constants.
2172193323Sed//===----------------------------------------------------------------------===//
2173193323Sed
2174193323Sed/// ParseValID - Parse an abstract value that doesn't necessarily have a
2175193323Sed/// type implied.  For example, if we parse "4" we don't know what integer type
2176193323Sed/// it has.  The value will later be combined with its type and checked for
2177202375Srdivacky/// sanity.  PFS is used to convert function-local operands of metadata (since
2178202375Srdivacky/// metadata operands are not just parsed here but also converted to values).
2179202375Srdivacky/// PFS can be null when we are not parsing metadata values inside a function.
2180202375Srdivackybool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2181193323Sed  ID.Loc = Lex.getLoc();
2182193323Sed  switch (Lex.getKind()) {
2183193323Sed  default: return TokError("expected value token");
2184193323Sed  case lltok::GlobalID:  // @42
2185193323Sed    ID.UIntVal = Lex.getUIntVal();
2186193323Sed    ID.Kind = ValID::t_GlobalID;
2187193323Sed    break;
2188193323Sed  case lltok::GlobalVar:  // @foo
2189193323Sed    ID.StrVal = Lex.getStrVal();
2190193323Sed    ID.Kind = ValID::t_GlobalName;
2191193323Sed    break;
2192193323Sed  case lltok::LocalVarID:  // %42
2193193323Sed    ID.UIntVal = Lex.getUIntVal();
2194193323Sed    ID.Kind = ValID::t_LocalID;
2195193323Sed    break;
2196193323Sed  case lltok::LocalVar:  // %foo
2197193323Sed    ID.StrVal = Lex.getStrVal();
2198193323Sed    ID.Kind = ValID::t_LocalName;
2199193323Sed    break;
2200210299Sed  case lltok::exclaim:   // !42, !{...}, or !"foo"
2201210299Sed    return ParseMetadataValue(ID, PFS);
2202193323Sed  case lltok::APSInt:
2203198090Srdivacky    ID.APSIntVal = Lex.getAPSIntVal();
2204193323Sed    ID.Kind = ValID::t_APSInt;
2205193323Sed    break;
2206193323Sed  case lltok::APFloat:
2207193323Sed    ID.APFloatVal = Lex.getAPFloatVal();
2208193323Sed    ID.Kind = ValID::t_APFloat;
2209193323Sed    break;
2210193323Sed  case lltok::kw_true:
2211198090Srdivacky    ID.ConstantVal = ConstantInt::getTrue(Context);
2212193323Sed    ID.Kind = ValID::t_Constant;
2213193323Sed    break;
2214193323Sed  case lltok::kw_false:
2215198090Srdivacky    ID.ConstantVal = ConstantInt::getFalse(Context);
2216193323Sed    ID.Kind = ValID::t_Constant;
2217193323Sed    break;
2218193323Sed  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2219193323Sed  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2220193323Sed  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2221198090Srdivacky
2222193323Sed  case lltok::lbrace: {
2223193323Sed    // ValID ::= '{' ConstVector '}'
2224193323Sed    Lex.Lex();
2225193323Sed    SmallVector<Constant*, 16> Elts;
2226193323Sed    if (ParseGlobalValueVector(Elts) ||
2227193323Sed        ParseToken(lltok::rbrace, "expected end of struct constant"))
2228193323Sed      return true;
2229198090Srdivacky
2230224145Sdim    ID.ConstantStructElts = new Constant*[Elts.size()];
2231224145Sdim    ID.UIntVal = Elts.size();
2232224145Sdim    memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2233224145Sdim    ID.Kind = ValID::t_ConstantStruct;
2234193323Sed    return false;
2235193323Sed  }
2236193323Sed  case lltok::less: {
2237193323Sed    // ValID ::= '<' ConstVector '>'         --> Vector.
2238193323Sed    // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2239193323Sed    Lex.Lex();
2240193323Sed    bool isPackedStruct = EatIfPresent(lltok::lbrace);
2241198090Srdivacky
2242193323Sed    SmallVector<Constant*, 16> Elts;
2243193323Sed    LocTy FirstEltLoc = Lex.getLoc();
2244193323Sed    if (ParseGlobalValueVector(Elts) ||
2245193323Sed        (isPackedStruct &&
2246193323Sed         ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2247193323Sed        ParseToken(lltok::greater, "expected end of constant"))
2248193323Sed      return true;
2249198090Srdivacky
2250193323Sed    if (isPackedStruct) {
2251224145Sdim      ID.ConstantStructElts = new Constant*[Elts.size()];
2252224145Sdim      memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2253224145Sdim      ID.UIntVal = Elts.size();
2254224145Sdim      ID.Kind = ValID::t_PackedConstantStruct;
2255193323Sed      return false;
2256193323Sed    }
2257198090Srdivacky
2258193323Sed    if (Elts.empty())
2259193323Sed      return Error(ID.Loc, "constant vector must not be empty");
2260193323Sed
2261203954Srdivacky    if (!Elts[0]->getType()->isIntegerTy() &&
2262234353Sdim        !Elts[0]->getType()->isFloatingPointTy() &&
2263234353Sdim        !Elts[0]->getType()->isPointerTy())
2264193323Sed      return Error(FirstEltLoc,
2265234353Sdim            "vector elements must have integer, pointer or floating point type");
2266198090Srdivacky
2267193323Sed    // Verify that all the vector elements have the same type.
2268193323Sed    for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2269193323Sed      if (Elts[i]->getType() != Elts[0]->getType())
2270193323Sed        return Error(FirstEltLoc,
2271218893Sdim                     "vector element #" + Twine(i) +
2272224145Sdim                    " is not of type '" + getTypeString(Elts[0]->getType()));
2273198090Srdivacky
2274218893Sdim    ID.ConstantVal = ConstantVector::get(Elts);
2275193323Sed    ID.Kind = ValID::t_Constant;
2276193323Sed    return false;
2277193323Sed  }
2278193323Sed  case lltok::lsquare: {   // Array Constant
2279193323Sed    Lex.Lex();
2280193323Sed    SmallVector<Constant*, 16> Elts;
2281193323Sed    LocTy FirstEltLoc = Lex.getLoc();
2282193323Sed    if (ParseGlobalValueVector(Elts) ||
2283193323Sed        ParseToken(lltok::rsquare, "expected end of array constant"))
2284193323Sed      return true;
2285193323Sed
2286193323Sed    // Handle empty element.
2287193323Sed    if (Elts.empty()) {
2288193323Sed      // Use undef instead of an array because it's inconvenient to determine
2289193323Sed      // the element type at this point, there being no elements to examine.
2290193323Sed      ID.Kind = ValID::t_EmptyArray;
2291193323Sed      return false;
2292193323Sed    }
2293198090Srdivacky
2294193323Sed    if (!Elts[0]->getType()->isFirstClassType())
2295198090Srdivacky      return Error(FirstEltLoc, "invalid array element type: " +
2296224145Sdim                   getTypeString(Elts[0]->getType()));
2297198090Srdivacky
2298198090Srdivacky    ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2299198090Srdivacky
2300193323Sed    // Verify all elements are correct type!
2301193323Sed    for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2302193323Sed      if (Elts[i]->getType() != Elts[0]->getType())
2303193323Sed        return Error(FirstEltLoc,
2304218893Sdim                     "array element #" + Twine(i) +
2305224145Sdim                     " is not of type '" + getTypeString(Elts[0]->getType()));
2306193323Sed    }
2307198090Srdivacky
2308224145Sdim    ID.ConstantVal = ConstantArray::get(ATy, Elts);
2309193323Sed    ID.Kind = ValID::t_Constant;
2310193323Sed    return false;
2311193323Sed  }
2312193323Sed  case lltok::kw_c:  // c "foo"
2313193323Sed    Lex.Lex();
2314234353Sdim    ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2315234353Sdim                                                  false);
2316193323Sed    if (ParseToken(lltok::StringConstant, "expected string")) return true;
2317193323Sed    ID.Kind = ValID::t_Constant;
2318193323Sed    return false;
2319193323Sed
2320193323Sed  case lltok::kw_asm: {
2321249423Sdim    // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2322249423Sdim    //             STRINGCONSTANT
2323243830Sdim    bool HasSideEffect, AlignStack, AsmDialect;
2324193323Sed    Lex.Lex();
2325193323Sed    if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2326198396Srdivacky        ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2327243830Sdim        ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2328193323Sed        ParseStringConstant(ID.StrVal) ||
2329193323Sed        ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2330193323Sed        ParseToken(lltok::StringConstant, "expected constraint string"))
2331193323Sed      return true;
2332193323Sed    ID.StrVal2 = Lex.getStrVal();
2333243830Sdim    ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2334243830Sdim      (unsigned(AsmDialect)<<2);
2335193323Sed    ID.Kind = ValID::t_InlineAsm;
2336193323Sed    return false;
2337193323Sed  }
2338198090Srdivacky
2339198892Srdivacky  case lltok::kw_blockaddress: {
2340198892Srdivacky    // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2341198892Srdivacky    Lex.Lex();
2342198892Srdivacky
2343198892Srdivacky    ValID Fn, Label;
2344198892Srdivacky    LocTy FnLoc, LabelLoc;
2345249423Sdim
2346198892Srdivacky    if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2347198892Srdivacky        ParseValID(Fn) ||
2348198892Srdivacky        ParseToken(lltok::comma, "expected comma in block address expression")||
2349198892Srdivacky        ParseValID(Label) ||
2350198892Srdivacky        ParseToken(lltok::rparen, "expected ')' in block address expression"))
2351198892Srdivacky      return true;
2352249423Sdim
2353198892Srdivacky    if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2354198892Srdivacky      return Error(Fn.Loc, "expected function name in blockaddress");
2355198892Srdivacky    if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2356198892Srdivacky      return Error(Label.Loc, "expected basic block name in blockaddress");
2357249423Sdim
2358198892Srdivacky    // Make a global variable as a placeholder for this reference.
2359198892Srdivacky    GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2360198892Srdivacky                                           false, GlobalValue::InternalLinkage,
2361198892Srdivacky                                                0, "");
2362198892Srdivacky    ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2363198892Srdivacky    ID.ConstantVal = FwdRef;
2364198892Srdivacky    ID.Kind = ValID::t_Constant;
2365198892Srdivacky    return false;
2366198892Srdivacky  }
2367249423Sdim
2368193323Sed  case lltok::kw_trunc:
2369193323Sed  case lltok::kw_zext:
2370193323Sed  case lltok::kw_sext:
2371193323Sed  case lltok::kw_fptrunc:
2372193323Sed  case lltok::kw_fpext:
2373193323Sed  case lltok::kw_bitcast:
2374193323Sed  case lltok::kw_uitofp:
2375193323Sed  case lltok::kw_sitofp:
2376193323Sed  case lltok::kw_fptoui:
2377198090Srdivacky  case lltok::kw_fptosi:
2378193323Sed  case lltok::kw_inttoptr:
2379198090Srdivacky  case lltok::kw_ptrtoint: {
2380193323Sed    unsigned Opc = Lex.getUIntVal();
2381224145Sdim    Type *DestTy = 0;
2382193323Sed    Constant *SrcVal;
2383193323Sed    Lex.Lex();
2384193323Sed    if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2385193323Sed        ParseGlobalTypeAndValue(SrcVal) ||
2386194612Sed        ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2387193323Sed        ParseType(DestTy) ||
2388193323Sed        ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2389193323Sed      return true;
2390193323Sed    if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2391193323Sed      return Error(ID.Loc, "invalid cast opcode for cast from '" +
2392224145Sdim                   getTypeString(SrcVal->getType()) + "' to '" +
2393224145Sdim                   getTypeString(DestTy) + "'");
2394198090Srdivacky    ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2395195340Sed                                                 SrcVal, DestTy);
2396193323Sed    ID.Kind = ValID::t_Constant;
2397193323Sed    return false;
2398193323Sed  }
2399193323Sed  case lltok::kw_extractvalue: {
2400193323Sed    Lex.Lex();
2401193323Sed    Constant *Val;
2402193323Sed    SmallVector<unsigned, 4> Indices;
2403193323Sed    if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2404193323Sed        ParseGlobalTypeAndValue(Val) ||
2405193323Sed        ParseIndexList(Indices) ||
2406193323Sed        ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2407193323Sed      return true;
2408198892Srdivacky
2409203954Srdivacky    if (!Val->getType()->isAggregateType())
2410203954Srdivacky      return Error(ID.Loc, "extractvalue operand must be aggregate type");
2411224145Sdim    if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2412193323Sed      return Error(ID.Loc, "invalid indices for extractvalue");
2413224145Sdim    ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2414193323Sed    ID.Kind = ValID::t_Constant;
2415193323Sed    return false;
2416193323Sed  }
2417193323Sed  case lltok::kw_insertvalue: {
2418193323Sed    Lex.Lex();
2419193323Sed    Constant *Val0, *Val1;
2420193323Sed    SmallVector<unsigned, 4> Indices;
2421193323Sed    if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2422193323Sed        ParseGlobalTypeAndValue(Val0) ||
2423193323Sed        ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2424193323Sed        ParseGlobalTypeAndValue(Val1) ||
2425193323Sed        ParseIndexList(Indices) ||
2426193323Sed        ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2427193323Sed      return true;
2428203954Srdivacky    if (!Val0->getType()->isAggregateType())
2429203954Srdivacky      return Error(ID.Loc, "insertvalue operand must be aggregate type");
2430224145Sdim    if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2431193323Sed      return Error(ID.Loc, "invalid indices for insertvalue");
2432224145Sdim    ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2433193323Sed    ID.Kind = ValID::t_Constant;
2434193323Sed    return false;
2435193323Sed  }
2436193323Sed  case lltok::kw_icmp:
2437198090Srdivacky  case lltok::kw_fcmp: {
2438193323Sed    unsigned PredVal, Opc = Lex.getUIntVal();
2439193323Sed    Constant *Val0, *Val1;
2440193323Sed    Lex.Lex();
2441193323Sed    if (ParseCmpPredicate(PredVal, Opc) ||
2442193323Sed        ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2443193323Sed        ParseGlobalTypeAndValue(Val0) ||
2444193323Sed        ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2445193323Sed        ParseGlobalTypeAndValue(Val1) ||
2446193323Sed        ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2447193323Sed      return true;
2448198090Srdivacky
2449193323Sed    if (Val0->getType() != Val1->getType())
2450193323Sed      return Error(ID.Loc, "compare operands must have the same type");
2451198090Srdivacky
2452193323Sed    CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2453198090Srdivacky
2454193323Sed    if (Opc == Instruction::FCmp) {
2455203954Srdivacky      if (!Val0->getType()->isFPOrFPVectorTy())
2456193323Sed        return Error(ID.Loc, "fcmp requires floating point operands");
2457198090Srdivacky      ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2458198090Srdivacky    } else {
2459198090Srdivacky      assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2460203954Srdivacky      if (!Val0->getType()->isIntOrIntVectorTy() &&
2461234353Sdim          !Val0->getType()->getScalarType()->isPointerTy())
2462193323Sed        return Error(ID.Loc, "icmp requires pointer or integer operands");
2463198090Srdivacky      ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2464193323Sed    }
2465193323Sed    ID.Kind = ValID::t_Constant;
2466193323Sed    return false;
2467193323Sed  }
2468198090Srdivacky
2469193323Sed  // Binary Operators.
2470193323Sed  case lltok::kw_add:
2471193574Sed  case lltok::kw_fadd:
2472193323Sed  case lltok::kw_sub:
2473193574Sed  case lltok::kw_fsub:
2474193323Sed  case lltok::kw_mul:
2475193574Sed  case lltok::kw_fmul:
2476193323Sed  case lltok::kw_udiv:
2477193323Sed  case lltok::kw_sdiv:
2478193323Sed  case lltok::kw_fdiv:
2479193323Sed  case lltok::kw_urem:
2480193323Sed  case lltok::kw_srem:
2481218893Sdim  case lltok::kw_frem:
2482218893Sdim  case lltok::kw_shl:
2483218893Sdim  case lltok::kw_lshr:
2484218893Sdim  case lltok::kw_ashr: {
2485198090Srdivacky    bool NUW = false;
2486198090Srdivacky    bool NSW = false;
2487198090Srdivacky    bool Exact = false;
2488193323Sed    unsigned Opc = Lex.getUIntVal();
2489193323Sed    Constant *Val0, *Val1;
2490193323Sed    Lex.Lex();
2491198090Srdivacky    LocTy ModifierLoc = Lex.getLoc();
2492218893Sdim    if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2493218893Sdim        Opc == Instruction::Mul || Opc == Instruction::Shl) {
2494198090Srdivacky      if (EatIfPresent(lltok::kw_nuw))
2495198090Srdivacky        NUW = true;
2496198090Srdivacky      if (EatIfPresent(lltok::kw_nsw)) {
2497198090Srdivacky        NSW = true;
2498198090Srdivacky        if (EatIfPresent(lltok::kw_nuw))
2499198090Srdivacky          NUW = true;
2500198090Srdivacky      }
2501218893Sdim    } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2502218893Sdim               Opc == Instruction::LShr || Opc == Instruction::AShr) {
2503198090Srdivacky      if (EatIfPresent(lltok::kw_exact))
2504198090Srdivacky        Exact = true;
2505198090Srdivacky    }
2506193323Sed    if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2507193323Sed        ParseGlobalTypeAndValue(Val0) ||
2508193323Sed        ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2509193323Sed        ParseGlobalTypeAndValue(Val1) ||
2510193323Sed        ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2511193323Sed      return true;
2512193323Sed    if (Val0->getType() != Val1->getType())
2513193323Sed      return Error(ID.Loc, "operands of constexpr must have same type");
2514203954Srdivacky    if (!Val0->getType()->isIntOrIntVectorTy()) {
2515198090Srdivacky      if (NUW)
2516198090Srdivacky        return Error(ModifierLoc, "nuw only applies to integer operations");
2517198090Srdivacky      if (NSW)
2518198090Srdivacky        return Error(ModifierLoc, "nsw only applies to integer operations");
2519198090Srdivacky    }
2520207618Srdivacky    // Check that the type is valid for the operator.
2521207618Srdivacky    switch (Opc) {
2522207618Srdivacky    case Instruction::Add:
2523207618Srdivacky    case Instruction::Sub:
2524207618Srdivacky    case Instruction::Mul:
2525207618Srdivacky    case Instruction::UDiv:
2526207618Srdivacky    case Instruction::SDiv:
2527207618Srdivacky    case Instruction::URem:
2528207618Srdivacky    case Instruction::SRem:
2529218893Sdim    case Instruction::Shl:
2530218893Sdim    case Instruction::AShr:
2531218893Sdim    case Instruction::LShr:
2532207618Srdivacky      if (!Val0->getType()->isIntOrIntVectorTy())
2533207618Srdivacky        return Error(ID.Loc, "constexpr requires integer operands");
2534207618Srdivacky      break;
2535207618Srdivacky    case Instruction::FAdd:
2536207618Srdivacky    case Instruction::FSub:
2537207618Srdivacky    case Instruction::FMul:
2538207618Srdivacky    case Instruction::FDiv:
2539207618Srdivacky    case Instruction::FRem:
2540207618Srdivacky      if (!Val0->getType()->isFPOrFPVectorTy())
2541207618Srdivacky        return Error(ID.Loc, "constexpr requires fp operands");
2542207618Srdivacky      break;
2543207618Srdivacky    default: llvm_unreachable("Unknown binary operator!");
2544207618Srdivacky    }
2545198090Srdivacky    unsigned Flags = 0;
2546198090Srdivacky    if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2547198090Srdivacky    if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2548218893Sdim    if (Exact) Flags |= PossiblyExactOperator::IsExact;
2549198090Srdivacky    Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2550198090Srdivacky    ID.ConstantVal = C;
2551193323Sed    ID.Kind = ValID::t_Constant;
2552193323Sed    return false;
2553193323Sed  }
2554198090Srdivacky
2555193323Sed  // Logical Operations
2556193323Sed  case lltok::kw_and:
2557193323Sed  case lltok::kw_or:
2558193323Sed  case lltok::kw_xor: {
2559193323Sed    unsigned Opc = Lex.getUIntVal();
2560193323Sed    Constant *Val0, *Val1;
2561193323Sed    Lex.Lex();
2562193323Sed    if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2563193323Sed        ParseGlobalTypeAndValue(Val0) ||
2564193323Sed        ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2565193323Sed        ParseGlobalTypeAndValue(Val1) ||
2566193323Sed        ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2567193323Sed      return true;
2568193323Sed    if (Val0->getType() != Val1->getType())
2569193323Sed      return Error(ID.Loc, "operands of constexpr must have same type");
2570203954Srdivacky    if (!Val0->getType()->isIntOrIntVectorTy())
2571193323Sed      return Error(ID.Loc,
2572193323Sed                   "constexpr requires integer or integer vector operands");
2573198090Srdivacky    ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2574193323Sed    ID.Kind = ValID::t_Constant;
2575193323Sed    return false;
2576198090Srdivacky  }
2577198090Srdivacky
2578193323Sed  case lltok::kw_getelementptr:
2579193323Sed  case lltok::kw_shufflevector:
2580193323Sed  case lltok::kw_insertelement:
2581193323Sed  case lltok::kw_extractelement:
2582193323Sed  case lltok::kw_select: {
2583193323Sed    unsigned Opc = Lex.getUIntVal();
2584193323Sed    SmallVector<Constant*, 16> Elts;
2585198090Srdivacky    bool InBounds = false;
2586193323Sed    Lex.Lex();
2587198090Srdivacky    if (Opc == Instruction::GetElementPtr)
2588198090Srdivacky      InBounds = EatIfPresent(lltok::kw_inbounds);
2589193323Sed    if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2590193323Sed        ParseGlobalValueVector(Elts) ||
2591193323Sed        ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2592193323Sed      return true;
2593198090Srdivacky
2594193323Sed    if (Opc == Instruction::GetElementPtr) {
2595234353Sdim      if (Elts.size() == 0 ||
2596234353Sdim          !Elts[0]->getType()->getScalarType()->isPointerTy())
2597193323Sed        return Error(ID.Loc, "getelementptr requires pointer operand");
2598198090Srdivacky
2599226633Sdim      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2600226633Sdim      if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2601193323Sed        return Error(ID.Loc, "invalid indices for getelementptr");
2602226633Sdim      ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2603226633Sdim                                                      InBounds);
2604193323Sed    } else if (Opc == Instruction::Select) {
2605193323Sed      if (Elts.size() != 3)
2606193323Sed        return Error(ID.Loc, "expected three operands to select");
2607193323Sed      if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2608193323Sed                                                              Elts[2]))
2609193323Sed        return Error(ID.Loc, Reason);
2610198090Srdivacky      ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2611193323Sed    } else if (Opc == Instruction::ShuffleVector) {
2612193323Sed      if (Elts.size() != 3)
2613193323Sed        return Error(ID.Loc, "expected three operands to shufflevector");
2614193323Sed      if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2615193323Sed        return Error(ID.Loc, "invalid operands to shufflevector");
2616195340Sed      ID.ConstantVal =
2617198090Srdivacky                 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2618193323Sed    } else if (Opc == Instruction::ExtractElement) {
2619193323Sed      if (Elts.size() != 2)
2620193323Sed        return Error(ID.Loc, "expected two operands to extractelement");
2621193323Sed      if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2622193323Sed        return Error(ID.Loc, "invalid extractelement operands");
2623198090Srdivacky      ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2624193323Sed    } else {
2625193323Sed      assert(Opc == Instruction::InsertElement && "Unknown opcode");
2626193323Sed      if (Elts.size() != 3)
2627193323Sed      return Error(ID.Loc, "expected three operands to insertelement");
2628193323Sed      if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2629193323Sed        return Error(ID.Loc, "invalid insertelement operands");
2630195340Sed      ID.ConstantVal =
2631198090Srdivacky                 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2632193323Sed    }
2633198090Srdivacky
2634193323Sed    ID.Kind = ValID::t_Constant;
2635193323Sed    return false;
2636193323Sed  }
2637193323Sed  }
2638198090Srdivacky
2639193323Sed  Lex.Lex();
2640193323Sed  return false;
2641193323Sed}
2642193323Sed
2643193323Sed/// ParseGlobalValue - Parse a global value with the specified type.
2644226633Sdimbool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2645202375Srdivacky  C = 0;
2646193323Sed  ValID ID;
2647202375Srdivacky  Value *V = NULL;
2648202375Srdivacky  bool Parsed = ParseValID(ID) ||
2649202375Srdivacky                ConvertValIDToValue(Ty, ID, V, NULL);
2650202375Srdivacky  if (V && !(C = dyn_cast<Constant>(V)))
2651202375Srdivacky    return Error(ID.Loc, "global values must be constants");
2652202375Srdivacky  return Parsed;
2653193323Sed}
2654193323Sed
2655202375Srdivackybool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2656224145Sdim  Type *Ty = 0;
2657224145Sdim  return ParseType(Ty) ||
2658224145Sdim         ParseGlobalValue(Ty, V);
2659202375Srdivacky}
2660202375Srdivacky
2661202375Srdivacky/// ParseGlobalValueVector
2662202375Srdivacky///   ::= /*empty*/
2663202375Srdivacky///   ::= TypeAndValue (',' TypeAndValue)*
2664202375Srdivackybool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2665202375Srdivacky  // Empty list.
2666202375Srdivacky  if (Lex.getKind() == lltok::rbrace ||
2667202375Srdivacky      Lex.getKind() == lltok::rsquare ||
2668202375Srdivacky      Lex.getKind() == lltok::greater ||
2669202375Srdivacky      Lex.getKind() == lltok::rparen)
2670202375Srdivacky    return false;
2671202375Srdivacky
2672202375Srdivacky  Constant *C;
2673202375Srdivacky  if (ParseGlobalTypeAndValue(C)) return true;
2674202375Srdivacky  Elts.push_back(C);
2675202375Srdivacky
2676202375Srdivacky  while (EatIfPresent(lltok::comma)) {
2677202375Srdivacky    if (ParseGlobalTypeAndValue(C)) return true;
2678202375Srdivacky    Elts.push_back(C);
2679202375Srdivacky  }
2680202375Srdivacky
2681202375Srdivacky  return false;
2682202375Srdivacky}
2683202375Srdivacky
2684212904Sdimbool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2685212904Sdim  assert(Lex.getKind() == lltok::lbrace);
2686212904Sdim  Lex.Lex();
2687212904Sdim
2688212904Sdim  SmallVector<Value*, 16> Elts;
2689212904Sdim  if (ParseMDNodeVector(Elts, PFS) ||
2690212904Sdim      ParseToken(lltok::rbrace, "expected end of metadata node"))
2691212904Sdim    return true;
2692212904Sdim
2693221345Sdim  ID.MDNodeVal = MDNode::get(Context, Elts);
2694212904Sdim  ID.Kind = ValID::t_MDNode;
2695212904Sdim  return false;
2696212904Sdim}
2697212904Sdim
2698210299Sed/// ParseMetadataValue
2699210299Sed///  ::= !42
2700210299Sed///  ::= !{...}
2701210299Sed///  ::= !"string"
2702210299Sedbool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2703210299Sed  assert(Lex.getKind() == lltok::exclaim);
2704210299Sed  Lex.Lex();
2705202375Srdivacky
2706210299Sed  // MDNode:
2707210299Sed  // !{ ... }
2708212904Sdim  if (Lex.getKind() == lltok::lbrace)
2709212904Sdim    return ParseMetadataListValue(ID, PFS);
2710210299Sed
2711210299Sed  // Standalone metadata reference
2712210299Sed  // !42
2713210299Sed  if (Lex.getKind() == lltok::APSInt) {
2714210299Sed    if (ParseMDNodeID(ID.MDNodeVal)) return true;
2715210299Sed    ID.Kind = ValID::t_MDNode;
2716210299Sed    return false;
2717210299Sed  }
2718210299Sed
2719210299Sed  // MDString:
2720210299Sed  //   ::= '!' STRINGCONSTANT
2721210299Sed  if (ParseMDString(ID.MDStringVal)) return true;
2722210299Sed  ID.Kind = ValID::t_MDString;
2723210299Sed  return false;
2724210299Sed}
2725210299Sed
2726210299Sed
2727202375Srdivacky//===----------------------------------------------------------------------===//
2728202375Srdivacky// Function Parsing.
2729202375Srdivacky//===----------------------------------------------------------------------===//
2730202375Srdivacky
2731226633Sdimbool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2732202375Srdivacky                                   PerFunctionState *PFS) {
2733204642Srdivacky  if (Ty->isFunctionTy())
2734193323Sed    return Error(ID.Loc, "functions are not values, refer to them as pointers");
2735198090Srdivacky
2736193323Sed  switch (ID.Kind) {
2737202375Srdivacky  case ValID::t_LocalID:
2738202375Srdivacky    if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2739202375Srdivacky    V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2740202375Srdivacky    return (V == 0);
2741202375Srdivacky  case ValID::t_LocalName:
2742202375Srdivacky    if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2743202375Srdivacky    V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2744202375Srdivacky    return (V == 0);
2745202375Srdivacky  case ValID::t_InlineAsm: {
2746226633Sdim    PointerType *PTy = dyn_cast<PointerType>(Ty);
2747249423Sdim    FunctionType *FTy =
2748202375Srdivacky      PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2749202375Srdivacky    if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2750202375Srdivacky      return Error(ID.Loc, "invalid type for inline asm constraint string");
2751243830Sdim    V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2752243830Sdim                       (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2753202375Srdivacky    return false;
2754202375Srdivacky  }
2755201360Srdivacky  case ValID::t_MDNode:
2756202375Srdivacky    if (!Ty->isMetadataTy())
2757202375Srdivacky      return Error(ID.Loc, "metadata value must have metadata type");
2758202375Srdivacky    V = ID.MDNodeVal;
2759202375Srdivacky    return false;
2760201360Srdivacky  case ValID::t_MDString:
2761202375Srdivacky    if (!Ty->isMetadataTy())
2762202375Srdivacky      return Error(ID.Loc, "metadata value must have metadata type");
2763202375Srdivacky    V = ID.MDStringVal;
2764202375Srdivacky    return false;
2765193323Sed  case ValID::t_GlobalName:
2766193323Sed    V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2767193323Sed    return V == 0;
2768193323Sed  case ValID::t_GlobalID:
2769193323Sed    V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2770193323Sed    return V == 0;
2771193323Sed  case ValID::t_APSInt:
2772204642Srdivacky    if (!Ty->isIntegerTy())
2773193323Sed      return Error(ID.Loc, "integer constant must have integer type");
2774218893Sdim    ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2775198090Srdivacky    V = ConstantInt::get(Context, ID.APSIntVal);
2776193323Sed    return false;
2777193323Sed  case ValID::t_APFloat:
2778203954Srdivacky    if (!Ty->isFloatingPointTy() ||
2779193323Sed        !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2780193323Sed      return Error(ID.Loc, "floating point constant invalid for type");
2781198090Srdivacky
2782234353Sdim    // The lexer has no type info, so builds all half, float, and double FP
2783234353Sdim    // constants as double.  Fix this here.  Long double does not need this.
2784234353Sdim    if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2785193323Sed      bool Ignored;
2786234353Sdim      if (Ty->isHalfTy())
2787234353Sdim        ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2788234353Sdim                              &Ignored);
2789234353Sdim      else if (Ty->isFloatTy())
2790234353Sdim        ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2791234353Sdim                              &Ignored);
2792193323Sed    }
2793198090Srdivacky    V = ConstantFP::get(Context, ID.APFloatVal);
2794198090Srdivacky
2795193323Sed    if (V->getType() != Ty)
2796193323Sed      return Error(ID.Loc, "floating point constant does not have type '" +
2797224145Sdim                   getTypeString(Ty) + "'");
2798198090Srdivacky
2799193323Sed    return false;
2800193323Sed  case ValID::t_Null:
2801204642Srdivacky    if (!Ty->isPointerTy())
2802193323Sed      return Error(ID.Loc, "null must be a pointer type");
2803198090Srdivacky    V = ConstantPointerNull::get(cast<PointerType>(Ty));
2804193323Sed    return false;
2805193323Sed  case ValID::t_Undef:
2806193323Sed    // FIXME: LabelTy should not be a first-class type.
2807224145Sdim    if (!Ty->isFirstClassType() || Ty->isLabelTy())
2808193323Sed      return Error(ID.Loc, "invalid type for undef constant");
2809198090Srdivacky    V = UndefValue::get(Ty);
2810193323Sed    return false;
2811193323Sed  case ValID::t_EmptyArray:
2812204642Srdivacky    if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2813193323Sed      return Error(ID.Loc, "invalid empty array initializer");
2814198090Srdivacky    V = UndefValue::get(Ty);
2815193323Sed    return false;
2816193323Sed  case ValID::t_Zero:
2817193323Sed    // FIXME: LabelTy should not be a first-class type.
2818198090Srdivacky    if (!Ty->isFirstClassType() || Ty->isLabelTy())
2819193323Sed      return Error(ID.Loc, "invalid type for null constant");
2820198090Srdivacky    V = Constant::getNullValue(Ty);
2821193323Sed    return false;
2822193323Sed  case ValID::t_Constant:
2823212904Sdim    if (ID.ConstantVal->getType() != Ty)
2824193323Sed      return Error(ID.Loc, "constant expression type mismatch");
2825203954Srdivacky
2826193323Sed    V = ID.ConstantVal;
2827193323Sed    return false;
2828224145Sdim  case ValID::t_ConstantStruct:
2829224145Sdim  case ValID::t_PackedConstantStruct:
2830226633Sdim    if (StructType *ST = dyn_cast<StructType>(Ty)) {
2831224145Sdim      if (ST->getNumElements() != ID.UIntVal)
2832224145Sdim        return Error(ID.Loc,
2833224145Sdim                     "initializer with struct type has wrong # elements");
2834224145Sdim      if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2835224145Sdim        return Error(ID.Loc, "packed'ness of initializer and type don't match");
2836249423Sdim
2837224145Sdim      // Verify that the elements are compatible with the structtype.
2838224145Sdim      for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2839224145Sdim        if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2840224145Sdim          return Error(ID.Loc, "element " + Twine(i) +
2841224145Sdim                    " of struct initializer doesn't match struct element type");
2842249423Sdim
2843226633Sdim      V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2844226633Sdim                                               ID.UIntVal));
2845224145Sdim    } else
2846224145Sdim      return Error(ID.Loc, "constant expression type mismatch");
2847224145Sdim    return false;
2848193323Sed  }
2849234353Sdim  llvm_unreachable("Invalid ValID");
2850193323Sed}
2851198090Srdivacky
2852226633Sdimbool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2853193323Sed  V = 0;
2854193323Sed  ValID ID;
2855224145Sdim  return ParseValID(ID, PFS) ||
2856224145Sdim         ConvertValIDToValue(Ty, ID, V, PFS);
2857193323Sed}
2858193323Sed
2859224145Sdimbool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2860224145Sdim  Type *Ty = 0;
2861224145Sdim  return ParseType(Ty) ||
2862224145Sdim         ParseValue(Ty, V, PFS);
2863193323Sed}
2864193323Sed
2865198892Srdivackybool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2866198892Srdivacky                                      PerFunctionState &PFS) {
2867198892Srdivacky  Value *V;
2868198892Srdivacky  Loc = Lex.getLoc();
2869198892Srdivacky  if (ParseTypeAndValue(V, PFS)) return true;
2870198892Srdivacky  if (!isa<BasicBlock>(V))
2871198892Srdivacky    return Error(Loc, "expected a basic block");
2872198892Srdivacky  BB = cast<BasicBlock>(V);
2873198892Srdivacky  return false;
2874198892Srdivacky}
2875198892Srdivacky
2876198892Srdivacky
2877193323Sed/// FunctionHeader
2878193323Sed///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2879218893Sdim///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2880193323Sed///       OptionalAlign OptGC
2881193323Sedbool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2882193323Sed  // Parse the linkage.
2883193323Sed  LocTy LinkageLoc = Lex.getLoc();
2884193323Sed  unsigned Linkage;
2885198090Srdivacky
2886234353Sdim  unsigned Visibility;
2887243830Sdim  AttrBuilder RetAttrs;
2888198090Srdivacky  CallingConv::ID CC;
2889224145Sdim  Type *RetType = 0;
2890193323Sed  LocTy RetTypeLoc = Lex.getLoc();
2891193323Sed  if (ParseOptionalLinkage(Linkage) ||
2892193323Sed      ParseOptionalVisibility(Visibility) ||
2893193323Sed      ParseOptionalCallingConv(CC) ||
2894249423Sdim      ParseOptionalReturnAttrs(RetAttrs) ||
2895193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2896193323Sed    return true;
2897193323Sed
2898193323Sed  // Verify that the linkage is ok.
2899193323Sed  switch ((GlobalValue::LinkageTypes)Linkage) {
2900193323Sed  case GlobalValue::ExternalLinkage:
2901193323Sed    break; // always ok.
2902193323Sed  case GlobalValue::DLLImportLinkage:
2903193323Sed  case GlobalValue::ExternalWeakLinkage:
2904193323Sed    if (isDefine)
2905193323Sed      return Error(LinkageLoc, "invalid linkage for function definition");
2906193323Sed    break;
2907193323Sed  case GlobalValue::PrivateLinkage:
2908198090Srdivacky  case GlobalValue::LinkerPrivateLinkage:
2909210299Sed  case GlobalValue::LinkerPrivateWeakLinkage:
2910193323Sed  case GlobalValue::InternalLinkage:
2911193323Sed  case GlobalValue::AvailableExternallyLinkage:
2912193323Sed  case GlobalValue::LinkOnceAnyLinkage:
2913193323Sed  case GlobalValue::LinkOnceODRLinkage:
2914243830Sdim  case GlobalValue::LinkOnceODRAutoHideLinkage:
2915193323Sed  case GlobalValue::WeakAnyLinkage:
2916193323Sed  case GlobalValue::WeakODRLinkage:
2917193323Sed  case GlobalValue::DLLExportLinkage:
2918193323Sed    if (!isDefine)
2919193323Sed      return Error(LinkageLoc, "invalid linkage for function declaration");
2920193323Sed    break;
2921193323Sed  case GlobalValue::AppendingLinkage:
2922193323Sed  case GlobalValue::CommonLinkage:
2923193323Sed    return Error(LinkageLoc, "invalid function linkage type");
2924193323Sed  }
2925198090Srdivacky
2926224145Sdim  if (!FunctionType::isValidReturnType(RetType))
2927193323Sed    return Error(RetTypeLoc, "invalid function return type");
2928198090Srdivacky
2929193323Sed  LocTy NameLoc = Lex.getLoc();
2930193323Sed
2931193323Sed  std::string FunctionName;
2932193323Sed  if (Lex.getKind() == lltok::GlobalVar) {
2933193323Sed    FunctionName = Lex.getStrVal();
2934193323Sed  } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2935193323Sed    unsigned NameID = Lex.getUIntVal();
2936193323Sed
2937193323Sed    if (NameID != NumberedVals.size())
2938193323Sed      return TokError("function expected to be numbered '%" +
2939218893Sdim                      Twine(NumberedVals.size()) + "'");
2940193323Sed  } else {
2941193323Sed    return TokError("expected function name");
2942193323Sed  }
2943198090Srdivacky
2944193323Sed  Lex.Lex();
2945198090Srdivacky
2946193323Sed  if (Lex.getKind() != lltok::lparen)
2947193323Sed    return TokError("expected '(' in function argument list");
2948198090Srdivacky
2949224145Sdim  SmallVector<ArgInfo, 8> ArgList;
2950193323Sed  bool isVarArg;
2951243830Sdim  AttrBuilder FuncAttrs;
2952249423Sdim  std::vector<unsigned> FwdRefAttrGrps;
2953249423Sdim  LocTy NoBuiltinLoc;
2954193323Sed  std::string Section;
2955193323Sed  unsigned Alignment;
2956193323Sed  std::string GC;
2957218893Sdim  bool UnnamedAddr;
2958218893Sdim  LocTy UnnamedAddrLoc;
2959193323Sed
2960224145Sdim  if (ParseArgumentList(ArgList, isVarArg) ||
2961218893Sdim      ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2962218893Sdim                         &UnnamedAddrLoc) ||
2963249423Sdim      ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
2964249423Sdim                                 NoBuiltinLoc) ||
2965193323Sed      (EatIfPresent(lltok::kw_section) &&
2966193323Sed       ParseStringConstant(Section)) ||
2967193323Sed      ParseOptionalAlignment(Alignment) ||
2968193323Sed      (EatIfPresent(lltok::kw_gc) &&
2969193323Sed       ParseStringConstant(GC)))
2970193323Sed    return true;
2971193323Sed
2972249423Sdim  if (FuncAttrs.contains(Attribute::NoBuiltin))
2973249423Sdim    return Error(NoBuiltinLoc, "'nobuiltin' attribute not valid on function");
2974249423Sdim
2975193323Sed  // If the alignment was parsed as an attribute, move to the alignment field.
2976243830Sdim  if (FuncAttrs.hasAlignmentAttr()) {
2977243830Sdim    Alignment = FuncAttrs.getAlignment();
2978249423Sdim    FuncAttrs.removeAttribute(Attribute::Alignment);
2979193323Sed  }
2980198090Srdivacky
2981193323Sed  // Okay, if we got here, the function is syntactically valid.  Convert types
2982193323Sed  // and do semantic checks.
2983224145Sdim  std::vector<Type*> ParamTypeList;
2984249423Sdim  SmallVector<AttributeSet, 8> Attrs;
2985198090Srdivacky
2986243830Sdim  if (RetAttrs.hasAttributes())
2987249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
2988249423Sdim                                      AttributeSet::ReturnIndex,
2989249423Sdim                                      RetAttrs));
2990198090Srdivacky
2991193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2992224145Sdim    ParamTypeList.push_back(ArgList[i].Ty);
2993249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1)) {
2994249423Sdim      AttrBuilder B(ArgList[i].Attrs, i + 1);
2995249423Sdim      Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
2996249423Sdim    }
2997193323Sed  }
2998193323Sed
2999243830Sdim  if (FuncAttrs.hasAttributes())
3000249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3001249423Sdim                                      AttributeSet::FunctionIndex,
3002249423Sdim                                      FuncAttrs));
3003193323Sed
3004249423Sdim  AttributeSet PAL = AttributeSet::get(Context, Attrs);
3005198090Srdivacky
3006249423Sdim  if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3007198090Srdivacky    return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3008198090Srdivacky
3009226633Sdim  FunctionType *FT =
3010198090Srdivacky    FunctionType::get(RetType, ParamTypeList, isVarArg);
3011226633Sdim  PointerType *PFT = PointerType::getUnqual(FT);
3012193323Sed
3013193323Sed  Fn = 0;
3014193323Sed  if (!FunctionName.empty()) {
3015193323Sed    // If this was a definition of a forward reference, remove the definition
3016193323Sed    // from the forward reference table and fill in the forward ref.
3017193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3018193323Sed      ForwardRefVals.find(FunctionName);
3019193323Sed    if (FRVI != ForwardRefVals.end()) {
3020193323Sed      Fn = M->getFunction(FunctionName);
3021243830Sdim      if (!Fn)
3022243830Sdim        return Error(FRVI->second.second, "invalid forward reference to "
3023243830Sdim                     "function as global value!");
3024207618Srdivacky      if (Fn->getType() != PFT)
3025207618Srdivacky        return Error(FRVI->second.second, "invalid forward reference to "
3026207618Srdivacky                     "function '" + FunctionName + "' with wrong type!");
3027249423Sdim
3028193323Sed      ForwardRefVals.erase(FRVI);
3029193323Sed    } else if ((Fn = M->getFunction(FunctionName))) {
3030224145Sdim      // Reject redefinitions.
3031224145Sdim      return Error(NameLoc, "invalid redefinition of function '" +
3032224145Sdim                   FunctionName + "'");
3033198892Srdivacky    } else if (M->getNamedValue(FunctionName)) {
3034198892Srdivacky      return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3035193323Sed    }
3036198090Srdivacky
3037198090Srdivacky  } else {
3038193323Sed    // If this is a definition of a forward referenced function, make sure the
3039193323Sed    // types agree.
3040193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3041193323Sed      = ForwardRefValIDs.find(NumberedVals.size());
3042193323Sed    if (I != ForwardRefValIDs.end()) {
3043193323Sed      Fn = cast<Function>(I->second.first);
3044193323Sed      if (Fn->getType() != PFT)
3045193323Sed        return Error(NameLoc, "type of definition and forward reference of '@" +
3046218893Sdim                     Twine(NumberedVals.size()) + "' disagree");
3047193323Sed      ForwardRefValIDs.erase(I);
3048193323Sed    }
3049193323Sed  }
3050193323Sed
3051193323Sed  if (Fn == 0)
3052193323Sed    Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3053193323Sed  else // Move the forward-reference to the correct spot in the module.
3054193323Sed    M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3055193323Sed
3056193323Sed  if (FunctionName.empty())
3057193323Sed    NumberedVals.push_back(Fn);
3058198090Srdivacky
3059193323Sed  Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3060193323Sed  Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3061193323Sed  Fn->setCallingConv(CC);
3062193323Sed  Fn->setAttributes(PAL);
3063218893Sdim  Fn->setUnnamedAddr(UnnamedAddr);
3064193323Sed  Fn->setAlignment(Alignment);
3065193323Sed  Fn->setSection(Section);
3066193323Sed  if (!GC.empty()) Fn->setGC(GC.c_str());
3067249423Sdim  ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3068198090Srdivacky
3069193323Sed  // Add all of the arguments we parsed to the function.
3070193323Sed  Function::arg_iterator ArgIt = Fn->arg_begin();
3071193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3072193323Sed    // If the argument has a name, insert it into the argument symbol table.
3073193323Sed    if (ArgList[i].Name.empty()) continue;
3074198090Srdivacky
3075193323Sed    // Set the name, if it conflicted, it will be auto-renamed.
3076193323Sed    ArgIt->setName(ArgList[i].Name);
3077198090Srdivacky
3078218893Sdim    if (ArgIt->getName() != ArgList[i].Name)
3079193323Sed      return Error(ArgList[i].Loc, "redefinition of argument '%" +
3080193323Sed                   ArgList[i].Name + "'");
3081193323Sed  }
3082198090Srdivacky
3083193323Sed  return false;
3084193323Sed}
3085193323Sed
3086193323Sed
3087193323Sed/// ParseFunctionBody
3088193323Sed///   ::= '{' BasicBlock+ '}'
3089193323Sed///
3090193323Sedbool LLParser::ParseFunctionBody(Function &Fn) {
3091224145Sdim  if (Lex.getKind() != lltok::lbrace)
3092193323Sed    return TokError("expected '{' in function body");
3093193323Sed  Lex.Lex();  // eat the {.
3094198090Srdivacky
3095198892Srdivacky  int FunctionNumber = -1;
3096198892Srdivacky  if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3097249423Sdim
3098198892Srdivacky  PerFunctionState PFS(*this, Fn, FunctionNumber);
3099198090Srdivacky
3100202375Srdivacky  // We need at least one basic block.
3101224145Sdim  if (Lex.getKind() == lltok::rbrace)
3102202375Srdivacky    return TokError("function body requires at least one basic block");
3103249423Sdim
3104224145Sdim  while (Lex.getKind() != lltok::rbrace)
3105193323Sed    if (ParseBasicBlock(PFS)) return true;
3106198090Srdivacky
3107193323Sed  // Eat the }.
3108193323Sed  Lex.Lex();
3109198090Srdivacky
3110193323Sed  // Verify function is ok.
3111198892Srdivacky  return PFS.FinishFunction();
3112193323Sed}
3113193323Sed
3114193323Sed/// ParseBasicBlock
3115193323Sed///   ::= LabelStr? Instruction*
3116193323Sedbool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3117193323Sed  // If this basic block starts out with a name, remember it.
3118193323Sed  std::string Name;
3119193323Sed  LocTy NameLoc = Lex.getLoc();
3120193323Sed  if (Lex.getKind() == lltok::LabelStr) {
3121193323Sed    Name = Lex.getStrVal();
3122193323Sed    Lex.Lex();
3123193323Sed  }
3124198090Srdivacky
3125193323Sed  BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3126193323Sed  if (BB == 0) return true;
3127198090Srdivacky
3128193323Sed  std::string NameStr;
3129198090Srdivacky
3130193323Sed  // Parse the instructions in this block until we get a terminator.
3131193323Sed  Instruction *Inst;
3132201360Srdivacky  SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
3133193323Sed  do {
3134193323Sed    // This instruction may have three possibilities for a name: a) none
3135193323Sed    // specified, b) name specified "%foo =", c) number specified: "%4 =".
3136193323Sed    LocTy NameLoc = Lex.getLoc();
3137193323Sed    int NameID = -1;
3138193323Sed    NameStr = "";
3139198090Srdivacky
3140193323Sed    if (Lex.getKind() == lltok::LocalVarID) {
3141193323Sed      NameID = Lex.getUIntVal();
3142193323Sed      Lex.Lex();
3143193323Sed      if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3144193323Sed        return true;
3145224145Sdim    } else if (Lex.getKind() == lltok::LocalVar) {
3146193323Sed      NameStr = Lex.getStrVal();
3147193323Sed      Lex.Lex();
3148193323Sed      if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3149193323Sed        return true;
3150193323Sed    }
3151198090Srdivacky
3152201360Srdivacky    switch (ParseInstruction(Inst, BB, PFS)) {
3153234353Sdim    default: llvm_unreachable("Unknown ParseInstruction result!");
3154201360Srdivacky    case InstError: return true;
3155201360Srdivacky    case InstNormal:
3156207618Srdivacky      BB->getInstList().push_back(Inst);
3157207618Srdivacky
3158201360Srdivacky      // With a normal result, we check to see if the instruction is followed by
3159201360Srdivacky      // a comma and metadata.
3160201360Srdivacky      if (EatIfPresent(lltok::comma))
3161212904Sdim        if (ParseInstructionMetadata(Inst, &PFS))
3162201360Srdivacky          return true;
3163201360Srdivacky      break;
3164201360Srdivacky    case InstExtraComma:
3165207618Srdivacky      BB->getInstList().push_back(Inst);
3166207618Srdivacky
3167201360Srdivacky      // If the instruction parser ate an extra comma at the end of it, it
3168201360Srdivacky      // *must* be followed by metadata.
3169212904Sdim      if (ParseInstructionMetadata(Inst, &PFS))
3170201360Srdivacky        return true;
3171249423Sdim      break;
3172201360Srdivacky    }
3173198090Srdivacky
3174193323Sed    // Set the name on the instruction.
3175193323Sed    if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3176193323Sed  } while (!isa<TerminatorInst>(Inst));
3177198090Srdivacky
3178193323Sed  return false;
3179193323Sed}
3180193323Sed
3181193323Sed//===----------------------------------------------------------------------===//
3182193323Sed// Instruction Parsing.
3183193323Sed//===----------------------------------------------------------------------===//
3184193323Sed
3185193323Sed/// ParseInstruction - Parse one of the many different instructions.
3186193323Sed///
3187201360Srdivackyint LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3188201360Srdivacky                               PerFunctionState &PFS) {
3189193323Sed  lltok::Kind Token = Lex.getKind();
3190193323Sed  if (Token == lltok::Eof)
3191193323Sed    return TokError("found end of file when expecting more instructions");
3192193323Sed  LocTy Loc = Lex.getLoc();
3193193323Sed  unsigned KeywordVal = Lex.getUIntVal();
3194193323Sed  Lex.Lex();  // Eat the keyword.
3195198090Srdivacky
3196193323Sed  switch (Token) {
3197193323Sed  default:                    return Error(Loc, "expected instruction opcode");
3198193323Sed  // Terminator Instructions.
3199198090Srdivacky  case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3200193323Sed  case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
3201193323Sed  case lltok::kw_br:          return ParseBr(Inst, PFS);
3202193323Sed  case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
3203198892Srdivacky  case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
3204193323Sed  case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
3205226633Sdim  case lltok::kw_resume:      return ParseResume(Inst, PFS);
3206193323Sed  // Binary Operators.
3207193323Sed  case lltok::kw_add:
3208193323Sed  case lltok::kw_sub:
3209218893Sdim  case lltok::kw_mul:
3210218893Sdim  case lltok::kw_shl: {
3211218893Sdim    bool NUW = EatIfPresent(lltok::kw_nuw);
3212218893Sdim    bool NSW = EatIfPresent(lltok::kw_nsw);
3213218893Sdim    if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3214249423Sdim
3215218893Sdim    if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3216249423Sdim
3217218893Sdim    if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3218218893Sdim    if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3219218893Sdim    return false;
3220198090Srdivacky  }
3221193574Sed  case lltok::kw_fadd:
3222193574Sed  case lltok::kw_fsub:
3223249423Sdim  case lltok::kw_fmul:
3224249423Sdim  case lltok::kw_fdiv:
3225249423Sdim  case lltok::kw_frem: {
3226249423Sdim    FastMathFlags FMF = EatFastMathFlagsIfPresent();
3227249423Sdim    int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3228249423Sdim    if (Res != 0)
3229249423Sdim      return Res;
3230249423Sdim    if (FMF.any())
3231249423Sdim      Inst->setFastMathFlags(FMF);
3232249423Sdim    return 0;
3233249423Sdim  }
3234193574Sed
3235218893Sdim  case lltok::kw_sdiv:
3236218893Sdim  case lltok::kw_udiv:
3237218893Sdim  case lltok::kw_lshr:
3238218893Sdim  case lltok::kw_ashr: {
3239218893Sdim    bool Exact = EatIfPresent(lltok::kw_exact);
3240218893Sdim
3241218893Sdim    if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3242218893Sdim    if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3243218893Sdim    return false;
3244198090Srdivacky  }
3245198090Srdivacky
3246193323Sed  case lltok::kw_urem:
3247193323Sed  case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3248193323Sed  case lltok::kw_and:
3249193323Sed  case lltok::kw_or:
3250193323Sed  case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
3251193323Sed  case lltok::kw_icmp:
3252198090Srdivacky  case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
3253193323Sed  // Casts.
3254193323Sed  case lltok::kw_trunc:
3255193323Sed  case lltok::kw_zext:
3256193323Sed  case lltok::kw_sext:
3257193323Sed  case lltok::kw_fptrunc:
3258193323Sed  case lltok::kw_fpext:
3259193323Sed  case lltok::kw_bitcast:
3260193323Sed  case lltok::kw_uitofp:
3261193323Sed  case lltok::kw_sitofp:
3262193323Sed  case lltok::kw_fptoui:
3263198090Srdivacky  case lltok::kw_fptosi:
3264193323Sed  case lltok::kw_inttoptr:
3265193323Sed  case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
3266193323Sed  // Other.
3267193323Sed  case lltok::kw_select:         return ParseSelect(Inst, PFS);
3268193323Sed  case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
3269193323Sed  case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3270193323Sed  case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
3271193323Sed  case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
3272193323Sed  case lltok::kw_phi:            return ParsePHI(Inst, PFS);
3273226633Sdim  case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
3274193323Sed  case lltok::kw_call:           return ParseCall(Inst, PFS, false);
3275193323Sed  case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
3276193323Sed  // Memory.
3277198396Srdivacky  case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
3278234353Sdim  case lltok::kw_load:           return ParseLoad(Inst, PFS);
3279234353Sdim  case lltok::kw_store:          return ParseStore(Inst, PFS);
3280226633Sdim  case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
3281226633Sdim  case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
3282226633Sdim  case lltok::kw_fence:          return ParseFence(Inst, PFS);
3283193323Sed  case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3284193323Sed  case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
3285193323Sed  case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
3286193323Sed  }
3287193323Sed}
3288193323Sed
3289193323Sed/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3290193323Sedbool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3291198090Srdivacky  if (Opc == Instruction::FCmp) {
3292193323Sed    switch (Lex.getKind()) {
3293249423Sdim    default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3294193323Sed    case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3295193323Sed    case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3296193323Sed    case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3297193323Sed    case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3298193323Sed    case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3299193323Sed    case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3300193323Sed    case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3301193323Sed    case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3302193323Sed    case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3303193323Sed    case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3304193323Sed    case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3305193323Sed    case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3306193323Sed    case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3307193323Sed    case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3308193323Sed    case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3309193323Sed    case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3310193323Sed    }
3311193323Sed  } else {
3312193323Sed    switch (Lex.getKind()) {
3313249423Sdim    default: return TokError("expected icmp predicate (e.g. 'eq')");
3314193323Sed    case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
3315193323Sed    case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
3316193323Sed    case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3317193323Sed    case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3318193323Sed    case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3319193323Sed    case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3320193323Sed    case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3321193323Sed    case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3322193323Sed    case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3323193323Sed    case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3324193323Sed    }
3325193323Sed  }
3326193323Sed  Lex.Lex();
3327193323Sed  return false;
3328193323Sed}
3329193323Sed
3330193323Sed//===----------------------------------------------------------------------===//
3331193323Sed// Terminator Instructions.
3332193323Sed//===----------------------------------------------------------------------===//
3333193323Sed
3334193323Sed/// ParseRet - Parse a return instruction.
3335201360Srdivacky///   ::= 'ret' void (',' !dbg, !1)*
3336201360Srdivacky///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
3337224145Sdimbool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3338224145Sdim                        PerFunctionState &PFS) {
3339224145Sdim  SMLoc TypeLoc = Lex.getLoc();
3340224145Sdim  Type *Ty = 0;
3341193323Sed  if (ParseType(Ty, true /*void allowed*/)) return true;
3342198090Srdivacky
3343224145Sdim  Type *ResType = PFS.getFunction().getReturnType();
3344249423Sdim
3345198090Srdivacky  if (Ty->isVoidTy()) {
3346224145Sdim    if (!ResType->isVoidTy())
3347224145Sdim      return Error(TypeLoc, "value doesn't match function result type '" +
3348224145Sdim                   getTypeString(ResType) + "'");
3349249423Sdim
3350198090Srdivacky    Inst = ReturnInst::Create(Context);
3351193323Sed    return false;
3352193323Sed  }
3353198090Srdivacky
3354193323Sed  Value *RV;
3355193323Sed  if (ParseValue(Ty, RV, PFS)) return true;
3356198090Srdivacky
3357224145Sdim  if (ResType != RV->getType())
3358224145Sdim    return Error(TypeLoc, "value doesn't match function result type '" +
3359224145Sdim                 getTypeString(ResType) + "'");
3360249423Sdim
3361198090Srdivacky  Inst = ReturnInst::Create(Context, RV);
3362224145Sdim  return false;
3363193323Sed}
3364193323Sed
3365193323Sed
3366193323Sed/// ParseBr
3367193323Sed///   ::= 'br' TypeAndValue
3368193323Sed///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3369193323Sedbool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3370193323Sed  LocTy Loc, Loc2;
3371198892Srdivacky  Value *Op0;
3372198892Srdivacky  BasicBlock *Op1, *Op2;
3373193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3374198090Srdivacky
3375193323Sed  if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3376193323Sed    Inst = BranchInst::Create(BB);
3377193323Sed    return false;
3378193323Sed  }
3379198090Srdivacky
3380198090Srdivacky  if (Op0->getType() != Type::getInt1Ty(Context))
3381193323Sed    return Error(Loc, "branch condition must have 'i1' type");
3382198090Srdivacky
3383193323Sed  if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3384198892Srdivacky      ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3385193323Sed      ParseToken(lltok::comma, "expected ',' after true destination") ||
3386198892Srdivacky      ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3387193323Sed    return true;
3388198090Srdivacky
3389198892Srdivacky  Inst = BranchInst::Create(Op1, Op2, Op0);
3390193323Sed  return false;
3391193323Sed}
3392193323Sed
3393193323Sed/// ParseSwitch
3394193323Sed///  Instruction
3395193323Sed///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3396193323Sed///  JumpTable
3397193323Sed///    ::= (TypeAndValue ',' TypeAndValue)*
3398193323Sedbool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3399193323Sed  LocTy CondLoc, BBLoc;
3400198892Srdivacky  Value *Cond;
3401198892Srdivacky  BasicBlock *DefaultBB;
3402193323Sed  if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3403193323Sed      ParseToken(lltok::comma, "expected ',' after switch condition") ||
3404198892Srdivacky      ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3405193323Sed      ParseToken(lltok::lsquare, "expected '[' with switch table"))
3406193323Sed    return true;
3407193323Sed
3408204642Srdivacky  if (!Cond->getType()->isIntegerTy())
3409193323Sed    return Error(CondLoc, "switch condition must have integer type");
3410198090Srdivacky
3411193323Sed  // Parse the jump table pairs.
3412193323Sed  SmallPtrSet<Value*, 32> SeenCases;
3413193323Sed  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3414193323Sed  while (Lex.getKind() != lltok::rsquare) {
3415198892Srdivacky    Value *Constant;
3416198892Srdivacky    BasicBlock *DestBB;
3417198090Srdivacky
3418193323Sed    if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3419193323Sed        ParseToken(lltok::comma, "expected ',' after case value") ||
3420198892Srdivacky        ParseTypeAndBasicBlock(DestBB, PFS))
3421193323Sed      return true;
3422249423Sdim
3423193323Sed    if (!SeenCases.insert(Constant))
3424193323Sed      return Error(CondLoc, "duplicate case value in switch");
3425193323Sed    if (!isa<ConstantInt>(Constant))
3426193323Sed      return Error(CondLoc, "case value is not a constant integer");
3427198090Srdivacky
3428198892Srdivacky    Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3429193323Sed  }
3430198090Srdivacky
3431193323Sed  Lex.Lex();  // Eat the ']'.
3432198090Srdivacky
3433198892Srdivacky  SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3434193323Sed  for (unsigned i = 0, e = Table.size(); i != e; ++i)
3435193323Sed    SI->addCase(Table[i].first, Table[i].second);
3436193323Sed  Inst = SI;
3437193323Sed  return false;
3438193323Sed}
3439193323Sed
3440198892Srdivacky/// ParseIndirectBr
3441198892Srdivacky///  Instruction
3442198892Srdivacky///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3443198892Srdivackybool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3444198892Srdivacky  LocTy AddrLoc;
3445198892Srdivacky  Value *Address;
3446198892Srdivacky  if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3447198892Srdivacky      ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3448198892Srdivacky      ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3449198892Srdivacky    return true;
3450249423Sdim
3451204642Srdivacky  if (!Address->getType()->isPointerTy())
3452198892Srdivacky    return Error(AddrLoc, "indirectbr address must have pointer type");
3453249423Sdim
3454198892Srdivacky  // Parse the destination list.
3455198892Srdivacky  SmallVector<BasicBlock*, 16> DestList;
3456249423Sdim
3457198892Srdivacky  if (Lex.getKind() != lltok::rsquare) {
3458198892Srdivacky    BasicBlock *DestBB;
3459198892Srdivacky    if (ParseTypeAndBasicBlock(DestBB, PFS))
3460198892Srdivacky      return true;
3461198892Srdivacky    DestList.push_back(DestBB);
3462249423Sdim
3463198892Srdivacky    while (EatIfPresent(lltok::comma)) {
3464198892Srdivacky      if (ParseTypeAndBasicBlock(DestBB, PFS))
3465198892Srdivacky        return true;
3466198892Srdivacky      DestList.push_back(DestBB);
3467198892Srdivacky    }
3468198892Srdivacky  }
3469249423Sdim
3470198892Srdivacky  if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3471198892Srdivacky    return true;
3472198892Srdivacky
3473198892Srdivacky  IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3474198892Srdivacky  for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3475198892Srdivacky    IBI->addDestination(DestList[i]);
3476198892Srdivacky  Inst = IBI;
3477198892Srdivacky  return false;
3478198892Srdivacky}
3479198892Srdivacky
3480198892Srdivacky
3481193323Sed/// ParseInvoke
3482193323Sed///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3483193323Sed///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3484193323Sedbool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3485193323Sed  LocTy CallLoc = Lex.getLoc();
3486243830Sdim  AttrBuilder RetAttrs, FnAttrs;
3487249423Sdim  std::vector<unsigned> FwdRefAttrGrps;
3488249423Sdim  LocTy NoBuiltinLoc;
3489198090Srdivacky  CallingConv::ID CC;
3490224145Sdim  Type *RetType = 0;
3491193323Sed  LocTy RetTypeLoc;
3492193323Sed  ValID CalleeID;
3493193323Sed  SmallVector<ParamInfo, 16> ArgList;
3494193323Sed
3495198892Srdivacky  BasicBlock *NormalBB, *UnwindBB;
3496193323Sed  if (ParseOptionalCallingConv(CC) ||
3497249423Sdim      ParseOptionalReturnAttrs(RetAttrs) ||
3498193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3499193323Sed      ParseValID(CalleeID) ||
3500193323Sed      ParseParameterList(ArgList, PFS) ||
3501249423Sdim      ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3502249423Sdim                                 NoBuiltinLoc) ||
3503193323Sed      ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3504198892Srdivacky      ParseTypeAndBasicBlock(NormalBB, PFS) ||
3505193323Sed      ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3506198892Srdivacky      ParseTypeAndBasicBlock(UnwindBB, PFS))
3507193323Sed    return true;
3508198090Srdivacky
3509193323Sed  // If RetType is a non-function pointer type, then this is the short syntax
3510193323Sed  // for the call, which means that RetType is just the return type.  Infer the
3511193323Sed  // rest of the function argument types from the arguments that are present.
3512226633Sdim  PointerType *PFTy = 0;
3513226633Sdim  FunctionType *Ty = 0;
3514193323Sed  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3515193323Sed      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3516193323Sed    // Pull out the types of all of the arguments...
3517224145Sdim    std::vector<Type*> ParamTypes;
3518193323Sed    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3519193323Sed      ParamTypes.push_back(ArgList[i].V->getType());
3520198090Srdivacky
3521193323Sed    if (!FunctionType::isValidReturnType(RetType))
3522193323Sed      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3523198090Srdivacky
3524198090Srdivacky    Ty = FunctionType::get(RetType, ParamTypes, false);
3525198090Srdivacky    PFTy = PointerType::getUnqual(Ty);
3526193323Sed  }
3527198090Srdivacky
3528193323Sed  // Look up the callee.
3529193323Sed  Value *Callee;
3530202375Srdivacky  if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3531198090Srdivacky
3532249423Sdim  // Set up the Attribute for the function.
3533249423Sdim  SmallVector<AttributeSet, 8> Attrs;
3534243830Sdim  if (RetAttrs.hasAttributes())
3535249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3536249423Sdim                                      AttributeSet::ReturnIndex,
3537249423Sdim                                      RetAttrs));
3538198090Srdivacky
3539193323Sed  SmallVector<Value*, 8> Args;
3540198090Srdivacky
3541193323Sed  // Loop through FunctionType's arguments and ensure they are specified
3542193323Sed  // correctly.  Also, gather any parameter attributes.
3543193323Sed  FunctionType::param_iterator I = Ty->param_begin();
3544193323Sed  FunctionType::param_iterator E = Ty->param_end();
3545193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3546226633Sdim    Type *ExpectedTy = 0;
3547193323Sed    if (I != E) {
3548193323Sed      ExpectedTy = *I++;
3549193323Sed    } else if (!Ty->isVarArg()) {
3550193323Sed      return Error(ArgList[i].Loc, "too many arguments specified");
3551193323Sed    }
3552198090Srdivacky
3553193323Sed    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3554193323Sed      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3555224145Sdim                   getTypeString(ExpectedTy) + "'");
3556193323Sed    Args.push_back(ArgList[i].V);
3557249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3558249423Sdim      AttrBuilder B(ArgList[i].Attrs, i + 1);
3559249423Sdim      Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3560249423Sdim    }
3561193323Sed  }
3562198090Srdivacky
3563193323Sed  if (I != E)
3564193323Sed    return Error(CallLoc, "not enough parameters specified for call");
3565198090Srdivacky
3566243830Sdim  if (FnAttrs.hasAttributes())
3567249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3568249423Sdim                                      AttributeSet::FunctionIndex,
3569249423Sdim                                      FnAttrs));
3570198090Srdivacky
3571249423Sdim  // Finish off the Attribute and check them
3572249423Sdim  AttributeSet PAL = AttributeSet::get(Context, Attrs);
3573198090Srdivacky
3574224145Sdim  InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3575193323Sed  II->setCallingConv(CC);
3576193323Sed  II->setAttributes(PAL);
3577249423Sdim  ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3578193323Sed  Inst = II;
3579193323Sed  return false;
3580193323Sed}
3581193323Sed
3582226633Sdim/// ParseResume
3583226633Sdim///   ::= 'resume' TypeAndValue
3584226633Sdimbool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3585226633Sdim  Value *Exn; LocTy ExnLoc;
3586226633Sdim  if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3587226633Sdim    return true;
3588193323Sed
3589226633Sdim  ResumeInst *RI = ResumeInst::Create(Exn);
3590226633Sdim  Inst = RI;
3591226633Sdim  return false;
3592226633Sdim}
3593193323Sed
3594193323Sed//===----------------------------------------------------------------------===//
3595193323Sed// Binary Operators.
3596193323Sed//===----------------------------------------------------------------------===//
3597193323Sed
3598193323Sed/// ParseArithmetic
3599193323Sed///  ::= ArithmeticOps TypeAndValue ',' Value
3600193323Sed///
3601193323Sed/// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3602193323Sed/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3603193323Sedbool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3604193323Sed                               unsigned Opc, unsigned OperandType) {
3605193323Sed  LocTy Loc; Value *LHS, *RHS;
3606193323Sed  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3607193323Sed      ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3608193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3609193323Sed    return true;
3610193323Sed
3611193323Sed  bool Valid;
3612193323Sed  switch (OperandType) {
3613198090Srdivacky  default: llvm_unreachable("Unknown operand type!");
3614193323Sed  case 0: // int or FP.
3615203954Srdivacky    Valid = LHS->getType()->isIntOrIntVectorTy() ||
3616203954Srdivacky            LHS->getType()->isFPOrFPVectorTy();
3617193323Sed    break;
3618203954Srdivacky  case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3619203954Srdivacky  case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3620193323Sed  }
3621198090Srdivacky
3622193323Sed  if (!Valid)
3623193323Sed    return Error(Loc, "invalid operand type for instruction");
3624198090Srdivacky
3625193323Sed  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3626193323Sed  return false;
3627193323Sed}
3628193323Sed
3629193323Sed/// ParseLogical
3630193323Sed///  ::= ArithmeticOps TypeAndValue ',' Value {
3631193323Sedbool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3632193323Sed                            unsigned Opc) {
3633193323Sed  LocTy Loc; Value *LHS, *RHS;
3634193323Sed  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3635193323Sed      ParseToken(lltok::comma, "expected ',' in logical operation") ||
3636193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3637193323Sed    return true;
3638193323Sed
3639203954Srdivacky  if (!LHS->getType()->isIntOrIntVectorTy())
3640193323Sed    return Error(Loc,"instruction requires integer or integer vector operands");
3641193323Sed
3642193323Sed  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3643193323Sed  return false;
3644193323Sed}
3645193323Sed
3646193323Sed
3647193323Sed/// ParseCompare
3648193323Sed///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3649193323Sed///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3650193323Sedbool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3651193323Sed                            unsigned Opc) {
3652193323Sed  // Parse the integer/fp comparison predicate.
3653193323Sed  LocTy Loc;
3654193323Sed  unsigned Pred;
3655193323Sed  Value *LHS, *RHS;
3656193323Sed  if (ParseCmpPredicate(Pred, Opc) ||
3657193323Sed      ParseTypeAndValue(LHS, Loc, PFS) ||
3658193323Sed      ParseToken(lltok::comma, "expected ',' after compare value") ||
3659193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3660193323Sed    return true;
3661198090Srdivacky
3662193323Sed  if (Opc == Instruction::FCmp) {
3663203954Srdivacky    if (!LHS->getType()->isFPOrFPVectorTy())
3664193323Sed      return Error(Loc, "fcmp requires floating point operands");
3665193323Sed    Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3666198090Srdivacky  } else {
3667198090Srdivacky    assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3668203954Srdivacky    if (!LHS->getType()->isIntOrIntVectorTy() &&
3669234353Sdim        !LHS->getType()->getScalarType()->isPointerTy())
3670193323Sed      return Error(Loc, "icmp requires integer operands");
3671193323Sed    Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3672193323Sed  }
3673193323Sed  return false;
3674193323Sed}
3675193323Sed
3676193323Sed//===----------------------------------------------------------------------===//
3677193323Sed// Other Instructions.
3678193323Sed//===----------------------------------------------------------------------===//
3679193323Sed
3680193323Sed
3681193323Sed/// ParseCast
3682193323Sed///   ::= CastOpc TypeAndValue 'to' Type
3683193323Sedbool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3684193323Sed                         unsigned Opc) {
3685224145Sdim  LocTy Loc;
3686224145Sdim  Value *Op;
3687224145Sdim  Type *DestTy = 0;
3688193323Sed  if (ParseTypeAndValue(Op, Loc, PFS) ||
3689193323Sed      ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3690193323Sed      ParseType(DestTy))
3691193323Sed    return true;
3692198090Srdivacky
3693193323Sed  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3694193323Sed    CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3695193323Sed    return Error(Loc, "invalid cast opcode for cast from '" +
3696224145Sdim                 getTypeString(Op->getType()) + "' to '" +
3697224145Sdim                 getTypeString(DestTy) + "'");
3698193323Sed  }
3699193323Sed  Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3700193323Sed  return false;
3701193323Sed}
3702193323Sed
3703193323Sed/// ParseSelect
3704193323Sed///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3705193323Sedbool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3706193323Sed  LocTy Loc;
3707193323Sed  Value *Op0, *Op1, *Op2;
3708193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3709193323Sed      ParseToken(lltok::comma, "expected ',' after select condition") ||
3710193323Sed      ParseTypeAndValue(Op1, PFS) ||
3711193323Sed      ParseToken(lltok::comma, "expected ',' after select value") ||
3712193323Sed      ParseTypeAndValue(Op2, PFS))
3713193323Sed    return true;
3714198090Srdivacky
3715193323Sed  if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3716193323Sed    return Error(Loc, Reason);
3717198090Srdivacky
3718193323Sed  Inst = SelectInst::Create(Op0, Op1, Op2);
3719193323Sed  return false;
3720193323Sed}
3721193323Sed
3722193323Sed/// ParseVA_Arg
3723193323Sed///   ::= 'va_arg' TypeAndValue ',' Type
3724193323Sedbool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3725193323Sed  Value *Op;
3726224145Sdim  Type *EltTy = 0;
3727193323Sed  LocTy TypeLoc;
3728193323Sed  if (ParseTypeAndValue(Op, PFS) ||
3729193323Sed      ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3730193323Sed      ParseType(EltTy, TypeLoc))
3731193323Sed    return true;
3732198090Srdivacky
3733193323Sed  if (!EltTy->isFirstClassType())
3734193323Sed    return Error(TypeLoc, "va_arg requires operand with first class type");
3735193323Sed
3736193323Sed  Inst = new VAArgInst(Op, EltTy);
3737193323Sed  return false;
3738193323Sed}
3739193323Sed
3740193323Sed/// ParseExtractElement
3741193323Sed///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3742193323Sedbool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3743193323Sed  LocTy Loc;
3744193323Sed  Value *Op0, *Op1;
3745193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3746193323Sed      ParseToken(lltok::comma, "expected ',' after extract value") ||
3747193323Sed      ParseTypeAndValue(Op1, PFS))
3748193323Sed    return true;
3749198090Srdivacky
3750193323Sed  if (!ExtractElementInst::isValidOperands(Op0, Op1))
3751193323Sed    return Error(Loc, "invalid extractelement operands");
3752198090Srdivacky
3753198090Srdivacky  Inst = ExtractElementInst::Create(Op0, Op1);
3754193323Sed  return false;
3755193323Sed}
3756193323Sed
3757193323Sed/// ParseInsertElement
3758193323Sed///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3759193323Sedbool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3760193323Sed  LocTy Loc;
3761193323Sed  Value *Op0, *Op1, *Op2;
3762193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3763193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3764193323Sed      ParseTypeAndValue(Op1, PFS) ||
3765193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3766193323Sed      ParseTypeAndValue(Op2, PFS))
3767193323Sed    return true;
3768198090Srdivacky
3769193323Sed  if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3770198090Srdivacky    return Error(Loc, "invalid insertelement operands");
3771198090Srdivacky
3772193323Sed  Inst = InsertElementInst::Create(Op0, Op1, Op2);
3773193323Sed  return false;
3774193323Sed}
3775193323Sed
3776193323Sed/// ParseShuffleVector
3777193323Sed///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3778193323Sedbool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3779193323Sed  LocTy Loc;
3780193323Sed  Value *Op0, *Op1, *Op2;
3781193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3782193323Sed      ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3783193323Sed      ParseTypeAndValue(Op1, PFS) ||
3784193323Sed      ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3785193323Sed      ParseTypeAndValue(Op2, PFS))
3786193323Sed    return true;
3787198090Srdivacky
3788193323Sed  if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3789234353Sdim    return Error(Loc, "invalid shufflevector operands");
3790198090Srdivacky
3791193323Sed  Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3792193323Sed  return false;
3793193323Sed}
3794193323Sed
3795193323Sed/// ParsePHI
3796198396Srdivacky///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3797201360Srdivackyint LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3798224145Sdim  Type *Ty = 0;  LocTy TypeLoc;
3799193323Sed  Value *Op0, *Op1;
3800198090Srdivacky
3801224145Sdim  if (ParseType(Ty, TypeLoc) ||
3802193323Sed      ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3803193323Sed      ParseValue(Ty, Op0, PFS) ||
3804193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3805198090Srdivacky      ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3806193323Sed      ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3807193323Sed    return true;
3808198090Srdivacky
3809201360Srdivacky  bool AteExtraComma = false;
3810193323Sed  SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3811193323Sed  while (1) {
3812193323Sed    PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3813198090Srdivacky
3814193323Sed    if (!EatIfPresent(lltok::comma))
3815193323Sed      break;
3816193323Sed
3817201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
3818201360Srdivacky      AteExtraComma = true;
3819198396Srdivacky      break;
3820201360Srdivacky    }
3821198396Srdivacky
3822193323Sed    if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3823193323Sed        ParseValue(Ty, Op0, PFS) ||
3824193323Sed        ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3825198090Srdivacky        ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3826193323Sed        ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3827193323Sed      return true;
3828193323Sed  }
3829198090Srdivacky
3830193323Sed  if (!Ty->isFirstClassType())
3831193323Sed    return Error(TypeLoc, "phi node must have first class type");
3832193323Sed
3833221345Sdim  PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3834193323Sed  for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3835193323Sed    PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3836193323Sed  Inst = PN;
3837201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3838193323Sed}
3839193323Sed
3840226633Sdim/// ParseLandingPad
3841226633Sdim///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3842226633Sdim/// Clause
3843226633Sdim///   ::= 'catch' TypeAndValue
3844226633Sdim///   ::= 'filter'
3845226633Sdim///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3846226633Sdimbool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3847226633Sdim  Type *Ty = 0; LocTy TyLoc;
3848226633Sdim  Value *PersFn; LocTy PersFnLoc;
3849226633Sdim
3850226633Sdim  if (ParseType(Ty, TyLoc) ||
3851226633Sdim      ParseToken(lltok::kw_personality, "expected 'personality'") ||
3852226633Sdim      ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3853226633Sdim    return true;
3854226633Sdim
3855226633Sdim  LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3856226633Sdim  LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3857226633Sdim
3858226633Sdim  while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3859226633Sdim    LandingPadInst::ClauseType CT;
3860226633Sdim    if (EatIfPresent(lltok::kw_catch))
3861226633Sdim      CT = LandingPadInst::Catch;
3862226633Sdim    else if (EatIfPresent(lltok::kw_filter))
3863226633Sdim      CT = LandingPadInst::Filter;
3864226633Sdim    else
3865226633Sdim      return TokError("expected 'catch' or 'filter' clause type");
3866226633Sdim
3867226633Sdim    Value *V; LocTy VLoc;
3868226633Sdim    if (ParseTypeAndValue(V, VLoc, PFS)) {
3869226633Sdim      delete LP;
3870226633Sdim      return true;
3871226633Sdim    }
3872226633Sdim
3873226633Sdim    // A 'catch' type expects a non-array constant. A filter clause expects an
3874226633Sdim    // array constant.
3875226633Sdim    if (CT == LandingPadInst::Catch) {
3876226633Sdim      if (isa<ArrayType>(V->getType()))
3877226633Sdim        Error(VLoc, "'catch' clause has an invalid type");
3878226633Sdim    } else {
3879226633Sdim      if (!isa<ArrayType>(V->getType()))
3880226633Sdim        Error(VLoc, "'filter' clause has an invalid type");
3881226633Sdim    }
3882226633Sdim
3883226633Sdim    LP->addClause(V);
3884226633Sdim  }
3885226633Sdim
3886226633Sdim  Inst = LP;
3887226633Sdim  return false;
3888226633Sdim}
3889226633Sdim
3890193323Sed/// ParseCall
3891193323Sed///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3892193323Sed///       ParameterList OptionalAttrs
3893193323Sedbool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3894193323Sed                         bool isTail) {
3895243830Sdim  AttrBuilder RetAttrs, FnAttrs;
3896249423Sdim  std::vector<unsigned> FwdRefAttrGrps;
3897249423Sdim  LocTy NoBuiltinLoc;
3898198090Srdivacky  CallingConv::ID CC;
3899224145Sdim  Type *RetType = 0;
3900193323Sed  LocTy RetTypeLoc;
3901193323Sed  ValID CalleeID;
3902193323Sed  SmallVector<ParamInfo, 16> ArgList;
3903193323Sed  LocTy CallLoc = Lex.getLoc();
3904198090Srdivacky
3905193323Sed  if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3906193323Sed      ParseOptionalCallingConv(CC) ||
3907249423Sdim      ParseOptionalReturnAttrs(RetAttrs) ||
3908193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3909193323Sed      ParseValID(CalleeID) ||
3910193323Sed      ParseParameterList(ArgList, PFS) ||
3911249423Sdim      ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3912249423Sdim                                 NoBuiltinLoc))
3913193323Sed    return true;
3914198090Srdivacky
3915193323Sed  // If RetType is a non-function pointer type, then this is the short syntax
3916193323Sed  // for the call, which means that RetType is just the return type.  Infer the
3917193323Sed  // rest of the function argument types from the arguments that are present.
3918226633Sdim  PointerType *PFTy = 0;
3919226633Sdim  FunctionType *Ty = 0;
3920193323Sed  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3921193323Sed      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3922193323Sed    // Pull out the types of all of the arguments...
3923224145Sdim    std::vector<Type*> ParamTypes;
3924193323Sed    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3925193323Sed      ParamTypes.push_back(ArgList[i].V->getType());
3926198090Srdivacky
3927193323Sed    if (!FunctionType::isValidReturnType(RetType))
3928193323Sed      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3929198090Srdivacky
3930198090Srdivacky    Ty = FunctionType::get(RetType, ParamTypes, false);
3931198090Srdivacky    PFTy = PointerType::getUnqual(Ty);
3932193323Sed  }
3933198090Srdivacky
3934193323Sed  // Look up the callee.
3935193323Sed  Value *Callee;
3936202375Srdivacky  if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3937198090Srdivacky
3938249423Sdim  // Set up the Attribute for the function.
3939249423Sdim  SmallVector<AttributeSet, 8> Attrs;
3940243830Sdim  if (RetAttrs.hasAttributes())
3941249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3942249423Sdim                                      AttributeSet::ReturnIndex,
3943249423Sdim                                      RetAttrs));
3944198090Srdivacky
3945193323Sed  SmallVector<Value*, 8> Args;
3946198090Srdivacky
3947193323Sed  // Loop through FunctionType's arguments and ensure they are specified
3948193323Sed  // correctly.  Also, gather any parameter attributes.
3949193323Sed  FunctionType::param_iterator I = Ty->param_begin();
3950193323Sed  FunctionType::param_iterator E = Ty->param_end();
3951193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3952226633Sdim    Type *ExpectedTy = 0;
3953193323Sed    if (I != E) {
3954193323Sed      ExpectedTy = *I++;
3955193323Sed    } else if (!Ty->isVarArg()) {
3956193323Sed      return Error(ArgList[i].Loc, "too many arguments specified");
3957193323Sed    }
3958198090Srdivacky
3959193323Sed    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3960193323Sed      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3961224145Sdim                   getTypeString(ExpectedTy) + "'");
3962193323Sed    Args.push_back(ArgList[i].V);
3963249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3964249423Sdim      AttrBuilder B(ArgList[i].Attrs, i + 1);
3965249423Sdim      Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3966249423Sdim    }
3967193323Sed  }
3968198090Srdivacky
3969193323Sed  if (I != E)
3970193323Sed    return Error(CallLoc, "not enough parameters specified for call");
3971193323Sed
3972243830Sdim  if (FnAttrs.hasAttributes())
3973249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3974249423Sdim                                      AttributeSet::FunctionIndex,
3975249423Sdim                                      FnAttrs));
3976193323Sed
3977249423Sdim  // Finish off the Attribute and check them
3978249423Sdim  AttributeSet PAL = AttributeSet::get(Context, Attrs);
3979198090Srdivacky
3980224145Sdim  CallInst *CI = CallInst::Create(Callee, Args);
3981193323Sed  CI->setTailCall(isTail);
3982193323Sed  CI->setCallingConv(CC);
3983193323Sed  CI->setAttributes(PAL);
3984249423Sdim  ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
3985193323Sed  Inst = CI;
3986193323Sed  return false;
3987193323Sed}
3988193323Sed
3989193323Sed//===----------------------------------------------------------------------===//
3990193323Sed// Memory Instructions.
3991193323Sed//===----------------------------------------------------------------------===//
3992193323Sed
3993193323Sed/// ParseAlloc
3994198090Srdivacky///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3995224145Sdimint LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3996193323Sed  Value *Size = 0;
3997195340Sed  LocTy SizeLoc;
3998193323Sed  unsigned Alignment = 0;
3999224145Sdim  Type *Ty = 0;
4000193323Sed  if (ParseType(Ty)) return true;
4001193323Sed
4002201360Srdivacky  bool AteExtraComma = false;
4003193323Sed  if (EatIfPresent(lltok::comma)) {
4004201360Srdivacky    if (Lex.getKind() == lltok::kw_align) {
4005201360Srdivacky      if (ParseOptionalAlignment(Alignment)) return true;
4006201360Srdivacky    } else if (Lex.getKind() == lltok::MetadataVar) {
4007201360Srdivacky      AteExtraComma = true;
4008198090Srdivacky    } else {
4009201360Srdivacky      if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4010201360Srdivacky          ParseOptionalCommaAlign(Alignment, AteExtraComma))
4011201360Srdivacky        return true;
4012193323Sed    }
4013193323Sed  }
4014193323Sed
4015210299Sed  if (Size && !Size->getType()->isIntegerTy())
4016210299Sed    return Error(SizeLoc, "element count must have integer type");
4017193323Sed
4018224145Sdim  Inst = new AllocaInst(Ty, Size, Alignment);
4019224145Sdim  return AteExtraComma ? InstExtraComma : InstNormal;
4020193323Sed}
4021193323Sed
4022193323Sed/// ParseLoad
4023226633Sdim///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4024249423Sdim///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
4025226633Sdim///       'singlethread'? AtomicOrdering (',' 'align' i32)?
4026234353Sdimint LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4027193323Sed  Value *Val; LocTy Loc;
4028198090Srdivacky  unsigned Alignment = 0;
4029201360Srdivacky  bool AteExtraComma = false;
4030226633Sdim  bool isAtomic = false;
4031226633Sdim  AtomicOrdering Ordering = NotAtomic;
4032226633Sdim  SynchronizationScope Scope = CrossThread;
4033226633Sdim
4034226633Sdim  if (Lex.getKind() == lltok::kw_atomic) {
4035226633Sdim    isAtomic = true;
4036226633Sdim    Lex.Lex();
4037226633Sdim  }
4038226633Sdim
4039234353Sdim  bool isVolatile = false;
4040226633Sdim  if (Lex.getKind() == lltok::kw_volatile) {
4041226633Sdim    isVolatile = true;
4042226633Sdim    Lex.Lex();
4043226633Sdim  }
4044226633Sdim
4045201360Srdivacky  if (ParseTypeAndValue(Val, Loc, PFS) ||
4046226633Sdim      ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4047201360Srdivacky      ParseOptionalCommaAlign(Alignment, AteExtraComma))
4048201360Srdivacky    return true;
4049193323Sed
4050204642Srdivacky  if (!Val->getType()->isPointerTy() ||
4051193323Sed      !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4052193323Sed    return Error(Loc, "load operand must be a pointer to a first class type");
4053226633Sdim  if (isAtomic && !Alignment)
4054226633Sdim    return Error(Loc, "atomic load must have explicit non-zero alignment");
4055226633Sdim  if (Ordering == Release || Ordering == AcquireRelease)
4056226633Sdim    return Error(Loc, "atomic load cannot use Release ordering");
4057198090Srdivacky
4058226633Sdim  Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4059201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4060193323Sed}
4061193323Sed
4062193323Sed/// ParseStore
4063226633Sdim
4064226633Sdim///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4065226633Sdim///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4066226633Sdim///       'singlethread'? AtomicOrdering (',' 'align' i32)?
4067234353Sdimint LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4068193323Sed  Value *Val, *Ptr; LocTy Loc, PtrLoc;
4069198090Srdivacky  unsigned Alignment = 0;
4070201360Srdivacky  bool AteExtraComma = false;
4071226633Sdim  bool isAtomic = false;
4072226633Sdim  AtomicOrdering Ordering = NotAtomic;
4073226633Sdim  SynchronizationScope Scope = CrossThread;
4074226633Sdim
4075226633Sdim  if (Lex.getKind() == lltok::kw_atomic) {
4076226633Sdim    isAtomic = true;
4077226633Sdim    Lex.Lex();
4078226633Sdim  }
4079226633Sdim
4080234353Sdim  bool isVolatile = false;
4081226633Sdim  if (Lex.getKind() == lltok::kw_volatile) {
4082226633Sdim    isVolatile = true;
4083226633Sdim    Lex.Lex();
4084226633Sdim  }
4085226633Sdim
4086193323Sed  if (ParseTypeAndValue(Val, Loc, PFS) ||
4087193323Sed      ParseToken(lltok::comma, "expected ',' after store operand") ||
4088201360Srdivacky      ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4089226633Sdim      ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4090201360Srdivacky      ParseOptionalCommaAlign(Alignment, AteExtraComma))
4091193323Sed    return true;
4092198090Srdivacky
4093204642Srdivacky  if (!Ptr->getType()->isPointerTy())
4094193323Sed    return Error(PtrLoc, "store operand must be a pointer");
4095193323Sed  if (!Val->getType()->isFirstClassType())
4096193323Sed    return Error(Loc, "store operand must be a first class value");
4097193323Sed  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4098193323Sed    return Error(Loc, "stored value and pointer type do not match");
4099226633Sdim  if (isAtomic && !Alignment)
4100226633Sdim    return Error(Loc, "atomic store must have explicit non-zero alignment");
4101226633Sdim  if (Ordering == Acquire || Ordering == AcquireRelease)
4102226633Sdim    return Error(Loc, "atomic store cannot use Acquire ordering");
4103198090Srdivacky
4104226633Sdim  Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4105201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4106193323Sed}
4107193323Sed
4108226633Sdim/// ParseCmpXchg
4109226633Sdim///   ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4110226633Sdim///       'singlethread'? AtomicOrdering
4111226633Sdimint LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4112226633Sdim  Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4113226633Sdim  bool AteExtraComma = false;
4114226633Sdim  AtomicOrdering Ordering = NotAtomic;
4115226633Sdim  SynchronizationScope Scope = CrossThread;
4116226633Sdim  bool isVolatile = false;
4117226633Sdim
4118226633Sdim  if (EatIfPresent(lltok::kw_volatile))
4119226633Sdim    isVolatile = true;
4120226633Sdim
4121226633Sdim  if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4122226633Sdim      ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4123226633Sdim      ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4124226633Sdim      ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4125226633Sdim      ParseTypeAndValue(New, NewLoc, PFS) ||
4126226633Sdim      ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4127226633Sdim    return true;
4128226633Sdim
4129226633Sdim  if (Ordering == Unordered)
4130226633Sdim    return TokError("cmpxchg cannot be unordered");
4131226633Sdim  if (!Ptr->getType()->isPointerTy())
4132226633Sdim    return Error(PtrLoc, "cmpxchg operand must be a pointer");
4133226633Sdim  if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4134226633Sdim    return Error(CmpLoc, "compare value and pointer type do not match");
4135226633Sdim  if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4136226633Sdim    return Error(NewLoc, "new value and pointer type do not match");
4137226633Sdim  if (!New->getType()->isIntegerTy())
4138226633Sdim    return Error(NewLoc, "cmpxchg operand must be an integer");
4139226633Sdim  unsigned Size = New->getType()->getPrimitiveSizeInBits();
4140226633Sdim  if (Size < 8 || (Size & (Size - 1)))
4141226633Sdim    return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4142226633Sdim                         " integer");
4143226633Sdim
4144226633Sdim  AtomicCmpXchgInst *CXI =
4145226633Sdim    new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4146226633Sdim  CXI->setVolatile(isVolatile);
4147226633Sdim  Inst = CXI;
4148226633Sdim  return AteExtraComma ? InstExtraComma : InstNormal;
4149226633Sdim}
4150226633Sdim
4151226633Sdim/// ParseAtomicRMW
4152226633Sdim///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4153226633Sdim///       'singlethread'? AtomicOrdering
4154226633Sdimint LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4155226633Sdim  Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4156226633Sdim  bool AteExtraComma = false;
4157226633Sdim  AtomicOrdering Ordering = NotAtomic;
4158226633Sdim  SynchronizationScope Scope = CrossThread;
4159226633Sdim  bool isVolatile = false;
4160226633Sdim  AtomicRMWInst::BinOp Operation;
4161226633Sdim
4162226633Sdim  if (EatIfPresent(lltok::kw_volatile))
4163226633Sdim    isVolatile = true;
4164226633Sdim
4165226633Sdim  switch (Lex.getKind()) {
4166226633Sdim  default: return TokError("expected binary operation in atomicrmw");
4167226633Sdim  case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4168226633Sdim  case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4169226633Sdim  case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4170226633Sdim  case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4171226633Sdim  case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4172226633Sdim  case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4173226633Sdim  case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4174226633Sdim  case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4175226633Sdim  case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4176226633Sdim  case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4177226633Sdim  case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4178226633Sdim  }
4179226633Sdim  Lex.Lex();  // Eat the operation.
4180226633Sdim
4181226633Sdim  if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4182226633Sdim      ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4183226633Sdim      ParseTypeAndValue(Val, ValLoc, PFS) ||
4184226633Sdim      ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4185226633Sdim    return true;
4186226633Sdim
4187226633Sdim  if (Ordering == Unordered)
4188226633Sdim    return TokError("atomicrmw cannot be unordered");
4189226633Sdim  if (!Ptr->getType()->isPointerTy())
4190226633Sdim    return Error(PtrLoc, "atomicrmw operand must be a pointer");
4191226633Sdim  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4192226633Sdim    return Error(ValLoc, "atomicrmw value and pointer type do not match");
4193226633Sdim  if (!Val->getType()->isIntegerTy())
4194226633Sdim    return Error(ValLoc, "atomicrmw operand must be an integer");
4195226633Sdim  unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4196226633Sdim  if (Size < 8 || (Size & (Size - 1)))
4197226633Sdim    return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4198226633Sdim                         " integer");
4199226633Sdim
4200226633Sdim  AtomicRMWInst *RMWI =
4201226633Sdim    new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4202226633Sdim  RMWI->setVolatile(isVolatile);
4203226633Sdim  Inst = RMWI;
4204226633Sdim  return AteExtraComma ? InstExtraComma : InstNormal;
4205226633Sdim}
4206226633Sdim
4207226633Sdim/// ParseFence
4208226633Sdim///   ::= 'fence' 'singlethread'? AtomicOrdering
4209226633Sdimint LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4210226633Sdim  AtomicOrdering Ordering = NotAtomic;
4211226633Sdim  SynchronizationScope Scope = CrossThread;
4212226633Sdim  if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4213226633Sdim    return true;
4214226633Sdim
4215226633Sdim  if (Ordering == Unordered)
4216226633Sdim    return TokError("fence cannot be unordered");
4217226633Sdim  if (Ordering == Monotonic)
4218226633Sdim    return TokError("fence cannot be monotonic");
4219226633Sdim
4220226633Sdim  Inst = new FenceInst(Context, Ordering, Scope);
4221226633Sdim  return InstNormal;
4222226633Sdim}
4223226633Sdim
4224193323Sed/// ParseGetElementPtr
4225198090Srdivacky///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4226201360Srdivackyint LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4227234353Sdim  Value *Ptr = 0;
4228234353Sdim  Value *Val = 0;
4229234353Sdim  LocTy Loc, EltLoc;
4230198090Srdivacky
4231198090Srdivacky  bool InBounds = EatIfPresent(lltok::kw_inbounds);
4232198090Srdivacky
4233193323Sed  if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4234198090Srdivacky
4235234353Sdim  if (!Ptr->getType()->getScalarType()->isPointerTy())
4236193323Sed    return Error(Loc, "base of getelementptr must be a pointer");
4237198090Srdivacky
4238193323Sed  SmallVector<Value*, 16> Indices;
4239201360Srdivacky  bool AteExtraComma = false;
4240193323Sed  while (EatIfPresent(lltok::comma)) {
4241201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
4242201360Srdivacky      AteExtraComma = true;
4243198090Srdivacky      break;
4244201360Srdivacky    }
4245193323Sed    if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4246234353Sdim    if (!Val->getType()->getScalarType()->isIntegerTy())
4247193323Sed      return Error(EltLoc, "getelementptr index must be an integer");
4248234353Sdim    if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4249234353Sdim      return Error(EltLoc, "getelementptr index type missmatch");
4250234353Sdim    if (Val->getType()->isVectorTy()) {
4251234353Sdim      unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4252234353Sdim      unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4253234353Sdim      if (ValNumEl != PtrNumEl)
4254234353Sdim        return Error(EltLoc,
4255234353Sdim          "getelementptr vector index has a wrong number of elements");
4256234353Sdim    }
4257193323Sed    Indices.push_back(Val);
4258193323Sed  }
4259198090Srdivacky
4260226633Sdim  if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4261193323Sed    return Error(Loc, "invalid getelementptr indices");
4262226633Sdim  Inst = GetElementPtrInst::Create(Ptr, Indices);
4263198090Srdivacky  if (InBounds)
4264198090Srdivacky    cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4265201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4266193323Sed}
4267193323Sed
4268193323Sed/// ParseExtractValue
4269193323Sed///   ::= 'extractvalue' TypeAndValue (',' uint32)+
4270201360Srdivackyint LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4271193323Sed  Value *Val; LocTy Loc;
4272193323Sed  SmallVector<unsigned, 4> Indices;
4273201360Srdivacky  bool AteExtraComma;
4274193323Sed  if (ParseTypeAndValue(Val, Loc, PFS) ||
4275201360Srdivacky      ParseIndexList(Indices, AteExtraComma))
4276193323Sed    return true;
4277193323Sed
4278203954Srdivacky  if (!Val->getType()->isAggregateType())
4279203954Srdivacky    return Error(Loc, "extractvalue operand must be aggregate type");
4280193323Sed
4281224145Sdim  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4282193323Sed    return Error(Loc, "invalid indices for extractvalue");
4283224145Sdim  Inst = ExtractValueInst::Create(Val, Indices);
4284201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4285193323Sed}
4286193323Sed
4287193323Sed/// ParseInsertValue
4288193323Sed///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4289201360Srdivackyint LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4290193323Sed  Value *Val0, *Val1; LocTy Loc0, Loc1;
4291193323Sed  SmallVector<unsigned, 4> Indices;
4292201360Srdivacky  bool AteExtraComma;
4293193323Sed  if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4294193323Sed      ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4295193323Sed      ParseTypeAndValue(Val1, Loc1, PFS) ||
4296201360Srdivacky      ParseIndexList(Indices, AteExtraComma))
4297193323Sed    return true;
4298249423Sdim
4299203954Srdivacky  if (!Val0->getType()->isAggregateType())
4300203954Srdivacky    return Error(Loc0, "insertvalue operand must be aggregate type");
4301198090Srdivacky
4302224145Sdim  if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4303193323Sed    return Error(Loc0, "invalid indices for insertvalue");
4304224145Sdim  Inst = InsertValueInst::Create(Val0, Val1, Indices);
4305201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4306193323Sed}
4307193323Sed
4308193323Sed//===----------------------------------------------------------------------===//
4309193323Sed// Embedded metadata.
4310193323Sed//===----------------------------------------------------------------------===//
4311193323Sed
4312193323Sed/// ParseMDNodeVector
4313193323Sed///   ::= Element (',' Element)*
4314193323Sed/// Element
4315193323Sed///   ::= 'null' | TypeAndValue
4316202375Srdivackybool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4317202375Srdivacky                                 PerFunctionState *PFS) {
4318210299Sed  // Check for an empty list.
4319210299Sed  if (Lex.getKind() == lltok::rbrace)
4320210299Sed    return false;
4321210299Sed
4322193323Sed  do {
4323201360Srdivacky    // Null is a special case since it is typeless.
4324201360Srdivacky    if (EatIfPresent(lltok::kw_null)) {
4325201360Srdivacky      Elts.push_back(0);
4326201360Srdivacky      continue;
4327201360Srdivacky    }
4328249423Sdim
4329198090Srdivacky    Value *V = 0;
4330224145Sdim    if (ParseTypeAndValue(V, PFS)) return true;
4331193323Sed    Elts.push_back(V);
4332193323Sed  } while (EatIfPresent(lltok::comma));
4333193323Sed
4334193323Sed  return false;
4335193323Sed}
4336