1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
31 /// ValID - Represents a reference of a definition of some sort with no type.
32 /// There are several cases where we have to parse the value but where the
33 /// type can depend on later context. This may either be a numeric reference
34 /// or a symbolic (%var) reference. This is just a discriminated union.
37 t_LocalID, t_GlobalID, // ID in UIntVal.
38 t_LocalName, t_GlobalName, // Name in StrVal.
39 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
40 t_Null, t_Undef, t_Zero, // No value.
41 t_EmptyArray, // No value: []
42 t_Constant, // Value in ConstantVal.
43 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
48 std::string StrVal, StrVal2;
51 Constant *ConstantVal;
52 ValID() : APFloatVal(0.0) {}
56 /// Run: module ::= toplevelentity*
57 bool LLParser::Run() {
61 return ParseTopLevelEntities() ||
62 ValidateEndOfModule();
65 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
67 bool LLParser::ValidateEndOfModule() {
68 if (!ForwardRefTypes.empty())
69 return Error(ForwardRefTypes.begin()->second.second,
70 "use of undefined type named '" +
71 ForwardRefTypes.begin()->first + "'");
72 if (!ForwardRefTypeIDs.empty())
73 return Error(ForwardRefTypeIDs.begin()->second.second,
74 "use of undefined type '%" +
75 utostr(ForwardRefTypeIDs.begin()->first) + "'");
77 if (!ForwardRefVals.empty())
78 return Error(ForwardRefVals.begin()->second.second,
79 "use of undefined value '@" + ForwardRefVals.begin()->first +
82 if (!ForwardRefValIDs.empty())
83 return Error(ForwardRefValIDs.begin()->second.second,
84 "use of undefined value '@" +
85 utostr(ForwardRefValIDs.begin()->first) + "'");
87 if (!ForwardRefMDNodes.empty())
88 return Error(ForwardRefMDNodes.begin()->second.second,
89 "use of undefined metadata '!" +
90 utostr(ForwardRefMDNodes.begin()->first) + "'");
93 // Look for intrinsic functions and CallInst that need to be upgraded
94 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
95 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
100 //===----------------------------------------------------------------------===//
101 // Top-Level Entities
102 //===----------------------------------------------------------------------===//
104 bool LLParser::ParseTopLevelEntities() {
106 switch (Lex.getKind()) {
107 default: return TokError("expected top-level entity");
108 case lltok::Eof: return false;
109 //case lltok::kw_define:
110 case lltok::kw_declare: if (ParseDeclare()) return true; break;
111 case lltok::kw_define: if (ParseDefine()) return true; break;
112 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
113 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
114 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
115 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
116 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
117 case lltok::LocalVar: if (ParseNamedType()) return true; break;
118 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
119 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
121 // The Global variable production with no name can have many different
122 // optional leading prefixes, the production is:
123 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
124 // OptionalAddrSpace ('constant'|'global') ...
125 case lltok::kw_private: // OptionalLinkage
126 case lltok::kw_internal: // OptionalLinkage
127 case lltok::kw_weak: // OptionalLinkage
128 case lltok::kw_weak_odr: // OptionalLinkage
129 case lltok::kw_linkonce: // OptionalLinkage
130 case lltok::kw_linkonce_odr: // OptionalLinkage
131 case lltok::kw_appending: // OptionalLinkage
132 case lltok::kw_dllexport: // OptionalLinkage
133 case lltok::kw_common: // OptionalLinkage
134 case lltok::kw_dllimport: // OptionalLinkage
135 case lltok::kw_extern_weak: // OptionalLinkage
136 case lltok::kw_external: { // OptionalLinkage
137 unsigned Linkage, Visibility;
138 if (ParseOptionalLinkage(Linkage) ||
139 ParseOptionalVisibility(Visibility) ||
140 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
144 case lltok::kw_default: // OptionalVisibility
145 case lltok::kw_hidden: // OptionalVisibility
146 case lltok::kw_protected: { // OptionalVisibility
148 if (ParseOptionalVisibility(Visibility) ||
149 ParseGlobal("", SMLoc(), 0, false, Visibility))
154 case lltok::kw_thread_local: // OptionalThreadLocal
155 case lltok::kw_addrspace: // OptionalAddrSpace
156 case lltok::kw_constant: // GlobalType
157 case lltok::kw_global: // GlobalType
158 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
166 /// ::= 'module' 'asm' STRINGCONSTANT
167 bool LLParser::ParseModuleAsm() {
168 assert(Lex.getKind() == lltok::kw_module);
172 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
173 ParseStringConstant(AsmStr)) return true;
175 const std::string &AsmSoFar = M->getModuleInlineAsm();
176 if (AsmSoFar.empty())
177 M->setModuleInlineAsm(AsmStr);
179 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
184 /// ::= 'target' 'triple' '=' STRINGCONSTANT
185 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
186 bool LLParser::ParseTargetDefinition() {
187 assert(Lex.getKind() == lltok::kw_target);
190 default: return TokError("unknown target property");
191 case lltok::kw_triple:
193 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
194 ParseStringConstant(Str))
196 M->setTargetTriple(Str);
198 case lltok::kw_datalayout:
200 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
201 ParseStringConstant(Str))
203 M->setDataLayout(Str);
209 /// ::= 'deplibs' '=' '[' ']'
210 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
211 bool LLParser::ParseDepLibs() {
212 assert(Lex.getKind() == lltok::kw_deplibs);
214 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
215 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
218 if (EatIfPresent(lltok::rsquare))
222 if (ParseStringConstant(Str)) return true;
225 while (EatIfPresent(lltok::comma)) {
226 if (ParseStringConstant(Str)) return true;
230 return ParseToken(lltok::rsquare, "expected ']' at end of list");
235 bool LLParser::ParseUnnamedType() {
236 assert(Lex.getKind() == lltok::kw_type);
237 LocTy TypeLoc = Lex.getLoc();
238 Lex.Lex(); // eat kw_type
240 PATypeHolder Ty(Type::VoidTy);
241 if (ParseType(Ty)) return true;
243 unsigned TypeID = NumberedTypes.size();
245 // See if this type was previously referenced.
246 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
247 FI = ForwardRefTypeIDs.find(TypeID);
248 if (FI != ForwardRefTypeIDs.end()) {
249 if (FI->second.first.get() == Ty)
250 return Error(TypeLoc, "self referential type is invalid");
252 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
253 Ty = FI->second.first.get();
254 ForwardRefTypeIDs.erase(FI);
257 NumberedTypes.push_back(Ty);
263 /// ::= LocalVar '=' 'type' type
264 bool LLParser::ParseNamedType() {
265 std::string Name = Lex.getStrVal();
266 LocTy NameLoc = Lex.getLoc();
267 Lex.Lex(); // eat LocalVar.
269 PATypeHolder Ty(Type::VoidTy);
271 if (ParseToken(lltok::equal, "expected '=' after name") ||
272 ParseToken(lltok::kw_type, "expected 'type' after name") ||
276 // Set the type name, checking for conflicts as we do so.
277 bool AlreadyExists = M->addTypeName(Name, Ty);
278 if (!AlreadyExists) return false;
280 // See if this type is a forward reference. We need to eagerly resolve
281 // types to allow recursive type redefinitions below.
282 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
283 FI = ForwardRefTypes.find(Name);
284 if (FI != ForwardRefTypes.end()) {
285 if (FI->second.first.get() == Ty)
286 return Error(NameLoc, "self referential type is invalid");
288 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
289 Ty = FI->second.first.get();
290 ForwardRefTypes.erase(FI);
293 // Inserting a name that is already defined, get the existing name.
294 const Type *Existing = M->getTypeByName(Name);
295 assert(Existing && "Conflict but no matching type?!");
297 // Otherwise, this is an attempt to redefine a type. That's okay if
298 // the redefinition is identical to the original.
299 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
300 if (Existing == Ty) return false;
302 // Any other kind of (non-equivalent) redefinition is an error.
303 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
304 Ty->getDescription() + "'");
309 /// ::= 'declare' FunctionHeader
310 bool LLParser::ParseDeclare() {
311 assert(Lex.getKind() == lltok::kw_declare);
315 return ParseFunctionHeader(F, false);
319 /// ::= 'define' FunctionHeader '{' ...
320 bool LLParser::ParseDefine() {
321 assert(Lex.getKind() == lltok::kw_define);
325 return ParseFunctionHeader(F, true) ||
326 ParseFunctionBody(*F);
332 bool LLParser::ParseGlobalType(bool &IsConstant) {
333 if (Lex.getKind() == lltok::kw_constant)
335 else if (Lex.getKind() == lltok::kw_global)
339 return TokError("expected 'global' or 'constant'");
345 /// ParseNamedGlobal:
346 /// GlobalVar '=' OptionalVisibility ALIAS ...
347 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
348 bool LLParser::ParseNamedGlobal() {
349 assert(Lex.getKind() == lltok::GlobalVar);
350 LocTy NameLoc = Lex.getLoc();
351 std::string Name = Lex.getStrVal();
355 unsigned Linkage, Visibility;
356 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
357 ParseOptionalLinkage(Linkage, HasLinkage) ||
358 ParseOptionalVisibility(Visibility))
361 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
362 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
363 return ParseAlias(Name, NameLoc, Visibility);
366 /// ParseStandaloneMetadata:
368 bool LLParser::ParseStandaloneMetadata() {
369 assert(Lex.getKind() == lltok::Metadata);
371 unsigned MetadataID = 0;
372 if (ParseUInt32(MetadataID))
374 if (MetadataCache.find(MetadataID) != MetadataCache.end())
375 return TokError("Metadata id is already used");
376 if (ParseToken(lltok::equal, "expected '=' here"))
380 PATypeHolder Ty(Type::VoidTy);
381 if (ParseType(Ty, TyLoc))
385 if (ParseGlobalValue(Ty, Init))
388 MetadataCache[MetadataID] = Init;
389 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
390 FI = ForwardRefMDNodes.find(MetadataID);
391 if (FI != ForwardRefMDNodes.end()) {
392 Constant *FwdNode = FI->second.first;
393 FwdNode->replaceAllUsesWith(Init);
394 ForwardRefMDNodes.erase(FI);
401 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
404 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
405 /// ::= 'getelementptr' '(' ... ')'
407 /// Everything through visibility has already been parsed.
409 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
410 unsigned Visibility) {
411 assert(Lex.getKind() == lltok::kw_alias);
414 LocTy LinkageLoc = Lex.getLoc();
415 if (ParseOptionalLinkage(Linkage))
418 if (Linkage != GlobalValue::ExternalLinkage &&
419 Linkage != GlobalValue::WeakAnyLinkage &&
420 Linkage != GlobalValue::WeakODRLinkage &&
421 Linkage != GlobalValue::InternalLinkage &&
422 Linkage != GlobalValue::PrivateLinkage)
423 return Error(LinkageLoc, "invalid linkage type for alias");
426 LocTy AliaseeLoc = Lex.getLoc();
427 if (Lex.getKind() != lltok::kw_bitcast &&
428 Lex.getKind() != lltok::kw_getelementptr) {
429 if (ParseGlobalTypeAndValue(Aliasee)) return true;
431 // The bitcast dest type is not present, it is implied by the dest type.
433 if (ParseValID(ID)) return true;
434 if (ID.Kind != ValID::t_Constant)
435 return Error(AliaseeLoc, "invalid aliasee");
436 Aliasee = ID.ConstantVal;
439 if (!isa<PointerType>(Aliasee->getType()))
440 return Error(AliaseeLoc, "alias must have pointer type");
442 // Okay, create the alias but do not insert it into the module yet.
443 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
444 (GlobalValue::LinkageTypes)Linkage, Name,
446 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
448 // See if this value already exists in the symbol table. If so, it is either
449 // a redefinition or a definition of a forward reference.
450 if (GlobalValue *Val =
451 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
452 // See if this was a redefinition. If so, there is no entry in
454 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
455 I = ForwardRefVals.find(Name);
456 if (I == ForwardRefVals.end())
457 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
459 // Otherwise, this was a definition of forward ref. Verify that types
461 if (Val->getType() != GA->getType())
462 return Error(NameLoc,
463 "forward reference and definition of alias have different types");
465 // If they agree, just RAUW the old value with the alias and remove the
467 Val->replaceAllUsesWith(GA);
468 Val->eraseFromParent();
469 ForwardRefVals.erase(I);
472 // Insert into the module, we know its name won't collide now.
473 M->getAliasList().push_back(GA);
474 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
480 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
481 /// OptionalAddrSpace GlobalType Type Const
482 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
483 /// OptionalAddrSpace GlobalType Type Const
485 /// Everything through visibility has been parsed already.
487 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
488 unsigned Linkage, bool HasLinkage,
489 unsigned Visibility) {
491 bool ThreadLocal, IsConstant;
494 PATypeHolder Ty(Type::VoidTy);
495 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
496 ParseOptionalAddrSpace(AddrSpace) ||
497 ParseGlobalType(IsConstant) ||
498 ParseType(Ty, TyLoc))
501 // If the linkage is specified and is external, then no initializer is
504 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
505 Linkage != GlobalValue::ExternalWeakLinkage &&
506 Linkage != GlobalValue::ExternalLinkage)) {
507 if (ParseGlobalValue(Ty, Init))
511 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
512 return Error(TyLoc, "invalid type for global variable");
514 GlobalVariable *GV = 0;
516 // See if the global was forward referenced, if so, use the global.
518 if ((GV = M->getGlobalVariable(Name, true)) &&
519 !ForwardRefVals.erase(Name))
520 return Error(NameLoc, "redefinition of global '@" + Name + "'");
522 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
523 I = ForwardRefValIDs.find(NumberedVals.size());
524 if (I != ForwardRefValIDs.end()) {
525 GV = cast<GlobalVariable>(I->second.first);
526 ForwardRefValIDs.erase(I);
531 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
532 Name, 0, false, AddrSpace);
534 if (GV->getType()->getElementType() != Ty)
536 "forward reference and definition of global have different types");
538 // Move the forward-reference to the correct spot in the module.
539 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
543 NumberedVals.push_back(GV);
545 // Set the parsed properties on the global.
547 GV->setInitializer(Init);
548 GV->setConstant(IsConstant);
549 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
550 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
551 GV->setThreadLocal(ThreadLocal);
553 // Parse attributes on the global.
554 while (Lex.getKind() == lltok::comma) {
557 if (Lex.getKind() == lltok::kw_section) {
559 GV->setSection(Lex.getStrVal());
560 if (ParseToken(lltok::StringConstant, "expected global section string"))
562 } else if (Lex.getKind() == lltok::kw_align) {
564 if (ParseOptionalAlignment(Alignment)) return true;
565 GV->setAlignment(Alignment);
567 TokError("unknown global variable property!");
575 //===----------------------------------------------------------------------===//
576 // GlobalValue Reference/Resolution Routines.
577 //===----------------------------------------------------------------------===//
579 /// GetGlobalVal - Get a value with the specified name or ID, creating a
580 /// forward reference record if needed. This can return null if the value
581 /// exists but does not have the right type.
582 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
584 const PointerType *PTy = dyn_cast<PointerType>(Ty);
586 Error(Loc, "global variable reference must have pointer type");
590 // Look this name up in the normal function symbol table.
592 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
594 // If this is a forward reference for the value, see if we already created a
595 // forward ref record.
597 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
598 I = ForwardRefVals.find(Name);
599 if (I != ForwardRefVals.end())
600 Val = I->second.first;
603 // If we have the value in the symbol table or fwd-ref table, return it.
605 if (Val->getType() == Ty) return Val;
606 Error(Loc, "'@" + Name + "' defined with type '" +
607 Val->getType()->getDescription() + "'");
611 // Otherwise, create a new forward reference for this value and remember it.
613 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
614 // Function types can return opaque but functions can't.
615 if (isa<OpaqueType>(FT->getReturnType())) {
616 Error(Loc, "function may not return opaque type");
620 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
622 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
623 GlobalValue::ExternalWeakLinkage, 0, Name);
626 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
630 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
631 const PointerType *PTy = dyn_cast<PointerType>(Ty);
633 Error(Loc, "global variable reference must have pointer type");
637 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
639 // If this is a forward reference for the value, see if we already created a
640 // forward ref record.
642 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
643 I = ForwardRefValIDs.find(ID);
644 if (I != ForwardRefValIDs.end())
645 Val = I->second.first;
648 // If we have the value in the symbol table or fwd-ref table, return it.
650 if (Val->getType() == Ty) return Val;
651 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
652 Val->getType()->getDescription() + "'");
656 // Otherwise, create a new forward reference for this value and remember it.
658 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
659 // Function types can return opaque but functions can't.
660 if (isa<OpaqueType>(FT->getReturnType())) {
661 Error(Loc, "function may not return opaque type");
664 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
666 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
667 GlobalValue::ExternalWeakLinkage, 0, "");
670 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
675 //===----------------------------------------------------------------------===//
677 //===----------------------------------------------------------------------===//
679 /// ParseToken - If the current token has the specified kind, eat it and return
680 /// success. Otherwise, emit the specified error and return failure.
681 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
682 if (Lex.getKind() != T)
683 return TokError(ErrMsg);
688 /// ParseStringConstant
689 /// ::= StringConstant
690 bool LLParser::ParseStringConstant(std::string &Result) {
691 if (Lex.getKind() != lltok::StringConstant)
692 return TokError("expected string constant");
693 Result = Lex.getStrVal();
700 bool LLParser::ParseUInt32(unsigned &Val) {
701 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
702 return TokError("expected integer");
703 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
704 if (Val64 != unsigned(Val64))
705 return TokError("expected 32-bit integer (too large)");
712 /// ParseOptionalAddrSpace
714 /// := 'addrspace' '(' uint32 ')'
715 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
717 if (!EatIfPresent(lltok::kw_addrspace))
719 return ParseToken(lltok::lparen, "expected '(' in address space") ||
720 ParseUInt32(AddrSpace) ||
721 ParseToken(lltok::rparen, "expected ')' in address space");
724 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
725 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
726 /// 2: function attr.
727 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
728 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
729 Attrs = Attribute::None;
730 LocTy AttrLoc = Lex.getLoc();
733 switch (Lex.getKind()) {
736 // Treat these as signext/zeroext if they occur in the argument list after
737 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
738 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
740 // FIXME: REMOVE THIS IN LLVM 3.0
742 if (Lex.getKind() == lltok::kw_sext)
743 Attrs |= Attribute::SExt;
745 Attrs |= Attribute::ZExt;
749 default: // End of attributes.
750 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
751 return Error(AttrLoc, "invalid use of function-only attribute");
753 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
754 return Error(AttrLoc, "invalid use of parameter-only attribute");
757 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
758 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
759 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
760 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
761 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
762 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
763 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
764 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
766 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
767 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
768 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
769 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
770 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
771 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
772 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
773 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
774 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
775 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
776 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
778 case lltok::kw_align: {
780 if (ParseOptionalAlignment(Alignment))
782 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
790 /// ParseOptionalLinkage
797 /// ::= 'linkonce_odr'
802 /// ::= 'extern_weak'
804 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
806 switch (Lex.getKind()) {
807 default: Res = GlobalValue::ExternalLinkage; return false;
808 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
809 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
810 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
811 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
812 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
813 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
814 case lltok::kw_available_externally:
815 Res = GlobalValue::AvailableExternallyLinkage;
817 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
818 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
819 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
820 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
821 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
822 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
829 /// ParseOptionalVisibility
835 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
836 switch (Lex.getKind()) {
837 default: Res = GlobalValue::DefaultVisibility; return false;
838 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
839 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
840 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
846 /// ParseOptionalCallingConv
851 /// ::= 'x86_stdcallcc'
852 /// ::= 'x86_fastcallcc'
854 /// ::= 'arm_aapcscc'
855 /// ::= 'arm_aapcs_vfpcc'
858 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
859 switch (Lex.getKind()) {
860 default: CC = CallingConv::C; return false;
861 case lltok::kw_ccc: CC = CallingConv::C; break;
862 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
863 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
864 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
865 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
866 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
867 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
868 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
869 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
875 /// ParseOptionalAlignment
878 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
880 if (!EatIfPresent(lltok::kw_align))
882 LocTy AlignLoc = Lex.getLoc();
883 if (ParseUInt32(Alignment)) return true;
884 if (!isPowerOf2_32(Alignment))
885 return Error(AlignLoc, "alignment is not a power of two");
889 /// ParseOptionalCommaAlignment
891 /// ::= ',' 'align' 4
892 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
894 if (!EatIfPresent(lltok::comma))
896 return ParseToken(lltok::kw_align, "expected 'align'") ||
897 ParseUInt32(Alignment);
901 /// ::= (',' uint32)+
902 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
903 if (Lex.getKind() != lltok::comma)
904 return TokError("expected ',' as start of index list");
906 while (EatIfPresent(lltok::comma)) {
908 if (ParseUInt32(Idx)) return true;
909 Indices.push_back(Idx);
915 //===----------------------------------------------------------------------===//
917 //===----------------------------------------------------------------------===//
919 /// ParseType - Parse and resolve a full type.
920 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
921 LocTy TypeLoc = Lex.getLoc();
922 if (ParseTypeRec(Result)) return true;
924 // Verify no unresolved uprefs.
926 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
928 if (!AllowVoid && Result.get() == Type::VoidTy)
929 return Error(TypeLoc, "void type only allowed for function results");
934 /// HandleUpRefs - Every time we finish a new layer of types, this function is
935 /// called. It loops through the UpRefs vector, which is a list of the
936 /// currently active types. For each type, if the up-reference is contained in
937 /// the newly completed type, we decrement the level count. When the level
938 /// count reaches zero, the up-referenced type is the type that is passed in:
939 /// thus we can complete the cycle.
941 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
942 // If Ty isn't abstract, or if there are no up-references in it, then there is
943 // nothing to resolve here.
944 if (!ty->isAbstract() || UpRefs.empty()) return ty;
948 errs() << "Type '" << Ty->getDescription()
949 << "' newly formed. Resolving upreferences.\n"
950 << UpRefs.size() << " upreferences active!\n";
953 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
954 // to zero), we resolve them all together before we resolve them to Ty. At
955 // the end of the loop, if there is anything to resolve to Ty, it will be in
957 OpaqueType *TypeToResolve = 0;
959 for (unsigned i = 0; i != UpRefs.size(); ++i) {
960 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
962 std::find(Ty->subtype_begin(), Ty->subtype_end(),
963 UpRefs[i].LastContainedTy) != Ty->subtype_end();
966 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
967 << UpRefs[i].LastContainedTy->getDescription() << ") = "
968 << (ContainsType ? "true" : "false")
969 << " level=" << UpRefs[i].NestingLevel << "\n";
974 // Decrement level of upreference
975 unsigned Level = --UpRefs[i].NestingLevel;
976 UpRefs[i].LastContainedTy = Ty;
978 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
983 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
986 TypeToResolve = UpRefs[i].UpRefTy;
988 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
989 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
990 --i; // Do not skip the next element.
994 TypeToResolve->refineAbstractTypeTo(Ty);
1000 /// ParseTypeRec - The recursive function used to process the internal
1001 /// implementation details of types.
1002 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1003 switch (Lex.getKind()) {
1005 return TokError("expected type");
1007 // TypeRec ::= 'float' | 'void' (etc)
1008 Result = Lex.getTyVal();
1011 case lltok::kw_opaque:
1012 // TypeRec ::= 'opaque'
1013 Result = Context.getOpaqueType();
1017 // TypeRec ::= '{' ... '}'
1018 if (ParseStructType(Result, false))
1021 case lltok::lsquare:
1022 // TypeRec ::= '[' ... ']'
1023 Lex.Lex(); // eat the lsquare.
1024 if (ParseArrayVectorType(Result, false))
1027 case lltok::less: // Either vector or packed struct.
1028 // TypeRec ::= '<' ... '>'
1030 if (Lex.getKind() == lltok::lbrace) {
1031 if (ParseStructType(Result, true) ||
1032 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1034 } else if (ParseArrayVectorType(Result, true))
1037 case lltok::LocalVar:
1038 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1040 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1043 Result = Context.getOpaqueType();
1044 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1045 std::make_pair(Result,
1047 M->addTypeName(Lex.getStrVal(), Result.get());
1052 case lltok::LocalVarID:
1054 if (Lex.getUIntVal() < NumberedTypes.size())
1055 Result = NumberedTypes[Lex.getUIntVal()];
1057 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1058 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1059 if (I != ForwardRefTypeIDs.end())
1060 Result = I->second.first;
1062 Result = Context.getOpaqueType();
1063 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1064 std::make_pair(Result,
1070 case lltok::backslash: {
1071 // TypeRec ::= '\' 4
1074 if (ParseUInt32(Val)) return true;
1075 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1076 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1082 // Parse the type suffixes.
1084 switch (Lex.getKind()) {
1086 default: return false;
1088 // TypeRec ::= TypeRec '*'
1090 if (Result.get() == Type::LabelTy)
1091 return TokError("basic block pointers are invalid");
1092 if (Result.get() == Type::VoidTy)
1093 return TokError("pointers to void are invalid; use i8* instead");
1094 if (!PointerType::isValidElementType(Result.get()))
1095 return TokError("pointer to this type is invalid");
1096 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1100 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1101 case lltok::kw_addrspace: {
1102 if (Result.get() == Type::LabelTy)
1103 return TokError("basic block pointers are invalid");
1104 if (Result.get() == Type::VoidTy)
1105 return TokError("pointers to void are invalid; use i8* instead");
1106 if (!PointerType::isValidElementType(Result.get()))
1107 return TokError("pointer to this type is invalid");
1109 if (ParseOptionalAddrSpace(AddrSpace) ||
1110 ParseToken(lltok::star, "expected '*' in address space"))
1113 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1117 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1119 if (ParseFunctionType(Result))
1126 /// ParseParameterList
1128 /// ::= '(' Arg (',' Arg)* ')'
1130 /// ::= Type OptionalAttributes Value OptionalAttributes
1131 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1132 PerFunctionState &PFS) {
1133 if (ParseToken(lltok::lparen, "expected '(' in call"))
1136 while (Lex.getKind() != lltok::rparen) {
1137 // If this isn't the first argument, we need a comma.
1138 if (!ArgList.empty() &&
1139 ParseToken(lltok::comma, "expected ',' in argument list"))
1142 // Parse the argument.
1144 PATypeHolder ArgTy(Type::VoidTy);
1145 unsigned ArgAttrs1, ArgAttrs2;
1147 if (ParseType(ArgTy, ArgLoc) ||
1148 ParseOptionalAttrs(ArgAttrs1, 0) ||
1149 ParseValue(ArgTy, V, PFS) ||
1150 // FIXME: Should not allow attributes after the argument, remove this in
1152 ParseOptionalAttrs(ArgAttrs2, 3))
1154 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1157 Lex.Lex(); // Lex the ')'.
1163 /// ParseArgumentList - Parse the argument list for a function type or function
1164 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1165 /// ::= '(' ArgTypeListI ')'
1169 /// ::= ArgTypeList ',' '...'
1170 /// ::= ArgType (',' ArgType)*
1172 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1173 bool &isVarArg, bool inType) {
1175 assert(Lex.getKind() == lltok::lparen);
1176 Lex.Lex(); // eat the (.
1178 if (Lex.getKind() == lltok::rparen) {
1180 } else if (Lex.getKind() == lltok::dotdotdot) {
1184 LocTy TypeLoc = Lex.getLoc();
1185 PATypeHolder ArgTy(Type::VoidTy);
1189 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1190 // types (such as a function returning a pointer to itself). If parsing a
1191 // function prototype, we require fully resolved types.
1192 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1193 ParseOptionalAttrs(Attrs, 0)) return true;
1195 if (ArgTy == Type::VoidTy)
1196 return Error(TypeLoc, "argument can not have void type");
1198 if (Lex.getKind() == lltok::LocalVar ||
1199 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1200 Name = Lex.getStrVal();
1204 if (!FunctionType::isValidArgumentType(ArgTy))
1205 return Error(TypeLoc, "invalid type for function argument");
1207 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1209 while (EatIfPresent(lltok::comma)) {
1210 // Handle ... at end of arg list.
1211 if (EatIfPresent(lltok::dotdotdot)) {
1216 // Otherwise must be an argument type.
1217 TypeLoc = Lex.getLoc();
1218 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1219 ParseOptionalAttrs(Attrs, 0)) return true;
1221 if (ArgTy == Type::VoidTy)
1222 return Error(TypeLoc, "argument can not have void type");
1224 if (Lex.getKind() == lltok::LocalVar ||
1225 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1226 Name = Lex.getStrVal();
1232 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1233 return Error(TypeLoc, "invalid type for function argument");
1235 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1239 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1242 /// ParseFunctionType
1243 /// ::= Type ArgumentList OptionalAttrs
1244 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1245 assert(Lex.getKind() == lltok::lparen);
1247 if (!FunctionType::isValidReturnType(Result))
1248 return TokError("invalid function return type");
1250 std::vector<ArgInfo> ArgList;
1253 if (ParseArgumentList(ArgList, isVarArg, true) ||
1254 // FIXME: Allow, but ignore attributes on function types!
1255 // FIXME: Remove in LLVM 3.0
1256 ParseOptionalAttrs(Attrs, 2))
1259 // Reject names on the arguments lists.
1260 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1261 if (!ArgList[i].Name.empty())
1262 return Error(ArgList[i].Loc, "argument name invalid in function type");
1263 if (!ArgList[i].Attrs != 0) {
1264 // Allow but ignore attributes on function types; this permits
1266 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1270 std::vector<const Type*> ArgListTy;
1271 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1272 ArgListTy.push_back(ArgList[i].Type);
1274 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1275 ArgListTy, isVarArg));
1279 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1282 /// ::= '{' TypeRec (',' TypeRec)* '}'
1283 /// ::= '<' '{' '}' '>'
1284 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1285 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1286 assert(Lex.getKind() == lltok::lbrace);
1287 Lex.Lex(); // Consume the '{'
1289 if (EatIfPresent(lltok::rbrace)) {
1290 Result = Context.getStructType(Packed);
1294 std::vector<PATypeHolder> ParamsList;
1295 LocTy EltTyLoc = Lex.getLoc();
1296 if (ParseTypeRec(Result)) return true;
1297 ParamsList.push_back(Result);
1299 if (Result == Type::VoidTy)
1300 return Error(EltTyLoc, "struct element can not have void type");
1301 if (!StructType::isValidElementType(Result))
1302 return Error(EltTyLoc, "invalid element type for struct");
1304 while (EatIfPresent(lltok::comma)) {
1305 EltTyLoc = Lex.getLoc();
1306 if (ParseTypeRec(Result)) return true;
1308 if (Result == Type::VoidTy)
1309 return Error(EltTyLoc, "struct element can not have void type");
1310 if (!StructType::isValidElementType(Result))
1311 return Error(EltTyLoc, "invalid element type for struct");
1313 ParamsList.push_back(Result);
1316 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1319 std::vector<const Type*> ParamsListTy;
1320 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1321 ParamsListTy.push_back(ParamsList[i].get());
1322 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1326 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1327 /// token has already been consumed.
1329 /// ::= '[' APSINTVAL 'x' Types ']'
1330 /// ::= '<' APSINTVAL 'x' Types '>'
1331 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1332 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1333 Lex.getAPSIntVal().getBitWidth() > 64)
1334 return TokError("expected number in address space");
1336 LocTy SizeLoc = Lex.getLoc();
1337 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1340 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1343 LocTy TypeLoc = Lex.getLoc();
1344 PATypeHolder EltTy(Type::VoidTy);
1345 if (ParseTypeRec(EltTy)) return true;
1347 if (EltTy == Type::VoidTy)
1348 return Error(TypeLoc, "array and vector element type cannot be void");
1350 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1351 "expected end of sequential type"))
1356 return Error(SizeLoc, "zero element vector is illegal");
1357 if ((unsigned)Size != Size)
1358 return Error(SizeLoc, "size too large for vector");
1359 if (!VectorType::isValidElementType(EltTy))
1360 return Error(TypeLoc, "vector element type must be fp or integer");
1361 Result = Context.getVectorType(EltTy, unsigned(Size));
1363 if (!ArrayType::isValidElementType(EltTy))
1364 return Error(TypeLoc, "invalid array element type");
1365 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1370 //===----------------------------------------------------------------------===//
1371 // Function Semantic Analysis.
1372 //===----------------------------------------------------------------------===//
1374 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1377 // Insert unnamed arguments into the NumberedVals list.
1378 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1381 NumberedVals.push_back(AI);
1384 LLParser::PerFunctionState::~PerFunctionState() {
1385 // If there were any forward referenced non-basicblock values, delete them.
1386 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1387 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1388 if (!isa<BasicBlock>(I->second.first)) {
1389 I->second.first->replaceAllUsesWith(
1390 P.getContext().getUndef(I->second.first->getType()));
1391 delete I->second.first;
1392 I->second.first = 0;
1395 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1396 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1397 if (!isa<BasicBlock>(I->second.first)) {
1398 I->second.first->replaceAllUsesWith(
1399 P.getContext().getUndef(I->second.first->getType()));
1400 delete I->second.first;
1401 I->second.first = 0;
1405 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1406 if (!ForwardRefVals.empty())
1407 return P.Error(ForwardRefVals.begin()->second.second,
1408 "use of undefined value '%" + ForwardRefVals.begin()->first +
1410 if (!ForwardRefValIDs.empty())
1411 return P.Error(ForwardRefValIDs.begin()->second.second,
1412 "use of undefined value '%" +
1413 utostr(ForwardRefValIDs.begin()->first) + "'");
1418 /// GetVal - Get a value with the specified name or ID, creating a
1419 /// forward reference record if needed. This can return null if the value
1420 /// exists but does not have the right type.
1421 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1422 const Type *Ty, LocTy Loc) {
1423 // Look this name up in the normal function symbol table.
1424 Value *Val = F.getValueSymbolTable().lookup(Name);
1426 // If this is a forward reference for the value, see if we already created a
1427 // forward ref record.
1429 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1430 I = ForwardRefVals.find(Name);
1431 if (I != ForwardRefVals.end())
1432 Val = I->second.first;
1435 // If we have the value in the symbol table or fwd-ref table, return it.
1437 if (Val->getType() == Ty) return Val;
1438 if (Ty == Type::LabelTy)
1439 P.Error(Loc, "'%" + Name + "' is not a basic block");
1441 P.Error(Loc, "'%" + Name + "' defined with type '" +
1442 Val->getType()->getDescription() + "'");
1446 // Don't make placeholders with invalid type.
1447 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1448 P.Error(Loc, "invalid use of a non-first-class type");
1452 // Otherwise, create a new forward reference for this value and remember it.
1454 if (Ty == Type::LabelTy)
1455 FwdVal = BasicBlock::Create(Name, &F);
1457 FwdVal = new Argument(Ty, Name);
1459 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1463 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1465 // Look this name up in the normal function symbol table.
1466 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1468 // If this is a forward reference for the value, see if we already created a
1469 // forward ref record.
1471 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1472 I = ForwardRefValIDs.find(ID);
1473 if (I != ForwardRefValIDs.end())
1474 Val = I->second.first;
1477 // If we have the value in the symbol table or fwd-ref table, return it.
1479 if (Val->getType() == Ty) return Val;
1480 if (Ty == Type::LabelTy)
1481 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1483 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1484 Val->getType()->getDescription() + "'");
1488 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1489 P.Error(Loc, "invalid use of a non-first-class type");
1493 // Otherwise, create a new forward reference for this value and remember it.
1495 if (Ty == Type::LabelTy)
1496 FwdVal = BasicBlock::Create("", &F);
1498 FwdVal = new Argument(Ty);
1500 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1504 /// SetInstName - After an instruction is parsed and inserted into its
1505 /// basic block, this installs its name.
1506 bool LLParser::PerFunctionState::SetInstName(int NameID,
1507 const std::string &NameStr,
1508 LocTy NameLoc, Instruction *Inst) {
1509 // If this instruction has void type, it cannot have a name or ID specified.
1510 if (Inst->getType() == Type::VoidTy) {
1511 if (NameID != -1 || !NameStr.empty())
1512 return P.Error(NameLoc, "instructions returning void cannot have a name");
1516 // If this was a numbered instruction, verify that the instruction is the
1517 // expected value and resolve any forward references.
1518 if (NameStr.empty()) {
1519 // If neither a name nor an ID was specified, just use the next ID.
1521 NameID = NumberedVals.size();
1523 if (unsigned(NameID) != NumberedVals.size())
1524 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1525 utostr(NumberedVals.size()) + "'");
1527 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1528 ForwardRefValIDs.find(NameID);
1529 if (FI != ForwardRefValIDs.end()) {
1530 if (FI->second.first->getType() != Inst->getType())
1531 return P.Error(NameLoc, "instruction forward referenced with type '" +
1532 FI->second.first->getType()->getDescription() + "'");
1533 FI->second.first->replaceAllUsesWith(Inst);
1534 ForwardRefValIDs.erase(FI);
1537 NumberedVals.push_back(Inst);
1541 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1542 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1543 FI = ForwardRefVals.find(NameStr);
1544 if (FI != ForwardRefVals.end()) {
1545 if (FI->second.first->getType() != Inst->getType())
1546 return P.Error(NameLoc, "instruction forward referenced with type '" +
1547 FI->second.first->getType()->getDescription() + "'");
1548 FI->second.first->replaceAllUsesWith(Inst);
1549 ForwardRefVals.erase(FI);
1552 // Set the name on the instruction.
1553 Inst->setName(NameStr);
1555 if (Inst->getNameStr() != NameStr)
1556 return P.Error(NameLoc, "multiple definition of local value named '" +
1561 /// GetBB - Get a basic block with the specified name or ID, creating a
1562 /// forward reference record if needed.
1563 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1565 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1568 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1569 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1572 /// DefineBB - Define the specified basic block, which is either named or
1573 /// unnamed. If there is an error, this returns null otherwise it returns
1574 /// the block being defined.
1575 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1579 BB = GetBB(NumberedVals.size(), Loc);
1581 BB = GetBB(Name, Loc);
1582 if (BB == 0) return 0; // Already diagnosed error.
1584 // Move the block to the end of the function. Forward ref'd blocks are
1585 // inserted wherever they happen to be referenced.
1586 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1588 // Remove the block from forward ref sets.
1590 ForwardRefValIDs.erase(NumberedVals.size());
1591 NumberedVals.push_back(BB);
1593 // BB forward references are already in the function symbol table.
1594 ForwardRefVals.erase(Name);
1600 //===----------------------------------------------------------------------===//
1602 //===----------------------------------------------------------------------===//
1604 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1605 /// type implied. For example, if we parse "4" we don't know what integer type
1606 /// it has. The value will later be combined with its type and checked for
1608 bool LLParser::ParseValID(ValID &ID) {
1609 ID.Loc = Lex.getLoc();
1610 switch (Lex.getKind()) {
1611 default: return TokError("expected value token");
1612 case lltok::GlobalID: // @42
1613 ID.UIntVal = Lex.getUIntVal();
1614 ID.Kind = ValID::t_GlobalID;
1616 case lltok::GlobalVar: // @foo
1617 ID.StrVal = Lex.getStrVal();
1618 ID.Kind = ValID::t_GlobalName;
1620 case lltok::LocalVarID: // %42
1621 ID.UIntVal = Lex.getUIntVal();
1622 ID.Kind = ValID::t_LocalID;
1624 case lltok::LocalVar: // %foo
1625 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1626 ID.StrVal = Lex.getStrVal();
1627 ID.Kind = ValID::t_LocalName;
1629 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1630 ID.Kind = ValID::t_Constant;
1632 if (Lex.getKind() == lltok::lbrace) {
1633 SmallVector<Value*, 16> Elts;
1634 if (ParseMDNodeVector(Elts) ||
1635 ParseToken(lltok::rbrace, "expected end of metadata node"))
1638 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1642 // Standalone metadata reference
1643 // !{ ..., !42, ... }
1645 if (!ParseUInt32(MID)) {
1646 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1647 if (I != MetadataCache.end())
1648 ID.ConstantVal = I->second;
1650 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
1651 FI = ForwardRefMDNodes.find(MID);
1652 if (FI != ForwardRefMDNodes.end())
1653 ID.ConstantVal = FI->second.first;
1655 // Create MDNode forward reference
1656 SmallVector<Value *, 1> Elts;
1657 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
1658 Elts.push_back(Context.getMDString(FwdRefName));
1659 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
1660 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
1661 ID.ConstantVal = FwdNode;
1669 // ::= '!' STRINGCONSTANT
1671 if (ParseStringConstant(Str)) return true;
1673 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
1677 ID.APSIntVal = Lex.getAPSIntVal();
1678 ID.Kind = ValID::t_APSInt;
1680 case lltok::APFloat:
1681 ID.APFloatVal = Lex.getAPFloatVal();
1682 ID.Kind = ValID::t_APFloat;
1684 case lltok::kw_true:
1685 ID.ConstantVal = Context.getConstantIntTrue();
1686 ID.Kind = ValID::t_Constant;
1688 case lltok::kw_false:
1689 ID.ConstantVal = Context.getConstantIntFalse();
1690 ID.Kind = ValID::t_Constant;
1692 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1693 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1694 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1696 case lltok::lbrace: {
1697 // ValID ::= '{' ConstVector '}'
1699 SmallVector<Constant*, 16> Elts;
1700 if (ParseGlobalValueVector(Elts) ||
1701 ParseToken(lltok::rbrace, "expected end of struct constant"))
1704 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1705 ID.Kind = ValID::t_Constant;
1709 // ValID ::= '<' ConstVector '>' --> Vector.
1710 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1712 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1714 SmallVector<Constant*, 16> Elts;
1715 LocTy FirstEltLoc = Lex.getLoc();
1716 if (ParseGlobalValueVector(Elts) ||
1718 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1719 ParseToken(lltok::greater, "expected end of constant"))
1722 if (isPackedStruct) {
1724 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1725 ID.Kind = ValID::t_Constant;
1730 return Error(ID.Loc, "constant vector must not be empty");
1732 if (!Elts[0]->getType()->isInteger() &&
1733 !Elts[0]->getType()->isFloatingPoint())
1734 return Error(FirstEltLoc,
1735 "vector elements must have integer or floating point type");
1737 // Verify that all the vector elements have the same type.
1738 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1739 if (Elts[i]->getType() != Elts[0]->getType())
1740 return Error(FirstEltLoc,
1741 "vector element #" + utostr(i) +
1742 " is not of type '" + Elts[0]->getType()->getDescription());
1744 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1745 ID.Kind = ValID::t_Constant;
1748 case lltok::lsquare: { // Array Constant
1750 SmallVector<Constant*, 16> Elts;
1751 LocTy FirstEltLoc = Lex.getLoc();
1752 if (ParseGlobalValueVector(Elts) ||
1753 ParseToken(lltok::rsquare, "expected end of array constant"))
1756 // Handle empty element.
1758 // Use undef instead of an array because it's inconvenient to determine
1759 // the element type at this point, there being no elements to examine.
1760 ID.Kind = ValID::t_EmptyArray;
1764 if (!Elts[0]->getType()->isFirstClassType())
1765 return Error(FirstEltLoc, "invalid array element type: " +
1766 Elts[0]->getType()->getDescription());
1768 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1770 // Verify all elements are correct type!
1771 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1772 if (Elts[i]->getType() != Elts[0]->getType())
1773 return Error(FirstEltLoc,
1774 "array element #" + utostr(i) +
1775 " is not of type '" +Elts[0]->getType()->getDescription());
1778 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1779 ID.Kind = ValID::t_Constant;
1782 case lltok::kw_c: // c "foo"
1784 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1785 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1786 ID.Kind = ValID::t_Constant;
1789 case lltok::kw_asm: {
1790 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1793 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1794 ParseStringConstant(ID.StrVal) ||
1795 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1796 ParseToken(lltok::StringConstant, "expected constraint string"))
1798 ID.StrVal2 = Lex.getStrVal();
1799 ID.UIntVal = HasSideEffect;
1800 ID.Kind = ValID::t_InlineAsm;
1804 case lltok::kw_trunc:
1805 case lltok::kw_zext:
1806 case lltok::kw_sext:
1807 case lltok::kw_fptrunc:
1808 case lltok::kw_fpext:
1809 case lltok::kw_bitcast:
1810 case lltok::kw_uitofp:
1811 case lltok::kw_sitofp:
1812 case lltok::kw_fptoui:
1813 case lltok::kw_fptosi:
1814 case lltok::kw_inttoptr:
1815 case lltok::kw_ptrtoint: {
1816 unsigned Opc = Lex.getUIntVal();
1817 PATypeHolder DestTy(Type::VoidTy);
1820 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1821 ParseGlobalTypeAndValue(SrcVal) ||
1822 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1823 ParseType(DestTy) ||
1824 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1826 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1827 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1828 SrcVal->getType()->getDescription() + "' to '" +
1829 DestTy->getDescription() + "'");
1830 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1832 ID.Kind = ValID::t_Constant;
1835 case lltok::kw_extractvalue: {
1838 SmallVector<unsigned, 4> Indices;
1839 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1840 ParseGlobalTypeAndValue(Val) ||
1841 ParseIndexList(Indices) ||
1842 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1844 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1845 return Error(ID.Loc, "extractvalue operand must be array or struct");
1846 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1848 return Error(ID.Loc, "invalid indices for extractvalue");
1850 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1851 ID.Kind = ValID::t_Constant;
1854 case lltok::kw_insertvalue: {
1856 Constant *Val0, *Val1;
1857 SmallVector<unsigned, 4> Indices;
1858 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1859 ParseGlobalTypeAndValue(Val0) ||
1860 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1861 ParseGlobalTypeAndValue(Val1) ||
1862 ParseIndexList(Indices) ||
1863 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1865 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1866 return Error(ID.Loc, "extractvalue operand must be array or struct");
1867 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1869 return Error(ID.Loc, "invalid indices for insertvalue");
1870 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1871 Indices.data(), Indices.size());
1872 ID.Kind = ValID::t_Constant;
1875 case lltok::kw_icmp:
1876 case lltok::kw_fcmp: {
1877 unsigned PredVal, Opc = Lex.getUIntVal();
1878 Constant *Val0, *Val1;
1880 if (ParseCmpPredicate(PredVal, Opc) ||
1881 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1882 ParseGlobalTypeAndValue(Val0) ||
1883 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1884 ParseGlobalTypeAndValue(Val1) ||
1885 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1888 if (Val0->getType() != Val1->getType())
1889 return Error(ID.Loc, "compare operands must have the same type");
1891 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1893 if (Opc == Instruction::FCmp) {
1894 if (!Val0->getType()->isFPOrFPVector())
1895 return Error(ID.Loc, "fcmp requires floating point operands");
1896 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1898 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1899 if (!Val0->getType()->isIntOrIntVector() &&
1900 !isa<PointerType>(Val0->getType()))
1901 return Error(ID.Loc, "icmp requires pointer or integer operands");
1902 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1904 ID.Kind = ValID::t_Constant;
1908 // Binary Operators.
1910 case lltok::kw_fadd:
1912 case lltok::kw_fsub:
1914 case lltok::kw_fmul:
1915 case lltok::kw_udiv:
1916 case lltok::kw_sdiv:
1917 case lltok::kw_fdiv:
1918 case lltok::kw_urem:
1919 case lltok::kw_srem:
1920 case lltok::kw_frem: {
1921 unsigned Opc = Lex.getUIntVal();
1922 Constant *Val0, *Val1;
1924 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1925 ParseGlobalTypeAndValue(Val0) ||
1926 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1927 ParseGlobalTypeAndValue(Val1) ||
1928 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1930 if (Val0->getType() != Val1->getType())
1931 return Error(ID.Loc, "operands of constexpr must have same type");
1932 if (!Val0->getType()->isIntOrIntVector() &&
1933 !Val0->getType()->isFPOrFPVector())
1934 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1935 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1936 ID.Kind = ValID::t_Constant;
1940 // Logical Operations
1942 case lltok::kw_lshr:
1943 case lltok::kw_ashr:
1946 case lltok::kw_xor: {
1947 unsigned Opc = Lex.getUIntVal();
1948 Constant *Val0, *Val1;
1950 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1951 ParseGlobalTypeAndValue(Val0) ||
1952 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1953 ParseGlobalTypeAndValue(Val1) ||
1954 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1956 if (Val0->getType() != Val1->getType())
1957 return Error(ID.Loc, "operands of constexpr must have same type");
1958 if (!Val0->getType()->isIntOrIntVector())
1959 return Error(ID.Loc,
1960 "constexpr requires integer or integer vector operands");
1961 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1962 ID.Kind = ValID::t_Constant;
1966 case lltok::kw_getelementptr:
1967 case lltok::kw_shufflevector:
1968 case lltok::kw_insertelement:
1969 case lltok::kw_extractelement:
1970 case lltok::kw_select: {
1971 unsigned Opc = Lex.getUIntVal();
1972 SmallVector<Constant*, 16> Elts;
1974 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1975 ParseGlobalValueVector(Elts) ||
1976 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1979 if (Opc == Instruction::GetElementPtr) {
1980 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1981 return Error(ID.Loc, "getelementptr requires pointer operand");
1983 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1984 (Value**)&Elts[1], Elts.size()-1))
1985 return Error(ID.Loc, "invalid indices for getelementptr");
1986 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
1987 &Elts[1], Elts.size()-1);
1988 } else if (Opc == Instruction::Select) {
1989 if (Elts.size() != 3)
1990 return Error(ID.Loc, "expected three operands to select");
1991 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1993 return Error(ID.Loc, Reason);
1994 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
1995 } else if (Opc == Instruction::ShuffleVector) {
1996 if (Elts.size() != 3)
1997 return Error(ID.Loc, "expected three operands to shufflevector");
1998 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1999 return Error(ID.Loc, "invalid operands to shufflevector");
2001 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2002 } else if (Opc == Instruction::ExtractElement) {
2003 if (Elts.size() != 2)
2004 return Error(ID.Loc, "expected two operands to extractelement");
2005 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2006 return Error(ID.Loc, "invalid extractelement operands");
2007 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2009 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2010 if (Elts.size() != 3)
2011 return Error(ID.Loc, "expected three operands to insertelement");
2012 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2013 return Error(ID.Loc, "invalid insertelement operands");
2015 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2018 ID.Kind = ValID::t_Constant;
2027 /// ParseGlobalValue - Parse a global value with the specified type.
2028 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2031 return ParseValID(ID) ||
2032 ConvertGlobalValIDToValue(Ty, ID, V);
2035 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2037 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2039 if (isa<FunctionType>(Ty))
2040 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2043 default: assert(0 && "Unknown ValID!");
2044 case ValID::t_LocalID:
2045 case ValID::t_LocalName:
2046 return Error(ID.Loc, "invalid use of function-local name");
2047 case ValID::t_InlineAsm:
2048 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2049 case ValID::t_GlobalName:
2050 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2052 case ValID::t_GlobalID:
2053 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2055 case ValID::t_APSInt:
2056 if (!isa<IntegerType>(Ty))
2057 return Error(ID.Loc, "integer constant must have integer type");
2058 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2059 V = Context.getConstantInt(ID.APSIntVal);
2061 case ValID::t_APFloat:
2062 if (!Ty->isFloatingPoint() ||
2063 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2064 return Error(ID.Loc, "floating point constant invalid for type");
2066 // The lexer has no type info, so builds all float and double FP constants
2067 // as double. Fix this here. Long double does not need this.
2068 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2069 Ty == Type::FloatTy) {
2071 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2074 V = Context.getConstantFP(ID.APFloatVal);
2076 if (V->getType() != Ty)
2077 return Error(ID.Loc, "floating point constant does not have type '" +
2078 Ty->getDescription() + "'");
2082 if (!isa<PointerType>(Ty))
2083 return Error(ID.Loc, "null must be a pointer type");
2084 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2086 case ValID::t_Undef:
2087 // FIXME: LabelTy should not be a first-class type.
2088 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2089 !isa<OpaqueType>(Ty))
2090 return Error(ID.Loc, "invalid type for undef constant");
2091 V = Context.getUndef(Ty);
2093 case ValID::t_EmptyArray:
2094 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2095 return Error(ID.Loc, "invalid empty array initializer");
2096 V = Context.getUndef(Ty);
2099 // FIXME: LabelTy should not be a first-class type.
2100 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2101 return Error(ID.Loc, "invalid type for null constant");
2102 V = Context.getNullValue(Ty);
2104 case ValID::t_Constant:
2105 if (ID.ConstantVal->getType() != Ty)
2106 return Error(ID.Loc, "constant expression type mismatch");
2112 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2113 PATypeHolder Type(Type::VoidTy);
2114 return ParseType(Type) ||
2115 ParseGlobalValue(Type, V);
2118 /// ParseGlobalValueVector
2120 /// ::= TypeAndValue (',' TypeAndValue)*
2121 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2123 if (Lex.getKind() == lltok::rbrace ||
2124 Lex.getKind() == lltok::rsquare ||
2125 Lex.getKind() == lltok::greater ||
2126 Lex.getKind() == lltok::rparen)
2130 if (ParseGlobalTypeAndValue(C)) return true;
2133 while (EatIfPresent(lltok::comma)) {
2134 if (ParseGlobalTypeAndValue(C)) return true;
2142 //===----------------------------------------------------------------------===//
2143 // Function Parsing.
2144 //===----------------------------------------------------------------------===//
2146 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2147 PerFunctionState &PFS) {
2148 if (ID.Kind == ValID::t_LocalID)
2149 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2150 else if (ID.Kind == ValID::t_LocalName)
2151 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2152 else if (ID.Kind == ValID::t_InlineAsm) {
2153 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2154 const FunctionType *FTy =
2155 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2156 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2157 return Error(ID.Loc, "invalid type for inline asm constraint string");
2158 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2162 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2170 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2173 return ParseValID(ID) ||
2174 ConvertValIDToValue(Ty, ID, V, PFS);
2177 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2178 PATypeHolder T(Type::VoidTy);
2179 return ParseType(T) ||
2180 ParseValue(T, V, PFS);
2184 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2185 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2186 /// OptionalAlign OptGC
2187 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2188 // Parse the linkage.
2189 LocTy LinkageLoc = Lex.getLoc();
2192 unsigned Visibility, CC, RetAttrs;
2193 PATypeHolder RetType(Type::VoidTy);
2194 LocTy RetTypeLoc = Lex.getLoc();
2195 if (ParseOptionalLinkage(Linkage) ||
2196 ParseOptionalVisibility(Visibility) ||
2197 ParseOptionalCallingConv(CC) ||
2198 ParseOptionalAttrs(RetAttrs, 1) ||
2199 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2202 // Verify that the linkage is ok.
2203 switch ((GlobalValue::LinkageTypes)Linkage) {
2204 case GlobalValue::ExternalLinkage:
2205 break; // always ok.
2206 case GlobalValue::DLLImportLinkage:
2207 case GlobalValue::ExternalWeakLinkage:
2209 return Error(LinkageLoc, "invalid linkage for function definition");
2211 case GlobalValue::PrivateLinkage:
2212 case GlobalValue::InternalLinkage:
2213 case GlobalValue::AvailableExternallyLinkage:
2214 case GlobalValue::LinkOnceAnyLinkage:
2215 case GlobalValue::LinkOnceODRLinkage:
2216 case GlobalValue::WeakAnyLinkage:
2217 case GlobalValue::WeakODRLinkage:
2218 case GlobalValue::DLLExportLinkage:
2220 return Error(LinkageLoc, "invalid linkage for function declaration");
2222 case GlobalValue::AppendingLinkage:
2223 case GlobalValue::GhostLinkage:
2224 case GlobalValue::CommonLinkage:
2225 return Error(LinkageLoc, "invalid function linkage type");
2228 if (!FunctionType::isValidReturnType(RetType) ||
2229 isa<OpaqueType>(RetType))
2230 return Error(RetTypeLoc, "invalid function return type");
2232 LocTy NameLoc = Lex.getLoc();
2234 std::string FunctionName;
2235 if (Lex.getKind() == lltok::GlobalVar) {
2236 FunctionName = Lex.getStrVal();
2237 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2238 unsigned NameID = Lex.getUIntVal();
2240 if (NameID != NumberedVals.size())
2241 return TokError("function expected to be numbered '%" +
2242 utostr(NumberedVals.size()) + "'");
2244 return TokError("expected function name");
2249 if (Lex.getKind() != lltok::lparen)
2250 return TokError("expected '(' in function argument list");
2252 std::vector<ArgInfo> ArgList;
2255 std::string Section;
2259 if (ParseArgumentList(ArgList, isVarArg, false) ||
2260 ParseOptionalAttrs(FuncAttrs, 2) ||
2261 (EatIfPresent(lltok::kw_section) &&
2262 ParseStringConstant(Section)) ||
2263 ParseOptionalAlignment(Alignment) ||
2264 (EatIfPresent(lltok::kw_gc) &&
2265 ParseStringConstant(GC)))
2268 // If the alignment was parsed as an attribute, move to the alignment field.
2269 if (FuncAttrs & Attribute::Alignment) {
2270 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2271 FuncAttrs &= ~Attribute::Alignment;
2274 // Okay, if we got here, the function is syntactically valid. Convert types
2275 // and do semantic checks.
2276 std::vector<const Type*> ParamTypeList;
2277 SmallVector<AttributeWithIndex, 8> Attrs;
2278 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2280 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2281 if (FuncAttrs & ObsoleteFuncAttrs) {
2282 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2283 FuncAttrs &= ~ObsoleteFuncAttrs;
2286 if (RetAttrs != Attribute::None)
2287 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2289 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2290 ParamTypeList.push_back(ArgList[i].Type);
2291 if (ArgList[i].Attrs != Attribute::None)
2292 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2295 if (FuncAttrs != Attribute::None)
2296 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2298 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2300 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2301 RetType != Type::VoidTy)
2302 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2304 const FunctionType *FT =
2305 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2306 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2309 if (!FunctionName.empty()) {
2310 // If this was a definition of a forward reference, remove the definition
2311 // from the forward reference table and fill in the forward ref.
2312 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2313 ForwardRefVals.find(FunctionName);
2314 if (FRVI != ForwardRefVals.end()) {
2315 Fn = M->getFunction(FunctionName);
2316 ForwardRefVals.erase(FRVI);
2317 } else if ((Fn = M->getFunction(FunctionName))) {
2318 // If this function already exists in the symbol table, then it is
2319 // multiply defined. We accept a few cases for old backwards compat.
2320 // FIXME: Remove this stuff for LLVM 3.0.
2321 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2322 (!Fn->isDeclaration() && isDefine)) {
2323 // If the redefinition has different type or different attributes,
2324 // reject it. If both have bodies, reject it.
2325 return Error(NameLoc, "invalid redefinition of function '" +
2326 FunctionName + "'");
2327 } else if (Fn->isDeclaration()) {
2328 // Make sure to strip off any argument names so we can't get conflicts.
2329 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2335 } else if (FunctionName.empty()) {
2336 // If this is a definition of a forward referenced function, make sure the
2338 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2339 = ForwardRefValIDs.find(NumberedVals.size());
2340 if (I != ForwardRefValIDs.end()) {
2341 Fn = cast<Function>(I->second.first);
2342 if (Fn->getType() != PFT)
2343 return Error(NameLoc, "type of definition and forward reference of '@" +
2344 utostr(NumberedVals.size()) +"' disagree");
2345 ForwardRefValIDs.erase(I);
2350 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2351 else // Move the forward-reference to the correct spot in the module.
2352 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2354 if (FunctionName.empty())
2355 NumberedVals.push_back(Fn);
2357 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2358 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2359 Fn->setCallingConv(CC);
2360 Fn->setAttributes(PAL);
2361 Fn->setAlignment(Alignment);
2362 Fn->setSection(Section);
2363 if (!GC.empty()) Fn->setGC(GC.c_str());
2365 // Add all of the arguments we parsed to the function.
2366 Function::arg_iterator ArgIt = Fn->arg_begin();
2367 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2368 // If the argument has a name, insert it into the argument symbol table.
2369 if (ArgList[i].Name.empty()) continue;
2371 // Set the name, if it conflicted, it will be auto-renamed.
2372 ArgIt->setName(ArgList[i].Name);
2374 if (ArgIt->getNameStr() != ArgList[i].Name)
2375 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2376 ArgList[i].Name + "'");
2383 /// ParseFunctionBody
2384 /// ::= '{' BasicBlock+ '}'
2385 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2387 bool LLParser::ParseFunctionBody(Function &Fn) {
2388 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2389 return TokError("expected '{' in function body");
2390 Lex.Lex(); // eat the {.
2392 PerFunctionState PFS(*this, Fn);
2394 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2395 if (ParseBasicBlock(PFS)) return true;
2400 // Verify function is ok.
2401 return PFS.VerifyFunctionComplete();
2405 /// ::= LabelStr? Instruction*
2406 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2407 // If this basic block starts out with a name, remember it.
2409 LocTy NameLoc = Lex.getLoc();
2410 if (Lex.getKind() == lltok::LabelStr) {
2411 Name = Lex.getStrVal();
2415 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2416 if (BB == 0) return true;
2418 std::string NameStr;
2420 // Parse the instructions in this block until we get a terminator.
2423 // This instruction may have three possibilities for a name: a) none
2424 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2425 LocTy NameLoc = Lex.getLoc();
2429 if (Lex.getKind() == lltok::LocalVarID) {
2430 NameID = Lex.getUIntVal();
2432 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2434 } else if (Lex.getKind() == lltok::LocalVar ||
2435 // FIXME: REMOVE IN LLVM 3.0
2436 Lex.getKind() == lltok::StringConstant) {
2437 NameStr = Lex.getStrVal();
2439 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2443 if (ParseInstruction(Inst, BB, PFS)) return true;
2445 BB->getInstList().push_back(Inst);
2447 // Set the name on the instruction.
2448 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2449 } while (!isa<TerminatorInst>(Inst));
2454 //===----------------------------------------------------------------------===//
2455 // Instruction Parsing.
2456 //===----------------------------------------------------------------------===//
2458 /// ParseInstruction - Parse one of the many different instructions.
2460 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2461 PerFunctionState &PFS) {
2462 lltok::Kind Token = Lex.getKind();
2463 if (Token == lltok::Eof)
2464 return TokError("found end of file when expecting more instructions");
2465 LocTy Loc = Lex.getLoc();
2466 unsigned KeywordVal = Lex.getUIntVal();
2467 Lex.Lex(); // Eat the keyword.
2470 default: return Error(Loc, "expected instruction opcode");
2471 // Terminator Instructions.
2472 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2473 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2474 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2475 case lltok::kw_br: return ParseBr(Inst, PFS);
2476 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2477 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2478 // Binary Operators.
2482 // API compatibility: Accept either integer or floating-point types.
2483 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2484 case lltok::kw_fadd:
2485 case lltok::kw_fsub:
2486 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2488 case lltok::kw_udiv:
2489 case lltok::kw_sdiv:
2490 case lltok::kw_urem:
2491 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2492 case lltok::kw_fdiv:
2493 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2495 case lltok::kw_lshr:
2496 case lltok::kw_ashr:
2499 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2500 case lltok::kw_icmp:
2501 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2503 case lltok::kw_trunc:
2504 case lltok::kw_zext:
2505 case lltok::kw_sext:
2506 case lltok::kw_fptrunc:
2507 case lltok::kw_fpext:
2508 case lltok::kw_bitcast:
2509 case lltok::kw_uitofp:
2510 case lltok::kw_sitofp:
2511 case lltok::kw_fptoui:
2512 case lltok::kw_fptosi:
2513 case lltok::kw_inttoptr:
2514 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2516 case lltok::kw_select: return ParseSelect(Inst, PFS);
2517 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2518 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2519 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2520 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2521 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2522 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2523 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2525 case lltok::kw_alloca:
2526 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2527 case lltok::kw_free: return ParseFree(Inst, PFS);
2528 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2529 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2530 case lltok::kw_volatile:
2531 if (EatIfPresent(lltok::kw_load))
2532 return ParseLoad(Inst, PFS, true);
2533 else if (EatIfPresent(lltok::kw_store))
2534 return ParseStore(Inst, PFS, true);
2536 return TokError("expected 'load' or 'store'");
2537 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2538 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2539 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2540 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2544 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2545 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2546 if (Opc == Instruction::FCmp) {
2547 switch (Lex.getKind()) {
2548 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2549 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2550 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2551 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2552 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2553 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2554 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2555 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2556 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2557 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2558 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2559 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2560 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2561 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2562 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2563 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2564 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2567 switch (Lex.getKind()) {
2568 default: TokError("expected icmp predicate (e.g. 'eq')");
2569 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2570 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2571 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2572 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2573 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2574 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2575 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2576 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2577 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2578 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2585 //===----------------------------------------------------------------------===//
2586 // Terminator Instructions.
2587 //===----------------------------------------------------------------------===//
2589 /// ParseRet - Parse a return instruction.
2591 /// ::= 'ret' TypeAndValue
2592 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2593 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2594 PerFunctionState &PFS) {
2595 PATypeHolder Ty(Type::VoidTy);
2596 if (ParseType(Ty, true /*void allowed*/)) return true;
2598 if (Ty == Type::VoidTy) {
2599 Inst = ReturnInst::Create();
2604 if (ParseValue(Ty, RV, PFS)) return true;
2606 // The normal case is one return value.
2607 if (Lex.getKind() == lltok::comma) {
2608 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2609 // of 'ret {i32,i32} {i32 1, i32 2}'
2610 SmallVector<Value*, 8> RVs;
2613 while (EatIfPresent(lltok::comma)) {
2614 if (ParseTypeAndValue(RV, PFS)) return true;
2618 RV = Context.getUndef(PFS.getFunction().getReturnType());
2619 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2620 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2621 BB->getInstList().push_back(I);
2625 Inst = ReturnInst::Create(RV);
2631 /// ::= 'br' TypeAndValue
2632 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2633 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2635 Value *Op0, *Op1, *Op2;
2636 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2638 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2639 Inst = BranchInst::Create(BB);
2643 if (Op0->getType() != Type::Int1Ty)
2644 return Error(Loc, "branch condition must have 'i1' type");
2646 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2647 ParseTypeAndValue(Op1, Loc, PFS) ||
2648 ParseToken(lltok::comma, "expected ',' after true destination") ||
2649 ParseTypeAndValue(Op2, Loc2, PFS))
2652 if (!isa<BasicBlock>(Op1))
2653 return Error(Loc, "true destination of branch must be a basic block");
2654 if (!isa<BasicBlock>(Op2))
2655 return Error(Loc2, "true destination of branch must be a basic block");
2657 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2663 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2665 /// ::= (TypeAndValue ',' TypeAndValue)*
2666 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2667 LocTy CondLoc, BBLoc;
2668 Value *Cond, *DefaultBB;
2669 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2670 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2671 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2672 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2675 if (!isa<IntegerType>(Cond->getType()))
2676 return Error(CondLoc, "switch condition must have integer type");
2677 if (!isa<BasicBlock>(DefaultBB))
2678 return Error(BBLoc, "default destination must be a basic block");
2680 // Parse the jump table pairs.
2681 SmallPtrSet<Value*, 32> SeenCases;
2682 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2683 while (Lex.getKind() != lltok::rsquare) {
2684 Value *Constant, *DestBB;
2686 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2687 ParseToken(lltok::comma, "expected ',' after case value") ||
2688 ParseTypeAndValue(DestBB, BBLoc, PFS))
2691 if (!SeenCases.insert(Constant))
2692 return Error(CondLoc, "duplicate case value in switch");
2693 if (!isa<ConstantInt>(Constant))
2694 return Error(CondLoc, "case value is not a constant integer");
2695 if (!isa<BasicBlock>(DestBB))
2696 return Error(BBLoc, "case destination is not a basic block");
2698 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2699 cast<BasicBlock>(DestBB)));
2702 Lex.Lex(); // Eat the ']'.
2704 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2706 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2707 SI->addCase(Table[i].first, Table[i].second);
2713 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2714 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2715 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2716 LocTy CallLoc = Lex.getLoc();
2717 unsigned CC, RetAttrs, FnAttrs;
2718 PATypeHolder RetType(Type::VoidTy);
2721 SmallVector<ParamInfo, 16> ArgList;
2723 Value *NormalBB, *UnwindBB;
2724 if (ParseOptionalCallingConv(CC) ||
2725 ParseOptionalAttrs(RetAttrs, 1) ||
2726 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2727 ParseValID(CalleeID) ||
2728 ParseParameterList(ArgList, PFS) ||
2729 ParseOptionalAttrs(FnAttrs, 2) ||
2730 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2731 ParseTypeAndValue(NormalBB, PFS) ||
2732 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2733 ParseTypeAndValue(UnwindBB, PFS))
2736 if (!isa<BasicBlock>(NormalBB))
2737 return Error(CallLoc, "normal destination is not a basic block");
2738 if (!isa<BasicBlock>(UnwindBB))
2739 return Error(CallLoc, "unwind destination is not a basic block");
2741 // If RetType is a non-function pointer type, then this is the short syntax
2742 // for the call, which means that RetType is just the return type. Infer the
2743 // rest of the function argument types from the arguments that are present.
2744 const PointerType *PFTy = 0;
2745 const FunctionType *Ty = 0;
2746 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2747 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2748 // Pull out the types of all of the arguments...
2749 std::vector<const Type*> ParamTypes;
2750 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2751 ParamTypes.push_back(ArgList[i].V->getType());
2753 if (!FunctionType::isValidReturnType(RetType))
2754 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2756 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2757 PFTy = Context.getPointerTypeUnqual(Ty);
2760 // Look up the callee.
2762 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2764 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2765 // function attributes.
2766 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2767 if (FnAttrs & ObsoleteFuncAttrs) {
2768 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2769 FnAttrs &= ~ObsoleteFuncAttrs;
2772 // Set up the Attributes for the function.
2773 SmallVector<AttributeWithIndex, 8> Attrs;
2774 if (RetAttrs != Attribute::None)
2775 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2777 SmallVector<Value*, 8> Args;
2779 // Loop through FunctionType's arguments and ensure they are specified
2780 // correctly. Also, gather any parameter attributes.
2781 FunctionType::param_iterator I = Ty->param_begin();
2782 FunctionType::param_iterator E = Ty->param_end();
2783 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2784 const Type *ExpectedTy = 0;
2787 } else if (!Ty->isVarArg()) {
2788 return Error(ArgList[i].Loc, "too many arguments specified");
2791 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2792 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2793 ExpectedTy->getDescription() + "'");
2794 Args.push_back(ArgList[i].V);
2795 if (ArgList[i].Attrs != Attribute::None)
2796 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2800 return Error(CallLoc, "not enough parameters specified for call");
2802 if (FnAttrs != Attribute::None)
2803 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2805 // Finish off the Attributes and check them
2806 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2808 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2809 cast<BasicBlock>(UnwindBB),
2810 Args.begin(), Args.end());
2811 II->setCallingConv(CC);
2812 II->setAttributes(PAL);
2819 //===----------------------------------------------------------------------===//
2820 // Binary Operators.
2821 //===----------------------------------------------------------------------===//
2824 /// ::= ArithmeticOps TypeAndValue ',' Value
2826 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2827 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2828 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2829 unsigned Opc, unsigned OperandType) {
2830 LocTy Loc; Value *LHS, *RHS;
2831 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2832 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2833 ParseValue(LHS->getType(), RHS, PFS))
2837 switch (OperandType) {
2838 default: assert(0 && "Unknown operand type!");
2839 case 0: // int or FP.
2840 Valid = LHS->getType()->isIntOrIntVector() ||
2841 LHS->getType()->isFPOrFPVector();
2843 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2844 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2848 return Error(Loc, "invalid operand type for instruction");
2850 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2855 /// ::= ArithmeticOps TypeAndValue ',' Value {
2856 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2858 LocTy Loc; Value *LHS, *RHS;
2859 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2860 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2861 ParseValue(LHS->getType(), RHS, PFS))
2864 if (!LHS->getType()->isIntOrIntVector())
2865 return Error(Loc,"instruction requires integer or integer vector operands");
2867 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2873 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2874 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2875 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2877 // Parse the integer/fp comparison predicate.
2881 if (ParseCmpPredicate(Pred, Opc) ||
2882 ParseTypeAndValue(LHS, Loc, PFS) ||
2883 ParseToken(lltok::comma, "expected ',' after compare value") ||
2884 ParseValue(LHS->getType(), RHS, PFS))
2887 if (Opc == Instruction::FCmp) {
2888 if (!LHS->getType()->isFPOrFPVector())
2889 return Error(Loc, "fcmp requires floating point operands");
2890 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2892 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
2893 if (!LHS->getType()->isIntOrIntVector() &&
2894 !isa<PointerType>(LHS->getType()))
2895 return Error(Loc, "icmp requires integer operands");
2896 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
2901 //===----------------------------------------------------------------------===//
2902 // Other Instructions.
2903 //===----------------------------------------------------------------------===//
2907 /// ::= CastOpc TypeAndValue 'to' Type
2908 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2910 LocTy Loc; Value *Op;
2911 PATypeHolder DestTy(Type::VoidTy);
2912 if (ParseTypeAndValue(Op, Loc, PFS) ||
2913 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2917 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2918 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2919 return Error(Loc, "invalid cast opcode for cast from '" +
2920 Op->getType()->getDescription() + "' to '" +
2921 DestTy->getDescription() + "'");
2923 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2928 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2929 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2931 Value *Op0, *Op1, *Op2;
2932 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2933 ParseToken(lltok::comma, "expected ',' after select condition") ||
2934 ParseTypeAndValue(Op1, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after select value") ||
2936 ParseTypeAndValue(Op2, PFS))
2939 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2940 return Error(Loc, Reason);
2942 Inst = SelectInst::Create(Op0, Op1, Op2);
2947 /// ::= 'va_arg' TypeAndValue ',' Type
2948 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2950 PATypeHolder EltTy(Type::VoidTy);
2952 if (ParseTypeAndValue(Op, PFS) ||
2953 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2954 ParseType(EltTy, TypeLoc))
2957 if (!EltTy->isFirstClassType())
2958 return Error(TypeLoc, "va_arg requires operand with first class type");
2960 Inst = new VAArgInst(Op, EltTy);
2964 /// ParseExtractElement
2965 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2966 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2969 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2970 ParseToken(lltok::comma, "expected ',' after extract value") ||
2971 ParseTypeAndValue(Op1, PFS))
2974 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2975 return Error(Loc, "invalid extractelement operands");
2977 Inst = new ExtractElementInst(Op0, Op1);
2981 /// ParseInsertElement
2982 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2983 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2985 Value *Op0, *Op1, *Op2;
2986 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2987 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2988 ParseTypeAndValue(Op1, PFS) ||
2989 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2990 ParseTypeAndValue(Op2, PFS))
2993 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2994 return Error(Loc, "invalid extractelement operands");
2996 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3000 /// ParseShuffleVector
3001 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3002 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3004 Value *Op0, *Op1, *Op2;
3005 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3006 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3007 ParseTypeAndValue(Op1, PFS) ||
3008 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3009 ParseTypeAndValue(Op2, PFS))
3012 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3013 return Error(Loc, "invalid extractelement operands");
3015 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3020 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3021 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3022 PATypeHolder Ty(Type::VoidTy);
3024 LocTy TypeLoc = Lex.getLoc();
3026 if (ParseType(Ty) ||
3027 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3028 ParseValue(Ty, Op0, PFS) ||
3029 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3030 ParseValue(Type::LabelTy, Op1, PFS) ||
3031 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3034 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3036 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3038 if (!EatIfPresent(lltok::comma))
3041 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3042 ParseValue(Ty, Op0, PFS) ||
3043 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3044 ParseValue(Type::LabelTy, Op1, PFS) ||
3045 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3049 if (!Ty->isFirstClassType())
3050 return Error(TypeLoc, "phi node must have first class type");
3052 PHINode *PN = PHINode::Create(Ty);
3053 PN->reserveOperandSpace(PHIVals.size());
3054 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3055 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3061 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3062 /// ParameterList OptionalAttrs
3063 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3065 unsigned CC, RetAttrs, FnAttrs;
3066 PATypeHolder RetType(Type::VoidTy);
3069 SmallVector<ParamInfo, 16> ArgList;
3070 LocTy CallLoc = Lex.getLoc();
3072 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3073 ParseOptionalCallingConv(CC) ||
3074 ParseOptionalAttrs(RetAttrs, 1) ||
3075 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3076 ParseValID(CalleeID) ||
3077 ParseParameterList(ArgList, PFS) ||
3078 ParseOptionalAttrs(FnAttrs, 2))
3081 // If RetType is a non-function pointer type, then this is the short syntax
3082 // for the call, which means that RetType is just the return type. Infer the
3083 // rest of the function argument types from the arguments that are present.
3084 const PointerType *PFTy = 0;
3085 const FunctionType *Ty = 0;
3086 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3087 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3088 // Pull out the types of all of the arguments...
3089 std::vector<const Type*> ParamTypes;
3090 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3091 ParamTypes.push_back(ArgList[i].V->getType());
3093 if (!FunctionType::isValidReturnType(RetType))
3094 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3096 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3097 PFTy = Context.getPointerTypeUnqual(Ty);
3100 // Look up the callee.
3102 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3104 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3105 // function attributes.
3106 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3107 if (FnAttrs & ObsoleteFuncAttrs) {
3108 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3109 FnAttrs &= ~ObsoleteFuncAttrs;
3112 // Set up the Attributes for the function.
3113 SmallVector<AttributeWithIndex, 8> Attrs;
3114 if (RetAttrs != Attribute::None)
3115 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3117 SmallVector<Value*, 8> Args;
3119 // Loop through FunctionType's arguments and ensure they are specified
3120 // correctly. Also, gather any parameter attributes.
3121 FunctionType::param_iterator I = Ty->param_begin();
3122 FunctionType::param_iterator E = Ty->param_end();
3123 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3124 const Type *ExpectedTy = 0;
3127 } else if (!Ty->isVarArg()) {
3128 return Error(ArgList[i].Loc, "too many arguments specified");
3131 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3132 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3133 ExpectedTy->getDescription() + "'");
3134 Args.push_back(ArgList[i].V);
3135 if (ArgList[i].Attrs != Attribute::None)
3136 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3140 return Error(CallLoc, "not enough parameters specified for call");
3142 if (FnAttrs != Attribute::None)
3143 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3145 // Finish off the Attributes and check them
3146 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3148 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3149 CI->setTailCall(isTail);
3150 CI->setCallingConv(CC);
3151 CI->setAttributes(PAL);
3156 //===----------------------------------------------------------------------===//
3157 // Memory Instructions.
3158 //===----------------------------------------------------------------------===//
3161 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3162 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3163 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3165 PATypeHolder Ty(Type::VoidTy);
3168 unsigned Alignment = 0;
3169 if (ParseType(Ty)) return true;
3171 if (EatIfPresent(lltok::comma)) {
3172 if (Lex.getKind() == lltok::kw_align) {
3173 if (ParseOptionalAlignment(Alignment)) return true;
3174 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3175 ParseOptionalCommaAlignment(Alignment)) {
3180 if (Size && Size->getType() != Type::Int32Ty)
3181 return Error(SizeLoc, "element count must be i32");
3183 if (Opc == Instruction::Malloc)
3184 Inst = new MallocInst(Ty, Size, Alignment);
3186 Inst = new AllocaInst(Ty, Size, Alignment);
3191 /// ::= 'free' TypeAndValue
3192 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3193 Value *Val; LocTy Loc;
3194 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3195 if (!isa<PointerType>(Val->getType()))
3196 return Error(Loc, "operand to free must be a pointer");
3197 Inst = new FreeInst(Val);
3202 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3203 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3205 Value *Val; LocTy Loc;
3207 if (ParseTypeAndValue(Val, Loc, PFS) ||
3208 ParseOptionalCommaAlignment(Alignment))
3211 if (!isa<PointerType>(Val->getType()) ||
3212 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3213 return Error(Loc, "load operand must be a pointer to a first class type");
3215 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3220 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3221 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3223 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3225 if (ParseTypeAndValue(Val, Loc, PFS) ||
3226 ParseToken(lltok::comma, "expected ',' after store operand") ||
3227 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3228 ParseOptionalCommaAlignment(Alignment))
3231 if (!isa<PointerType>(Ptr->getType()))
3232 return Error(PtrLoc, "store operand must be a pointer");
3233 if (!Val->getType()->isFirstClassType())
3234 return Error(Loc, "store operand must be a first class value");
3235 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3236 return Error(Loc, "stored value and pointer type do not match");
3238 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3243 /// ::= 'getresult' TypeAndValue ',' i32
3244 /// FIXME: Remove support for getresult in LLVM 3.0
3245 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3246 Value *Val; LocTy ValLoc, EltLoc;
3248 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3249 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3250 ParseUInt32(Element, EltLoc))
3253 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3254 return Error(ValLoc, "getresult inst requires an aggregate operand");
3255 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3256 return Error(EltLoc, "invalid getresult index for value");
3257 Inst = ExtractValueInst::Create(Val, Element);
3261 /// ParseGetElementPtr
3262 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3263 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3264 Value *Ptr, *Val; LocTy Loc, EltLoc;
3265 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3267 if (!isa<PointerType>(Ptr->getType()))
3268 return Error(Loc, "base of getelementptr must be a pointer");
3270 SmallVector<Value*, 16> Indices;
3271 while (EatIfPresent(lltok::comma)) {
3272 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3273 if (!isa<IntegerType>(Val->getType()))
3274 return Error(EltLoc, "getelementptr index must be an integer");
3275 Indices.push_back(Val);
3278 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3279 Indices.begin(), Indices.end()))
3280 return Error(Loc, "invalid getelementptr indices");
3281 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3285 /// ParseExtractValue
3286 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3287 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3288 Value *Val; LocTy Loc;
3289 SmallVector<unsigned, 4> Indices;
3290 if (ParseTypeAndValue(Val, Loc, PFS) ||
3291 ParseIndexList(Indices))
3294 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3295 return Error(Loc, "extractvalue operand must be array or struct");
3297 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3299 return Error(Loc, "invalid indices for extractvalue");
3300 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3304 /// ParseInsertValue
3305 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3306 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3307 Value *Val0, *Val1; LocTy Loc0, Loc1;
3308 SmallVector<unsigned, 4> Indices;
3309 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3310 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3311 ParseTypeAndValue(Val1, Loc1, PFS) ||
3312 ParseIndexList(Indices))
3315 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3316 return Error(Loc0, "extractvalue operand must be array or struct");
3318 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3320 return Error(Loc0, "invalid indices for insertvalue");
3321 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3325 //===----------------------------------------------------------------------===//
3326 // Embedded metadata.
3327 //===----------------------------------------------------------------------===//
3329 /// ParseMDNodeVector
3330 /// ::= Element (',' Element)*
3332 /// ::= 'null' | TypeAndValue
3333 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3334 assert(Lex.getKind() == lltok::lbrace);
3338 if (Lex.getKind() == lltok::kw_null) {
3343 if (ParseGlobalTypeAndValue(C)) return true;
3347 } while (EatIfPresent(lltok::comma));