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/Module.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
29 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
39 t_EmptyArray, // No value: []
40 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
46 std::string StrVal, StrVal2;
49 Constant *ConstantVal;
50 ValID() : APFloatVal(0.0) {}
54 /// Run: module ::= toplevelentity*
55 bool LLParser::Run() {
59 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
63 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65 bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 bool LLParser::ParseTopLevelEntities() {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
116 case lltok::kw_private: // OptionalLinkage
117 case lltok::kw_internal: // OptionalLinkage
118 case lltok::kw_weak: // OptionalLinkage
119 case lltok::kw_weak_odr: // OptionalLinkage
120 case lltok::kw_linkonce: // OptionalLinkage
121 case lltok::kw_linkonce_odr: // OptionalLinkage
122 case lltok::kw_appending: // OptionalLinkage
123 case lltok::kw_dllexport: // OptionalLinkage
124 case lltok::kw_common: // OptionalLinkage
125 case lltok::kw_dllimport: // OptionalLinkage
126 case lltok::kw_extern_weak: // OptionalLinkage
127 case lltok::kw_external: { // OptionalLinkage
128 unsigned Linkage, Visibility;
129 if (ParseOptionalLinkage(Linkage) ||
130 ParseOptionalVisibility(Visibility) ||
131 ParseGlobal("", 0, Linkage, true, Visibility))
135 case lltok::kw_default: // OptionalVisibility
136 case lltok::kw_hidden: // OptionalVisibility
137 case lltok::kw_protected: { // OptionalVisibility
139 if (ParseOptionalVisibility(Visibility) ||
140 ParseGlobal("", 0, 0, false, Visibility))
145 case lltok::kw_thread_local: // OptionalThreadLocal
146 case lltok::kw_addrspace: // OptionalAddrSpace
147 case lltok::kw_constant: // GlobalType
148 case lltok::kw_global: // GlobalType
149 if (ParseGlobal("", 0, 0, false, 0)) return true;
157 /// ::= 'module' 'asm' STRINGCONSTANT
158 bool LLParser::ParseModuleAsm() {
159 assert(Lex.getKind() == lltok::kw_module);
163 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
164 ParseStringConstant(AsmStr)) return true;
166 const std::string &AsmSoFar = M->getModuleInlineAsm();
167 if (AsmSoFar.empty())
168 M->setModuleInlineAsm(AsmStr);
170 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
175 /// ::= 'target' 'triple' '=' STRINGCONSTANT
176 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
177 bool LLParser::ParseTargetDefinition() {
178 assert(Lex.getKind() == lltok::kw_target);
181 default: return TokError("unknown target property");
182 case lltok::kw_triple:
184 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
185 ParseStringConstant(Str))
187 M->setTargetTriple(Str);
189 case lltok::kw_datalayout:
191 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
192 ParseStringConstant(Str))
194 M->setDataLayout(Str);
200 /// ::= 'deplibs' '=' '[' ']'
201 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
202 bool LLParser::ParseDepLibs() {
203 assert(Lex.getKind() == lltok::kw_deplibs);
205 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
206 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
209 if (EatIfPresent(lltok::rsquare))
213 if (ParseStringConstant(Str)) return true;
216 while (EatIfPresent(lltok::comma)) {
217 if (ParseStringConstant(Str)) return true;
221 return ParseToken(lltok::rsquare, "expected ']' at end of list");
226 bool LLParser::ParseUnnamedType() {
227 assert(Lex.getKind() == lltok::kw_type);
228 LocTy TypeLoc = Lex.getLoc();
229 Lex.Lex(); // eat kw_type
231 PATypeHolder Ty(Type::VoidTy);
232 if (ParseType(Ty)) return true;
234 unsigned TypeID = NumberedTypes.size();
236 // See if this type was previously referenced.
237 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
238 FI = ForwardRefTypeIDs.find(TypeID);
239 if (FI != ForwardRefTypeIDs.end()) {
240 if (FI->second.first.get() == Ty)
241 return Error(TypeLoc, "self referential type is invalid");
243 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
244 Ty = FI->second.first.get();
245 ForwardRefTypeIDs.erase(FI);
248 NumberedTypes.push_back(Ty);
254 /// ::= LocalVar '=' 'type' type
255 bool LLParser::ParseNamedType() {
256 std::string Name = Lex.getStrVal();
257 LocTy NameLoc = Lex.getLoc();
258 Lex.Lex(); // eat LocalVar.
260 PATypeHolder Ty(Type::VoidTy);
262 if (ParseToken(lltok::equal, "expected '=' after name") ||
263 ParseToken(lltok::kw_type, "expected 'type' after name") ||
267 // Set the type name, checking for conflicts as we do so.
268 bool AlreadyExists = M->addTypeName(Name, Ty);
269 if (!AlreadyExists) return false;
271 // See if this type is a forward reference. We need to eagerly resolve
272 // types to allow recursive type redefinitions below.
273 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
274 FI = ForwardRefTypes.find(Name);
275 if (FI != ForwardRefTypes.end()) {
276 if (FI->second.first.get() == Ty)
277 return Error(NameLoc, "self referential type is invalid");
279 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
280 Ty = FI->second.first.get();
281 ForwardRefTypes.erase(FI);
284 // Inserting a name that is already defined, get the existing name.
285 const Type *Existing = M->getTypeByName(Name);
286 assert(Existing && "Conflict but no matching type?!");
288 // Otherwise, this is an attempt to redefine a type. That's okay if
289 // the redefinition is identical to the original.
290 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
291 if (Existing == Ty) return false;
293 // Any other kind of (non-equivalent) redefinition is an error.
294 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
295 Ty->getDescription() + "'");
300 /// ::= 'declare' FunctionHeader
301 bool LLParser::ParseDeclare() {
302 assert(Lex.getKind() == lltok::kw_declare);
306 return ParseFunctionHeader(F, false);
310 /// ::= 'define' FunctionHeader '{' ...
311 bool LLParser::ParseDefine() {
312 assert(Lex.getKind() == lltok::kw_define);
316 return ParseFunctionHeader(F, true) ||
317 ParseFunctionBody(*F);
323 bool LLParser::ParseGlobalType(bool &IsConstant) {
324 if (Lex.getKind() == lltok::kw_constant)
326 else if (Lex.getKind() == lltok::kw_global)
330 return TokError("expected 'global' or 'constant'");
336 /// ParseNamedGlobal:
337 /// GlobalVar '=' OptionalVisibility ALIAS ...
338 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
339 bool LLParser::ParseNamedGlobal() {
340 assert(Lex.getKind() == lltok::GlobalVar);
341 LocTy NameLoc = Lex.getLoc();
342 std::string Name = Lex.getStrVal();
346 unsigned Linkage, Visibility;
347 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
348 ParseOptionalLinkage(Linkage, HasLinkage) ||
349 ParseOptionalVisibility(Visibility))
352 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
353 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
354 return ParseAlias(Name, NameLoc, Visibility);
358 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
360 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
362 /// Everything through visibility has already been parsed.
364 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
365 unsigned Visibility) {
366 assert(Lex.getKind() == lltok::kw_alias);
369 LocTy LinkageLoc = Lex.getLoc();
370 if (ParseOptionalLinkage(Linkage))
373 if (Linkage != GlobalValue::ExternalLinkage &&
374 Linkage != GlobalValue::WeakAnyLinkage &&
375 Linkage != GlobalValue::WeakODRLinkage &&
376 Linkage != GlobalValue::InternalLinkage &&
377 Linkage != GlobalValue::PrivateLinkage)
378 return Error(LinkageLoc, "invalid linkage type for alias");
381 LocTy AliaseeLoc = Lex.getLoc();
382 if (Lex.getKind() != lltok::kw_bitcast) {
383 if (ParseGlobalTypeAndValue(Aliasee)) return true;
385 // The bitcast dest type is not present, it is implied by the dest type.
387 if (ParseValID(ID)) return true;
388 if (ID.Kind != ValID::t_Constant)
389 return Error(AliaseeLoc, "invalid aliasee");
390 Aliasee = ID.ConstantVal;
393 if (!isa<PointerType>(Aliasee->getType()))
394 return Error(AliaseeLoc, "alias must have pointer type");
396 // Okay, create the alias but do not insert it into the module yet.
397 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
398 (GlobalValue::LinkageTypes)Linkage, Name,
400 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
402 // See if this value already exists in the symbol table. If so, it is either
403 // a redefinition or a definition of a forward reference.
404 if (GlobalValue *Val =
405 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
406 // See if this was a redefinition. If so, there is no entry in
408 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
409 I = ForwardRefVals.find(Name);
410 if (I == ForwardRefVals.end())
411 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
413 // Otherwise, this was a definition of forward ref. Verify that types
415 if (Val->getType() != GA->getType())
416 return Error(NameLoc,
417 "forward reference and definition of alias have different types");
419 // If they agree, just RAUW the old value with the alias and remove the
421 Val->replaceAllUsesWith(GA);
422 Val->eraseFromParent();
423 ForwardRefVals.erase(I);
426 // Insert into the module, we know its name won't collide now.
427 M->getAliasList().push_back(GA);
428 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
434 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
435 /// OptionalAddrSpace GlobalType Type Const
436 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
437 /// OptionalAddrSpace GlobalType Type Const
439 /// Everything through visibility has been parsed already.
441 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
442 unsigned Linkage, bool HasLinkage,
443 unsigned Visibility) {
445 bool ThreadLocal, IsConstant;
448 PATypeHolder Ty(Type::VoidTy);
449 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
450 ParseOptionalAddrSpace(AddrSpace) ||
451 ParseGlobalType(IsConstant) ||
452 ParseType(Ty, TyLoc))
455 // If the linkage is specified and is external, then no initializer is
458 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
459 Linkage != GlobalValue::ExternalWeakLinkage &&
460 Linkage != GlobalValue::ExternalLinkage)) {
461 if (ParseGlobalValue(Ty, Init))
465 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
466 return Error(TyLoc, "invalid type for global variable");
468 GlobalVariable *GV = 0;
470 // See if the global was forward referenced, if so, use the global.
472 if ((GV = M->getGlobalVariable(Name, true)) &&
473 !ForwardRefVals.erase(Name))
474 return Error(NameLoc, "redefinition of global '@" + Name + "'");
476 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
477 I = ForwardRefValIDs.find(NumberedVals.size());
478 if (I != ForwardRefValIDs.end()) {
479 GV = cast<GlobalVariable>(I->second.first);
480 ForwardRefValIDs.erase(I);
485 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
486 M, false, AddrSpace);
488 if (GV->getType()->getElementType() != Ty)
490 "forward reference and definition of global have different types");
492 // Move the forward-reference to the correct spot in the module.
493 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
497 NumberedVals.push_back(GV);
499 // Set the parsed properties on the global.
501 GV->setInitializer(Init);
502 GV->setConstant(IsConstant);
503 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
504 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
505 GV->setThreadLocal(ThreadLocal);
507 // Parse attributes on the global.
508 while (Lex.getKind() == lltok::comma) {
511 if (Lex.getKind() == lltok::kw_section) {
513 GV->setSection(Lex.getStrVal());
514 if (ParseToken(lltok::StringConstant, "expected global section string"))
516 } else if (Lex.getKind() == lltok::kw_align) {
518 if (ParseOptionalAlignment(Alignment)) return true;
519 GV->setAlignment(Alignment);
521 TokError("unknown global variable property!");
529 //===----------------------------------------------------------------------===//
530 // GlobalValue Reference/Resolution Routines.
531 //===----------------------------------------------------------------------===//
533 /// GetGlobalVal - Get a value with the specified name or ID, creating a
534 /// forward reference record if needed. This can return null if the value
535 /// exists but does not have the right type.
536 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
538 const PointerType *PTy = dyn_cast<PointerType>(Ty);
540 Error(Loc, "global variable reference must have pointer type");
544 // Look this name up in the normal function symbol table.
546 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
548 // If this is a forward reference for the value, see if we already created a
549 // forward ref record.
551 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
552 I = ForwardRefVals.find(Name);
553 if (I != ForwardRefVals.end())
554 Val = I->second.first;
557 // If we have the value in the symbol table or fwd-ref table, return it.
559 if (Val->getType() == Ty) return Val;
560 Error(Loc, "'@" + Name + "' defined with type '" +
561 Val->getType()->getDescription() + "'");
565 // Otherwise, create a new forward reference for this value and remember it.
567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
568 // Function types can return opaque but functions can't.
569 if (isa<OpaqueType>(FT->getReturnType())) {
570 Error(Loc, "function may not return opaque type");
574 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
576 FwdVal = new GlobalVariable(PTy->getElementType(), false,
577 GlobalValue::ExternalWeakLinkage, 0, Name, M);
580 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
584 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
587 Error(Loc, "global variable reference must have pointer type");
591 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
593 // If this is a forward reference for the value, see if we already created a
594 // forward ref record.
596 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
597 I = ForwardRefValIDs.find(ID);
598 if (I != ForwardRefValIDs.end())
599 Val = I->second.first;
602 // If we have the value in the symbol table or fwd-ref table, return it.
604 if (Val->getType() == Ty) return Val;
605 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
606 Val->getType()->getDescription() + "'");
610 // Otherwise, create a new forward reference for this value and remember it.
612 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
613 // Function types can return opaque but functions can't.
614 if (isa<OpaqueType>(FT->getReturnType())) {
615 Error(Loc, "function may not return opaque type");
618 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
620 FwdVal = new GlobalVariable(PTy->getElementType(), false,
621 GlobalValue::ExternalWeakLinkage, 0, "", M);
624 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
629 //===----------------------------------------------------------------------===//
631 //===----------------------------------------------------------------------===//
633 /// ParseToken - If the current token has the specified kind, eat it and return
634 /// success. Otherwise, emit the specified error and return failure.
635 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
636 if (Lex.getKind() != T)
637 return TokError(ErrMsg);
642 /// ParseStringConstant
643 /// ::= StringConstant
644 bool LLParser::ParseStringConstant(std::string &Result) {
645 if (Lex.getKind() != lltok::StringConstant)
646 return TokError("expected string constant");
647 Result = Lex.getStrVal();
654 bool LLParser::ParseUInt32(unsigned &Val) {
655 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
656 return TokError("expected integer");
657 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
658 if (Val64 != unsigned(Val64))
659 return TokError("expected 32-bit integer (too large)");
666 /// ParseOptionalAddrSpace
668 /// := 'addrspace' '(' uint32 ')'
669 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
671 if (!EatIfPresent(lltok::kw_addrspace))
673 return ParseToken(lltok::lparen, "expected '(' in address space") ||
674 ParseUInt32(AddrSpace) ||
675 ParseToken(lltok::rparen, "expected ')' in address space");
678 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
679 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
680 /// 2: function attr.
681 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
682 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
683 Attrs = Attribute::None;
684 LocTy AttrLoc = Lex.getLoc();
687 switch (Lex.getKind()) {
690 // Treat these as signext/zeroext if they occur in the argument list after
691 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
692 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
694 // FIXME: REMOVE THIS IN LLVM 3.0
696 if (Lex.getKind() == lltok::kw_sext)
697 Attrs |= Attribute::SExt;
699 Attrs |= Attribute::ZExt;
703 default: // End of attributes.
704 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
705 return Error(AttrLoc, "invalid use of function-only attribute");
707 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
708 return Error(AttrLoc, "invalid use of parameter-only attribute");
711 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
712 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
713 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
714 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
715 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
716 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
717 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
718 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
720 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
721 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
722 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
723 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
724 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
725 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
726 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
727 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
728 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
731 case lltok::kw_align: {
733 if (ParseOptionalAlignment(Alignment))
735 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
743 /// ParseOptionalLinkage
750 /// ::= 'linkonce_odr'
755 /// ::= 'extern_weak'
757 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
759 switch (Lex.getKind()) {
760 default: Res = GlobalValue::ExternalLinkage; return false;
761 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
762 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
763 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
764 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
765 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
766 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
767 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
768 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
769 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
770 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
771 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
772 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
779 /// ParseOptionalVisibility
785 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
786 switch (Lex.getKind()) {
787 default: Res = GlobalValue::DefaultVisibility; return false;
788 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
789 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
790 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
796 /// ParseOptionalCallingConv
801 /// ::= 'x86_stdcallcc'
802 /// ::= 'x86_fastcallcc'
805 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
806 switch (Lex.getKind()) {
807 default: CC = CallingConv::C; return false;
808 case lltok::kw_ccc: CC = CallingConv::C; break;
809 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
810 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
811 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
812 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
813 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
819 /// ParseOptionalAlignment
822 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
824 if (!EatIfPresent(lltok::kw_align))
826 LocTy AlignLoc = Lex.getLoc();
827 if (ParseUInt32(Alignment)) return true;
828 if (!isPowerOf2_32(Alignment))
829 return Error(AlignLoc, "alignment is not a power of two");
833 /// ParseOptionalCommaAlignment
835 /// ::= ',' 'align' 4
836 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
838 if (!EatIfPresent(lltok::comma))
840 return ParseToken(lltok::kw_align, "expected 'align'") ||
841 ParseUInt32(Alignment);
845 /// ::= (',' uint32)+
846 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
847 if (Lex.getKind() != lltok::comma)
848 return TokError("expected ',' as start of index list");
850 while (EatIfPresent(lltok::comma)) {
852 if (ParseUInt32(Idx)) return true;
853 Indices.push_back(Idx);
859 //===----------------------------------------------------------------------===//
861 //===----------------------------------------------------------------------===//
863 /// ParseType - Parse and resolve a full type.
864 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
865 LocTy TypeLoc = Lex.getLoc();
866 if (ParseTypeRec(Result)) return true;
868 // Verify no unresolved uprefs.
870 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
872 if (!AllowVoid && Result.get() == Type::VoidTy)
873 return Error(TypeLoc, "void type only allowed for function results");
878 /// HandleUpRefs - Every time we finish a new layer of types, this function is
879 /// called. It loops through the UpRefs vector, which is a list of the
880 /// currently active types. For each type, if the up-reference is contained in
881 /// the newly completed type, we decrement the level count. When the level
882 /// count reaches zero, the up-referenced type is the type that is passed in:
883 /// thus we can complete the cycle.
885 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
886 // If Ty isn't abstract, or if there are no up-references in it, then there is
887 // nothing to resolve here.
888 if (!ty->isAbstract() || UpRefs.empty()) return ty;
892 errs() << "Type '" << Ty->getDescription()
893 << "' newly formed. Resolving upreferences.\n"
894 << UpRefs.size() << " upreferences active!\n";
897 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
898 // to zero), we resolve them all together before we resolve them to Ty. At
899 // the end of the loop, if there is anything to resolve to Ty, it will be in
901 OpaqueType *TypeToResolve = 0;
903 for (unsigned i = 0; i != UpRefs.size(); ++i) {
904 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
906 std::find(Ty->subtype_begin(), Ty->subtype_end(),
907 UpRefs[i].LastContainedTy) != Ty->subtype_end();
910 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
911 << UpRefs[i].LastContainedTy->getDescription() << ") = "
912 << (ContainsType ? "true" : "false")
913 << " level=" << UpRefs[i].NestingLevel << "\n";
918 // Decrement level of upreference
919 unsigned Level = --UpRefs[i].NestingLevel;
920 UpRefs[i].LastContainedTy = Ty;
922 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
927 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
930 TypeToResolve = UpRefs[i].UpRefTy;
932 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
933 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
934 --i; // Do not skip the next element.
938 TypeToResolve->refineAbstractTypeTo(Ty);
944 /// ParseTypeRec - The recursive function used to process the internal
945 /// implementation details of types.
946 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
947 switch (Lex.getKind()) {
949 return TokError("expected type");
951 // TypeRec ::= 'float' | 'void' (etc)
952 Result = Lex.getTyVal();
955 case lltok::kw_opaque:
956 // TypeRec ::= 'opaque'
957 Result = OpaqueType::get();
961 // TypeRec ::= '{' ... '}'
962 if (ParseStructType(Result, false))
966 // TypeRec ::= '[' ... ']'
967 Lex.Lex(); // eat the lsquare.
968 if (ParseArrayVectorType(Result, false))
971 case lltok::less: // Either vector or packed struct.
972 // TypeRec ::= '<' ... '>'
974 if (Lex.getKind() == lltok::lbrace) {
975 if (ParseStructType(Result, true) ||
976 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
978 } else if (ParseArrayVectorType(Result, true))
981 case lltok::LocalVar:
982 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
984 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
987 Result = OpaqueType::get();
988 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
989 std::make_pair(Result,
991 M->addTypeName(Lex.getStrVal(), Result.get());
996 case lltok::LocalVarID:
998 if (Lex.getUIntVal() < NumberedTypes.size())
999 Result = NumberedTypes[Lex.getUIntVal()];
1001 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1002 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1003 if (I != ForwardRefTypeIDs.end())
1004 Result = I->second.first;
1006 Result = OpaqueType::get();
1007 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1008 std::make_pair(Result,
1014 case lltok::backslash: {
1015 // TypeRec ::= '\' 4
1018 if (ParseUInt32(Val)) return true;
1019 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1020 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1026 // Parse the type suffixes.
1028 switch (Lex.getKind()) {
1030 default: return false;
1032 // TypeRec ::= TypeRec '*'
1034 if (Result.get() == Type::LabelTy)
1035 return TokError("basic block pointers are invalid");
1036 if (Result.get() == Type::VoidTy)
1037 return TokError("pointers to void are invalid; use i8* instead");
1038 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1042 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1043 case lltok::kw_addrspace: {
1044 if (Result.get() == Type::LabelTy)
1045 return TokError("basic block pointers are invalid");
1046 if (Result.get() == Type::VoidTy)
1047 return TokError("pointers to void are invalid; use i8* instead");
1049 if (ParseOptionalAddrSpace(AddrSpace) ||
1050 ParseToken(lltok::star, "expected '*' in address space"))
1053 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1057 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1059 if (ParseFunctionType(Result))
1066 /// ParseParameterList
1068 /// ::= '(' Arg (',' Arg)* ')'
1070 /// ::= Type OptionalAttributes Value OptionalAttributes
1071 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1072 PerFunctionState &PFS) {
1073 if (ParseToken(lltok::lparen, "expected '(' in call"))
1076 while (Lex.getKind() != lltok::rparen) {
1077 // If this isn't the first argument, we need a comma.
1078 if (!ArgList.empty() &&
1079 ParseToken(lltok::comma, "expected ',' in argument list"))
1082 // Parse the argument.
1084 PATypeHolder ArgTy(Type::VoidTy);
1085 unsigned ArgAttrs1, ArgAttrs2;
1087 if (ParseType(ArgTy, ArgLoc) ||
1088 ParseOptionalAttrs(ArgAttrs1, 0) ||
1089 ParseValue(ArgTy, V, PFS) ||
1090 // FIXME: Should not allow attributes after the argument, remove this in
1092 ParseOptionalAttrs(ArgAttrs2, 3))
1094 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1097 Lex.Lex(); // Lex the ')'.
1103 /// ParseArgumentList - Parse the argument list for a function type or function
1104 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1105 /// ::= '(' ArgTypeListI ')'
1109 /// ::= ArgTypeList ',' '...'
1110 /// ::= ArgType (',' ArgType)*
1112 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1113 bool &isVarArg, bool inType) {
1115 assert(Lex.getKind() == lltok::lparen);
1116 Lex.Lex(); // eat the (.
1118 if (Lex.getKind() == lltok::rparen) {
1120 } else if (Lex.getKind() == lltok::dotdotdot) {
1124 LocTy TypeLoc = Lex.getLoc();
1125 PATypeHolder ArgTy(Type::VoidTy);
1129 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1130 // types (such as a function returning a pointer to itself). If parsing a
1131 // function prototype, we require fully resolved types.
1132 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1133 ParseOptionalAttrs(Attrs, 0)) return true;
1135 if (ArgTy == Type::VoidTy)
1136 return Error(TypeLoc, "argument can not have void type");
1138 if (Lex.getKind() == lltok::LocalVar ||
1139 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1140 Name = Lex.getStrVal();
1144 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1145 return Error(TypeLoc, "invalid type for function argument");
1147 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1149 while (EatIfPresent(lltok::comma)) {
1150 // Handle ... at end of arg list.
1151 if (EatIfPresent(lltok::dotdotdot)) {
1156 // Otherwise must be an argument type.
1157 TypeLoc = Lex.getLoc();
1158 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1159 ParseOptionalAttrs(Attrs, 0)) return true;
1161 if (ArgTy == Type::VoidTy)
1162 return Error(TypeLoc, "argument can not have void type");
1164 if (Lex.getKind() == lltok::LocalVar ||
1165 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1166 Name = Lex.getStrVal();
1172 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1173 return Error(TypeLoc, "invalid type for function argument");
1175 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1179 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1182 /// ParseFunctionType
1183 /// ::= Type ArgumentList OptionalAttrs
1184 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1185 assert(Lex.getKind() == lltok::lparen);
1187 if (!FunctionType::isValidReturnType(Result))
1188 return TokError("invalid function return type");
1190 std::vector<ArgInfo> ArgList;
1193 if (ParseArgumentList(ArgList, isVarArg, true) ||
1194 // FIXME: Allow, but ignore attributes on function types!
1195 // FIXME: Remove in LLVM 3.0
1196 ParseOptionalAttrs(Attrs, 2))
1199 // Reject names on the arguments lists.
1200 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1201 if (!ArgList[i].Name.empty())
1202 return Error(ArgList[i].Loc, "argument name invalid in function type");
1203 if (!ArgList[i].Attrs != 0) {
1204 // Allow but ignore attributes on function types; this permits
1206 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1210 std::vector<const Type*> ArgListTy;
1211 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1212 ArgListTy.push_back(ArgList[i].Type);
1214 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1218 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1221 /// ::= '{' TypeRec (',' TypeRec)* '}'
1222 /// ::= '<' '{' '}' '>'
1223 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1224 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1225 assert(Lex.getKind() == lltok::lbrace);
1226 Lex.Lex(); // Consume the '{'
1228 if (EatIfPresent(lltok::rbrace)) {
1229 Result = StructType::get(std::vector<const Type*>(), Packed);
1233 std::vector<PATypeHolder> ParamsList;
1234 LocTy EltTyLoc = Lex.getLoc();
1235 if (ParseTypeRec(Result)) return true;
1236 ParamsList.push_back(Result);
1238 if (Result == Type::VoidTy)
1239 return Error(EltTyLoc, "struct element can not have void type");
1241 while (EatIfPresent(lltok::comma)) {
1242 EltTyLoc = Lex.getLoc();
1243 if (ParseTypeRec(Result)) return true;
1245 if (Result == Type::VoidTy)
1246 return Error(EltTyLoc, "struct element can not have void type");
1248 ParamsList.push_back(Result);
1251 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1254 std::vector<const Type*> ParamsListTy;
1255 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1256 ParamsListTy.push_back(ParamsList[i].get());
1257 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1261 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1262 /// token has already been consumed.
1264 /// ::= '[' APSINTVAL 'x' Types ']'
1265 /// ::= '<' APSINTVAL 'x' Types '>'
1266 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1267 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1268 Lex.getAPSIntVal().getBitWidth() > 64)
1269 return TokError("expected number in address space");
1271 LocTy SizeLoc = Lex.getLoc();
1272 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1275 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1278 LocTy TypeLoc = Lex.getLoc();
1279 PATypeHolder EltTy(Type::VoidTy);
1280 if (ParseTypeRec(EltTy)) return true;
1282 if (EltTy == Type::VoidTy)
1283 return Error(TypeLoc, "array and vector element type cannot be void");
1285 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1286 "expected end of sequential type"))
1291 return Error(SizeLoc, "zero element vector is illegal");
1292 if ((unsigned)Size != Size)
1293 return Error(SizeLoc, "size too large for vector");
1294 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1295 return Error(TypeLoc, "vector element type must be fp or integer");
1296 Result = VectorType::get(EltTy, unsigned(Size));
1298 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1299 return Error(TypeLoc, "invalid array element type");
1300 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1305 //===----------------------------------------------------------------------===//
1306 // Function Semantic Analysis.
1307 //===----------------------------------------------------------------------===//
1309 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1312 // Insert unnamed arguments into the NumberedVals list.
1313 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1316 NumberedVals.push_back(AI);
1319 LLParser::PerFunctionState::~PerFunctionState() {
1320 // If there were any forward referenced non-basicblock values, delete them.
1321 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1322 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1323 if (!isa<BasicBlock>(I->second.first)) {
1324 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1326 delete I->second.first;
1327 I->second.first = 0;
1330 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1331 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1332 if (!isa<BasicBlock>(I->second.first)) {
1333 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1335 delete I->second.first;
1336 I->second.first = 0;
1340 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1341 if (!ForwardRefVals.empty())
1342 return P.Error(ForwardRefVals.begin()->second.second,
1343 "use of undefined value '%" + ForwardRefVals.begin()->first +
1345 if (!ForwardRefValIDs.empty())
1346 return P.Error(ForwardRefValIDs.begin()->second.second,
1347 "use of undefined value '%" +
1348 utostr(ForwardRefValIDs.begin()->first) + "'");
1353 /// GetVal - Get a value with the specified name or ID, creating a
1354 /// forward reference record if needed. This can return null if the value
1355 /// exists but does not have the right type.
1356 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1357 const Type *Ty, LocTy Loc) {
1358 // Look this name up in the normal function symbol table.
1359 Value *Val = F.getValueSymbolTable().lookup(Name);
1361 // If this is a forward reference for the value, see if we already created a
1362 // forward ref record.
1364 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1365 I = ForwardRefVals.find(Name);
1366 if (I != ForwardRefVals.end())
1367 Val = I->second.first;
1370 // If we have the value in the symbol table or fwd-ref table, return it.
1372 if (Val->getType() == Ty) return Val;
1373 if (Ty == Type::LabelTy)
1374 P.Error(Loc, "'%" + Name + "' is not a basic block");
1376 P.Error(Loc, "'%" + Name + "' defined with type '" +
1377 Val->getType()->getDescription() + "'");
1381 // Don't make placeholders with invalid type.
1382 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1383 P.Error(Loc, "invalid use of a non-first-class type");
1387 // Otherwise, create a new forward reference for this value and remember it.
1389 if (Ty == Type::LabelTy)
1390 FwdVal = BasicBlock::Create(Name, &F);
1392 FwdVal = new Argument(Ty, Name);
1394 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1398 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1400 // Look this name up in the normal function symbol table.
1401 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1403 // If this is a forward reference for the value, see if we already created a
1404 // forward ref record.
1406 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1407 I = ForwardRefValIDs.find(ID);
1408 if (I != ForwardRefValIDs.end())
1409 Val = I->second.first;
1412 // If we have the value in the symbol table or fwd-ref table, return it.
1414 if (Val->getType() == Ty) return Val;
1415 if (Ty == Type::LabelTy)
1416 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1418 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1419 Val->getType()->getDescription() + "'");
1423 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1424 P.Error(Loc, "invalid use of a non-first-class type");
1428 // Otherwise, create a new forward reference for this value and remember it.
1430 if (Ty == Type::LabelTy)
1431 FwdVal = BasicBlock::Create("", &F);
1433 FwdVal = new Argument(Ty);
1435 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1439 /// SetInstName - After an instruction is parsed and inserted into its
1440 /// basic block, this installs its name.
1441 bool LLParser::PerFunctionState::SetInstName(int NameID,
1442 const std::string &NameStr,
1443 LocTy NameLoc, Instruction *Inst) {
1444 // If this instruction has void type, it cannot have a name or ID specified.
1445 if (Inst->getType() == Type::VoidTy) {
1446 if (NameID != -1 || !NameStr.empty())
1447 return P.Error(NameLoc, "instructions returning void cannot have a name");
1451 // If this was a numbered instruction, verify that the instruction is the
1452 // expected value and resolve any forward references.
1453 if (NameStr.empty()) {
1454 // If neither a name nor an ID was specified, just use the next ID.
1456 NameID = NumberedVals.size();
1458 if (unsigned(NameID) != NumberedVals.size())
1459 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1460 utostr(NumberedVals.size()) + "'");
1462 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1463 ForwardRefValIDs.find(NameID);
1464 if (FI != ForwardRefValIDs.end()) {
1465 if (FI->second.first->getType() != Inst->getType())
1466 return P.Error(NameLoc, "instruction forward referenced with type '" +
1467 FI->second.first->getType()->getDescription() + "'");
1468 FI->second.first->replaceAllUsesWith(Inst);
1469 ForwardRefValIDs.erase(FI);
1472 NumberedVals.push_back(Inst);
1476 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1477 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1478 FI = ForwardRefVals.find(NameStr);
1479 if (FI != ForwardRefVals.end()) {
1480 if (FI->second.first->getType() != Inst->getType())
1481 return P.Error(NameLoc, "instruction forward referenced with type '" +
1482 FI->second.first->getType()->getDescription() + "'");
1483 FI->second.first->replaceAllUsesWith(Inst);
1484 ForwardRefVals.erase(FI);
1487 // Set the name on the instruction.
1488 Inst->setName(NameStr);
1490 if (Inst->getNameStr() != NameStr)
1491 return P.Error(NameLoc, "multiple definition of local value named '" +
1496 /// GetBB - Get a basic block with the specified name or ID, creating a
1497 /// forward reference record if needed.
1498 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1500 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1503 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1504 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1507 /// DefineBB - Define the specified basic block, which is either named or
1508 /// unnamed. If there is an error, this returns null otherwise it returns
1509 /// the block being defined.
1510 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1514 BB = GetBB(NumberedVals.size(), Loc);
1516 BB = GetBB(Name, Loc);
1517 if (BB == 0) return 0; // Already diagnosed error.
1519 // Move the block to the end of the function. Forward ref'd blocks are
1520 // inserted wherever they happen to be referenced.
1521 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1523 // Remove the block from forward ref sets.
1525 ForwardRefValIDs.erase(NumberedVals.size());
1526 NumberedVals.push_back(BB);
1528 // BB forward references are already in the function symbol table.
1529 ForwardRefVals.erase(Name);
1535 //===----------------------------------------------------------------------===//
1537 //===----------------------------------------------------------------------===//
1539 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1540 /// type implied. For example, if we parse "4" we don't know what integer type
1541 /// it has. The value will later be combined with its type and checked for
1543 bool LLParser::ParseValID(ValID &ID) {
1544 ID.Loc = Lex.getLoc();
1545 switch (Lex.getKind()) {
1546 default: return TokError("expected value token");
1547 case lltok::GlobalID: // @42
1548 ID.UIntVal = Lex.getUIntVal();
1549 ID.Kind = ValID::t_GlobalID;
1551 case lltok::GlobalVar: // @foo
1552 ID.StrVal = Lex.getStrVal();
1553 ID.Kind = ValID::t_GlobalName;
1555 case lltok::LocalVarID: // %42
1556 ID.UIntVal = Lex.getUIntVal();
1557 ID.Kind = ValID::t_LocalID;
1559 case lltok::LocalVar: // %foo
1560 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1561 ID.StrVal = Lex.getStrVal();
1562 ID.Kind = ValID::t_LocalName;
1565 ID.APSIntVal = Lex.getAPSIntVal();
1566 ID.Kind = ValID::t_APSInt;
1568 case lltok::APFloat:
1569 ID.APFloatVal = Lex.getAPFloatVal();
1570 ID.Kind = ValID::t_APFloat;
1572 case lltok::kw_true:
1573 ID.ConstantVal = ConstantInt::getTrue();
1574 ID.Kind = ValID::t_Constant;
1576 case lltok::kw_false:
1577 ID.ConstantVal = ConstantInt::getFalse();
1578 ID.Kind = ValID::t_Constant;
1580 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1581 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1582 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1584 case lltok::lbrace: {
1585 // ValID ::= '{' ConstVector '}'
1587 SmallVector<Constant*, 16> Elts;
1588 if (ParseGlobalValueVector(Elts) ||
1589 ParseToken(lltok::rbrace, "expected end of struct constant"))
1592 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1593 ID.Kind = ValID::t_Constant;
1597 // ValID ::= '<' ConstVector '>' --> Vector.
1598 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1600 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1602 SmallVector<Constant*, 16> Elts;
1603 LocTy FirstEltLoc = Lex.getLoc();
1604 if (ParseGlobalValueVector(Elts) ||
1606 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1607 ParseToken(lltok::greater, "expected end of constant"))
1610 if (isPackedStruct) {
1611 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1612 ID.Kind = ValID::t_Constant;
1617 return Error(ID.Loc, "constant vector must not be empty");
1619 if (!Elts[0]->getType()->isInteger() &&
1620 !Elts[0]->getType()->isFloatingPoint())
1621 return Error(FirstEltLoc,
1622 "vector elements must have integer or floating point type");
1624 // Verify that all the vector elements have the same type.
1625 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1626 if (Elts[i]->getType() != Elts[0]->getType())
1627 return Error(FirstEltLoc,
1628 "vector element #" + utostr(i) +
1629 " is not of type '" + Elts[0]->getType()->getDescription());
1631 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1632 ID.Kind = ValID::t_Constant;
1635 case lltok::lsquare: { // Array Constant
1637 SmallVector<Constant*, 16> Elts;
1638 LocTy FirstEltLoc = Lex.getLoc();
1639 if (ParseGlobalValueVector(Elts) ||
1640 ParseToken(lltok::rsquare, "expected end of array constant"))
1643 // Handle empty element.
1645 // Use undef instead of an array because it's inconvenient to determine
1646 // the element type at this point, there being no elements to examine.
1647 ID.Kind = ValID::t_EmptyArray;
1651 if (!Elts[0]->getType()->isFirstClassType())
1652 return Error(FirstEltLoc, "invalid array element type: " +
1653 Elts[0]->getType()->getDescription());
1655 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1657 // Verify all elements are correct type!
1658 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1659 if (Elts[i]->getType() != Elts[0]->getType())
1660 return Error(FirstEltLoc,
1661 "array element #" + utostr(i) +
1662 " is not of type '" +Elts[0]->getType()->getDescription());
1665 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1666 ID.Kind = ValID::t_Constant;
1669 case lltok::kw_c: // c "foo"
1671 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1672 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1673 ID.Kind = ValID::t_Constant;
1676 case lltok::kw_asm: {
1677 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1680 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1681 ParseStringConstant(ID.StrVal) ||
1682 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1683 ParseToken(lltok::StringConstant, "expected constraint string"))
1685 ID.StrVal2 = Lex.getStrVal();
1686 ID.UIntVal = HasSideEffect;
1687 ID.Kind = ValID::t_InlineAsm;
1691 case lltok::kw_trunc:
1692 case lltok::kw_zext:
1693 case lltok::kw_sext:
1694 case lltok::kw_fptrunc:
1695 case lltok::kw_fpext:
1696 case lltok::kw_bitcast:
1697 case lltok::kw_uitofp:
1698 case lltok::kw_sitofp:
1699 case lltok::kw_fptoui:
1700 case lltok::kw_fptosi:
1701 case lltok::kw_inttoptr:
1702 case lltok::kw_ptrtoint: {
1703 unsigned Opc = Lex.getUIntVal();
1704 PATypeHolder DestTy(Type::VoidTy);
1707 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1708 ParseGlobalTypeAndValue(SrcVal) ||
1709 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1710 ParseType(DestTy) ||
1711 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1713 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1714 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1715 SrcVal->getType()->getDescription() + "' to '" +
1716 DestTy->getDescription() + "'");
1717 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1719 ID.Kind = ValID::t_Constant;
1722 case lltok::kw_extractvalue: {
1725 SmallVector<unsigned, 4> Indices;
1726 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1727 ParseGlobalTypeAndValue(Val) ||
1728 ParseIndexList(Indices) ||
1729 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1731 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1732 return Error(ID.Loc, "extractvalue operand must be array or struct");
1733 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1735 return Error(ID.Loc, "invalid indices for extractvalue");
1736 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1737 &Indices[0], Indices.size());
1738 ID.Kind = ValID::t_Constant;
1741 case lltok::kw_insertvalue: {
1743 Constant *Val0, *Val1;
1744 SmallVector<unsigned, 4> Indices;
1745 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1746 ParseGlobalTypeAndValue(Val0) ||
1747 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1748 ParseGlobalTypeAndValue(Val1) ||
1749 ParseIndexList(Indices) ||
1750 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1752 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1753 return Error(ID.Loc, "extractvalue operand must be array or struct");
1754 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1756 return Error(ID.Loc, "invalid indices for insertvalue");
1757 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1758 &Indices[0], Indices.size());
1759 ID.Kind = ValID::t_Constant;
1762 case lltok::kw_icmp:
1763 case lltok::kw_fcmp:
1764 case lltok::kw_vicmp:
1765 case lltok::kw_vfcmp: {
1766 unsigned PredVal, Opc = Lex.getUIntVal();
1767 Constant *Val0, *Val1;
1769 if (ParseCmpPredicate(PredVal, Opc) ||
1770 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1771 ParseGlobalTypeAndValue(Val0) ||
1772 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1773 ParseGlobalTypeAndValue(Val1) ||
1774 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1777 if (Val0->getType() != Val1->getType())
1778 return Error(ID.Loc, "compare operands must have the same type");
1780 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1782 if (Opc == Instruction::FCmp) {
1783 if (!Val0->getType()->isFPOrFPVector())
1784 return Error(ID.Loc, "fcmp requires floating point operands");
1785 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1786 } else if (Opc == Instruction::ICmp) {
1787 if (!Val0->getType()->isIntOrIntVector() &&
1788 !isa<PointerType>(Val0->getType()))
1789 return Error(ID.Loc, "icmp requires pointer or integer operands");
1790 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1791 } else if (Opc == Instruction::VFCmp) {
1792 // FIXME: REMOVE VFCMP Support
1793 if (!Val0->getType()->isFPOrFPVector() ||
1794 !isa<VectorType>(Val0->getType()))
1795 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1796 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1797 } else if (Opc == Instruction::VICmp) {
1798 // FIXME: REMOVE VICMP Support
1799 if (!Val0->getType()->isIntOrIntVector() ||
1800 !isa<VectorType>(Val0->getType()))
1801 return Error(ID.Loc, "vicmp requires vector floating point operands");
1802 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1804 ID.Kind = ValID::t_Constant;
1808 // Binary Operators.
1812 case lltok::kw_udiv:
1813 case lltok::kw_sdiv:
1814 case lltok::kw_fdiv:
1815 case lltok::kw_urem:
1816 case lltok::kw_srem:
1817 case lltok::kw_frem: {
1818 unsigned Opc = Lex.getUIntVal();
1819 Constant *Val0, *Val1;
1821 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1822 ParseGlobalTypeAndValue(Val0) ||
1823 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1824 ParseGlobalTypeAndValue(Val1) ||
1825 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1827 if (Val0->getType() != Val1->getType())
1828 return Error(ID.Loc, "operands of constexpr must have same type");
1829 if (!Val0->getType()->isIntOrIntVector() &&
1830 !Val0->getType()->isFPOrFPVector())
1831 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1832 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1833 ID.Kind = ValID::t_Constant;
1837 // Logical Operations
1839 case lltok::kw_lshr:
1840 case lltok::kw_ashr:
1843 case lltok::kw_xor: {
1844 unsigned Opc = Lex.getUIntVal();
1845 Constant *Val0, *Val1;
1847 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1848 ParseGlobalTypeAndValue(Val0) ||
1849 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1850 ParseGlobalTypeAndValue(Val1) ||
1851 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1853 if (Val0->getType() != Val1->getType())
1854 return Error(ID.Loc, "operands of constexpr must have same type");
1855 if (!Val0->getType()->isIntOrIntVector())
1856 return Error(ID.Loc,
1857 "constexpr requires integer or integer vector operands");
1858 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1859 ID.Kind = ValID::t_Constant;
1863 case lltok::kw_getelementptr:
1864 case lltok::kw_shufflevector:
1865 case lltok::kw_insertelement:
1866 case lltok::kw_extractelement:
1867 case lltok::kw_select: {
1868 unsigned Opc = Lex.getUIntVal();
1869 SmallVector<Constant*, 16> Elts;
1871 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1872 ParseGlobalValueVector(Elts) ||
1873 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1876 if (Opc == Instruction::GetElementPtr) {
1877 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1878 return Error(ID.Loc, "getelementptr requires pointer operand");
1880 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1881 (Value**)&Elts[1], Elts.size()-1))
1882 return Error(ID.Loc, "invalid indices for getelementptr");
1883 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1884 &Elts[1], Elts.size()-1);
1885 } else if (Opc == Instruction::Select) {
1886 if (Elts.size() != 3)
1887 return Error(ID.Loc, "expected three operands to select");
1888 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1890 return Error(ID.Loc, Reason);
1891 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1892 } else if (Opc == Instruction::ShuffleVector) {
1893 if (Elts.size() != 3)
1894 return Error(ID.Loc, "expected three operands to shufflevector");
1895 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1896 return Error(ID.Loc, "invalid operands to shufflevector");
1897 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1898 } else if (Opc == Instruction::ExtractElement) {
1899 if (Elts.size() != 2)
1900 return Error(ID.Loc, "expected two operands to extractelement");
1901 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1902 return Error(ID.Loc, "invalid extractelement operands");
1903 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1905 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1906 if (Elts.size() != 3)
1907 return Error(ID.Loc, "expected three operands to insertelement");
1908 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1909 return Error(ID.Loc, "invalid insertelement operands");
1910 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1913 ID.Kind = ValID::t_Constant;
1922 /// ParseGlobalValue - Parse a global value with the specified type.
1923 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1926 return ParseValID(ID) ||
1927 ConvertGlobalValIDToValue(Ty, ID, V);
1930 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1932 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1934 if (isa<FunctionType>(Ty))
1935 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1938 default: assert(0 && "Unknown ValID!");
1939 case ValID::t_LocalID:
1940 case ValID::t_LocalName:
1941 return Error(ID.Loc, "invalid use of function-local name");
1942 case ValID::t_InlineAsm:
1943 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1944 case ValID::t_GlobalName:
1945 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1947 case ValID::t_GlobalID:
1948 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1950 case ValID::t_APSInt:
1951 if (!isa<IntegerType>(Ty))
1952 return Error(ID.Loc, "integer constant must have integer type");
1953 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1954 V = ConstantInt::get(ID.APSIntVal);
1956 case ValID::t_APFloat:
1957 if (!Ty->isFloatingPoint() ||
1958 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1959 return Error(ID.Loc, "floating point constant invalid for type");
1961 // The lexer has no type info, so builds all float and double FP constants
1962 // as double. Fix this here. Long double does not need this.
1963 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1964 Ty == Type::FloatTy) {
1966 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1969 V = ConstantFP::get(ID.APFloatVal);
1971 if (V->getType() != Ty)
1972 return Error(ID.Loc, "floating point constant does not have type '" +
1973 Ty->getDescription() + "'");
1977 if (!isa<PointerType>(Ty))
1978 return Error(ID.Loc, "null must be a pointer type");
1979 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1981 case ValID::t_Undef:
1982 // FIXME: LabelTy should not be a first-class type.
1983 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1984 !isa<OpaqueType>(Ty))
1985 return Error(ID.Loc, "invalid type for undef constant");
1986 V = UndefValue::get(Ty);
1988 case ValID::t_EmptyArray:
1989 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1990 return Error(ID.Loc, "invalid empty array initializer");
1991 V = UndefValue::get(Ty);
1994 // FIXME: LabelTy should not be a first-class type.
1995 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1996 return Error(ID.Loc, "invalid type for null constant");
1997 V = Constant::getNullValue(Ty);
1999 case ValID::t_Constant:
2000 if (ID.ConstantVal->getType() != Ty)
2001 return Error(ID.Loc, "constant expression type mismatch");
2007 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2008 PATypeHolder Type(Type::VoidTy);
2009 return ParseType(Type) ||
2010 ParseGlobalValue(Type, V);
2013 /// ParseGlobalValueVector
2015 /// ::= TypeAndValue (',' TypeAndValue)*
2016 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2018 if (Lex.getKind() == lltok::rbrace ||
2019 Lex.getKind() == lltok::rsquare ||
2020 Lex.getKind() == lltok::greater ||
2021 Lex.getKind() == lltok::rparen)
2025 if (ParseGlobalTypeAndValue(C)) return true;
2028 while (EatIfPresent(lltok::comma)) {
2029 if (ParseGlobalTypeAndValue(C)) return true;
2037 //===----------------------------------------------------------------------===//
2038 // Function Parsing.
2039 //===----------------------------------------------------------------------===//
2041 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2042 PerFunctionState &PFS) {
2043 if (ID.Kind == ValID::t_LocalID)
2044 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2045 else if (ID.Kind == ValID::t_LocalName)
2046 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2047 else if (ID.Kind == ValID::t_InlineAsm) {
2048 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2049 const FunctionType *FTy =
2050 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2051 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2052 return Error(ID.Loc, "invalid type for inline asm constraint string");
2053 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2057 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2065 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2068 return ParseValID(ID) ||
2069 ConvertValIDToValue(Ty, ID, V, PFS);
2072 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2073 PATypeHolder T(Type::VoidTy);
2074 return ParseType(T) ||
2075 ParseValue(T, V, PFS);
2079 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2080 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2081 /// OptionalAlign OptGC
2082 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2083 // Parse the linkage.
2084 LocTy LinkageLoc = Lex.getLoc();
2087 unsigned Visibility, CC, RetAttrs;
2088 PATypeHolder RetType(Type::VoidTy);
2089 LocTy RetTypeLoc = Lex.getLoc();
2090 if (ParseOptionalLinkage(Linkage) ||
2091 ParseOptionalVisibility(Visibility) ||
2092 ParseOptionalCallingConv(CC) ||
2093 ParseOptionalAttrs(RetAttrs, 1) ||
2094 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2097 // Verify that the linkage is ok.
2098 switch ((GlobalValue::LinkageTypes)Linkage) {
2099 case GlobalValue::ExternalLinkage:
2100 break; // always ok.
2101 case GlobalValue::DLLImportLinkage:
2102 case GlobalValue::ExternalWeakLinkage:
2104 return Error(LinkageLoc, "invalid linkage for function definition");
2106 case GlobalValue::PrivateLinkage:
2107 case GlobalValue::InternalLinkage:
2108 case GlobalValue::LinkOnceAnyLinkage:
2109 case GlobalValue::LinkOnceODRLinkage:
2110 case GlobalValue::WeakAnyLinkage:
2111 case GlobalValue::WeakODRLinkage:
2112 case GlobalValue::DLLExportLinkage:
2114 return Error(LinkageLoc, "invalid linkage for function declaration");
2116 case GlobalValue::AppendingLinkage:
2117 case GlobalValue::GhostLinkage:
2118 case GlobalValue::CommonLinkage:
2119 return Error(LinkageLoc, "invalid function linkage type");
2122 if (!FunctionType::isValidReturnType(RetType) ||
2123 isa<OpaqueType>(RetType))
2124 return Error(RetTypeLoc, "invalid function return type");
2126 LocTy NameLoc = Lex.getLoc();
2128 std::string FunctionName;
2129 if (Lex.getKind() == lltok::GlobalVar) {
2130 FunctionName = Lex.getStrVal();
2131 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2132 unsigned NameID = Lex.getUIntVal();
2134 if (NameID != NumberedVals.size())
2135 return TokError("function expected to be numbered '%" +
2136 utostr(NumberedVals.size()) + "'");
2138 return TokError("expected function name");
2143 if (Lex.getKind() != lltok::lparen)
2144 return TokError("expected '(' in function argument list");
2146 std::vector<ArgInfo> ArgList;
2149 std::string Section;
2153 if (ParseArgumentList(ArgList, isVarArg, false) ||
2154 ParseOptionalAttrs(FuncAttrs, 2) ||
2155 (EatIfPresent(lltok::kw_section) &&
2156 ParseStringConstant(Section)) ||
2157 ParseOptionalAlignment(Alignment) ||
2158 (EatIfPresent(lltok::kw_gc) &&
2159 ParseStringConstant(GC)))
2162 // If the alignment was parsed as an attribute, move to the alignment field.
2163 if (FuncAttrs & Attribute::Alignment) {
2164 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2165 FuncAttrs &= ~Attribute::Alignment;
2168 // Okay, if we got here, the function is syntactically valid. Convert types
2169 // and do semantic checks.
2170 std::vector<const Type*> ParamTypeList;
2171 SmallVector<AttributeWithIndex, 8> Attrs;
2172 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2174 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2175 if (FuncAttrs & ObsoleteFuncAttrs) {
2176 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2177 FuncAttrs &= ~ObsoleteFuncAttrs;
2180 if (RetAttrs != Attribute::None)
2181 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2183 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2184 ParamTypeList.push_back(ArgList[i].Type);
2185 if (ArgList[i].Attrs != Attribute::None)
2186 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2189 if (FuncAttrs != Attribute::None)
2190 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2192 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2194 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2195 RetType != Type::VoidTy)
2196 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2198 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2199 const PointerType *PFT = PointerType::getUnqual(FT);
2202 if (!FunctionName.empty()) {
2203 // If this was a definition of a forward reference, remove the definition
2204 // from the forward reference table and fill in the forward ref.
2205 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2206 ForwardRefVals.find(FunctionName);
2207 if (FRVI != ForwardRefVals.end()) {
2208 Fn = M->getFunction(FunctionName);
2209 ForwardRefVals.erase(FRVI);
2210 } else if ((Fn = M->getFunction(FunctionName))) {
2211 // If this function already exists in the symbol table, then it is
2212 // multiply defined. We accept a few cases for old backwards compat.
2213 // FIXME: Remove this stuff for LLVM 3.0.
2214 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2215 (!Fn->isDeclaration() && isDefine)) {
2216 // If the redefinition has different type or different attributes,
2217 // reject it. If both have bodies, reject it.
2218 return Error(NameLoc, "invalid redefinition of function '" +
2219 FunctionName + "'");
2220 } else if (Fn->isDeclaration()) {
2221 // Make sure to strip off any argument names so we can't get conflicts.
2222 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2228 } else if (FunctionName.empty()) {
2229 // If this is a definition of a forward referenced function, make sure the
2231 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2232 = ForwardRefValIDs.find(NumberedVals.size());
2233 if (I != ForwardRefValIDs.end()) {
2234 Fn = cast<Function>(I->second.first);
2235 if (Fn->getType() != PFT)
2236 return Error(NameLoc, "type of definition and forward reference of '@" +
2237 utostr(NumberedVals.size()) +"' disagree");
2238 ForwardRefValIDs.erase(I);
2243 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2244 else // Move the forward-reference to the correct spot in the module.
2245 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2247 if (FunctionName.empty())
2248 NumberedVals.push_back(Fn);
2250 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2251 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2252 Fn->setCallingConv(CC);
2253 Fn->setAttributes(PAL);
2254 Fn->setAlignment(Alignment);
2255 Fn->setSection(Section);
2256 if (!GC.empty()) Fn->setGC(GC.c_str());
2258 // Add all of the arguments we parsed to the function.
2259 Function::arg_iterator ArgIt = Fn->arg_begin();
2260 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2261 // If the argument has a name, insert it into the argument symbol table.
2262 if (ArgList[i].Name.empty()) continue;
2264 // Set the name, if it conflicted, it will be auto-renamed.
2265 ArgIt->setName(ArgList[i].Name);
2267 if (ArgIt->getNameStr() != ArgList[i].Name)
2268 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2269 ArgList[i].Name + "'");
2276 /// ParseFunctionBody
2277 /// ::= '{' BasicBlock+ '}'
2278 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2280 bool LLParser::ParseFunctionBody(Function &Fn) {
2281 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2282 return TokError("expected '{' in function body");
2283 Lex.Lex(); // eat the {.
2285 PerFunctionState PFS(*this, Fn);
2287 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2288 if (ParseBasicBlock(PFS)) return true;
2293 // Verify function is ok.
2294 return PFS.VerifyFunctionComplete();
2298 /// ::= LabelStr? Instruction*
2299 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2300 // If this basic block starts out with a name, remember it.
2302 LocTy NameLoc = Lex.getLoc();
2303 if (Lex.getKind() == lltok::LabelStr) {
2304 Name = Lex.getStrVal();
2308 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2309 if (BB == 0) return true;
2311 std::string NameStr;
2313 // Parse the instructions in this block until we get a terminator.
2316 // This instruction may have three possibilities for a name: a) none
2317 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2318 LocTy NameLoc = Lex.getLoc();
2322 if (Lex.getKind() == lltok::LocalVarID) {
2323 NameID = Lex.getUIntVal();
2325 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2327 } else if (Lex.getKind() == lltok::LocalVar ||
2328 // FIXME: REMOVE IN LLVM 3.0
2329 Lex.getKind() == lltok::StringConstant) {
2330 NameStr = Lex.getStrVal();
2332 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2336 if (ParseInstruction(Inst, BB, PFS)) return true;
2338 BB->getInstList().push_back(Inst);
2340 // Set the name on the instruction.
2341 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2342 } while (!isa<TerminatorInst>(Inst));
2347 //===----------------------------------------------------------------------===//
2348 // Instruction Parsing.
2349 //===----------------------------------------------------------------------===//
2351 /// ParseInstruction - Parse one of the many different instructions.
2353 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2354 PerFunctionState &PFS) {
2355 lltok::Kind Token = Lex.getKind();
2356 if (Token == lltok::Eof)
2357 return TokError("found end of file when expecting more instructions");
2358 LocTy Loc = Lex.getLoc();
2359 unsigned KeywordVal = Lex.getUIntVal();
2360 Lex.Lex(); // Eat the keyword.
2363 default: return Error(Loc, "expected instruction opcode");
2364 // Terminator Instructions.
2365 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2366 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2367 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2368 case lltok::kw_br: return ParseBr(Inst, PFS);
2369 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2370 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2371 // Binary Operators.
2374 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2376 case lltok::kw_udiv:
2377 case lltok::kw_sdiv:
2378 case lltok::kw_urem:
2379 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2380 case lltok::kw_fdiv:
2381 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2383 case lltok::kw_lshr:
2384 case lltok::kw_ashr:
2387 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2388 case lltok::kw_icmp:
2389 case lltok::kw_fcmp:
2390 case lltok::kw_vicmp:
2391 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
2393 case lltok::kw_trunc:
2394 case lltok::kw_zext:
2395 case lltok::kw_sext:
2396 case lltok::kw_fptrunc:
2397 case lltok::kw_fpext:
2398 case lltok::kw_bitcast:
2399 case lltok::kw_uitofp:
2400 case lltok::kw_sitofp:
2401 case lltok::kw_fptoui:
2402 case lltok::kw_fptosi:
2403 case lltok::kw_inttoptr:
2404 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2406 case lltok::kw_select: return ParseSelect(Inst, PFS);
2407 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2408 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2409 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2410 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2411 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2412 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2413 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2415 case lltok::kw_alloca:
2416 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2417 case lltok::kw_free: return ParseFree(Inst, PFS);
2418 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2419 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2420 case lltok::kw_volatile:
2421 if (EatIfPresent(lltok::kw_load))
2422 return ParseLoad(Inst, PFS, true);
2423 else if (EatIfPresent(lltok::kw_store))
2424 return ParseStore(Inst, PFS, true);
2426 return TokError("expected 'load' or 'store'");
2427 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2428 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2429 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2430 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2434 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2435 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2436 // FIXME: REMOVE vicmp/vfcmp!
2437 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2438 switch (Lex.getKind()) {
2439 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2440 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2441 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2442 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2443 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2444 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2445 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2446 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2447 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2448 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2449 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2450 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2451 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2452 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2453 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2454 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2455 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2458 switch (Lex.getKind()) {
2459 default: TokError("expected icmp predicate (e.g. 'eq')");
2460 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2461 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2462 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2463 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2464 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2465 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2466 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2467 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2468 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2469 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2476 //===----------------------------------------------------------------------===//
2477 // Terminator Instructions.
2478 //===----------------------------------------------------------------------===//
2480 /// ParseRet - Parse a return instruction.
2482 /// ::= 'ret' TypeAndValue
2483 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2484 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2485 PerFunctionState &PFS) {
2486 PATypeHolder Ty(Type::VoidTy);
2487 if (ParseType(Ty, true /*void allowed*/)) return true;
2489 if (Ty == Type::VoidTy) {
2490 Inst = ReturnInst::Create();
2495 if (ParseValue(Ty, RV, PFS)) return true;
2497 // The normal case is one return value.
2498 if (Lex.getKind() == lltok::comma) {
2499 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2500 // of 'ret {i32,i32} {i32 1, i32 2}'
2501 SmallVector<Value*, 8> RVs;
2504 while (EatIfPresent(lltok::comma)) {
2505 if (ParseTypeAndValue(RV, PFS)) return true;
2509 RV = UndefValue::get(PFS.getFunction().getReturnType());
2510 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2511 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2512 BB->getInstList().push_back(I);
2516 Inst = ReturnInst::Create(RV);
2522 /// ::= 'br' TypeAndValue
2523 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2524 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2526 Value *Op0, *Op1, *Op2;
2527 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2529 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2530 Inst = BranchInst::Create(BB);
2534 if (Op0->getType() != Type::Int1Ty)
2535 return Error(Loc, "branch condition must have 'i1' type");
2537 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2538 ParseTypeAndValue(Op1, Loc, PFS) ||
2539 ParseToken(lltok::comma, "expected ',' after true destination") ||
2540 ParseTypeAndValue(Op2, Loc2, PFS))
2543 if (!isa<BasicBlock>(Op1))
2544 return Error(Loc, "true destination of branch must be a basic block");
2545 if (!isa<BasicBlock>(Op2))
2546 return Error(Loc2, "true destination of branch must be a basic block");
2548 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2554 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2556 /// ::= (TypeAndValue ',' TypeAndValue)*
2557 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2558 LocTy CondLoc, BBLoc;
2559 Value *Cond, *DefaultBB;
2560 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2561 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2562 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2563 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2566 if (!isa<IntegerType>(Cond->getType()))
2567 return Error(CondLoc, "switch condition must have integer type");
2568 if (!isa<BasicBlock>(DefaultBB))
2569 return Error(BBLoc, "default destination must be a basic block");
2571 // Parse the jump table pairs.
2572 SmallPtrSet<Value*, 32> SeenCases;
2573 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2574 while (Lex.getKind() != lltok::rsquare) {
2575 Value *Constant, *DestBB;
2577 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2578 ParseToken(lltok::comma, "expected ',' after case value") ||
2579 ParseTypeAndValue(DestBB, BBLoc, PFS))
2582 if (!SeenCases.insert(Constant))
2583 return Error(CondLoc, "duplicate case value in switch");
2584 if (!isa<ConstantInt>(Constant))
2585 return Error(CondLoc, "case value is not a constant integer");
2586 if (!isa<BasicBlock>(DestBB))
2587 return Error(BBLoc, "case destination is not a basic block");
2589 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2590 cast<BasicBlock>(DestBB)));
2593 Lex.Lex(); // Eat the ']'.
2595 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2597 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2598 SI->addCase(Table[i].first, Table[i].second);
2604 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2605 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2606 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2607 LocTy CallLoc = Lex.getLoc();
2608 unsigned CC, RetAttrs, FnAttrs;
2609 PATypeHolder RetType(Type::VoidTy);
2612 SmallVector<ParamInfo, 16> ArgList;
2614 Value *NormalBB, *UnwindBB;
2615 if (ParseOptionalCallingConv(CC) ||
2616 ParseOptionalAttrs(RetAttrs, 1) ||
2617 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2618 ParseValID(CalleeID) ||
2619 ParseParameterList(ArgList, PFS) ||
2620 ParseOptionalAttrs(FnAttrs, 2) ||
2621 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2622 ParseTypeAndValue(NormalBB, PFS) ||
2623 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2624 ParseTypeAndValue(UnwindBB, PFS))
2627 if (!isa<BasicBlock>(NormalBB))
2628 return Error(CallLoc, "normal destination is not a basic block");
2629 if (!isa<BasicBlock>(UnwindBB))
2630 return Error(CallLoc, "unwind destination is not a basic block");
2632 // If RetType is a non-function pointer type, then this is the short syntax
2633 // for the call, which means that RetType is just the return type. Infer the
2634 // rest of the function argument types from the arguments that are present.
2635 const PointerType *PFTy = 0;
2636 const FunctionType *Ty = 0;
2637 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2638 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2639 // Pull out the types of all of the arguments...
2640 std::vector<const Type*> ParamTypes;
2641 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2642 ParamTypes.push_back(ArgList[i].V->getType());
2644 if (!FunctionType::isValidReturnType(RetType))
2645 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2647 Ty = FunctionType::get(RetType, ParamTypes, false);
2648 PFTy = PointerType::getUnqual(Ty);
2651 // Look up the callee.
2653 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2655 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2656 // function attributes.
2657 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2658 if (FnAttrs & ObsoleteFuncAttrs) {
2659 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2660 FnAttrs &= ~ObsoleteFuncAttrs;
2663 // Set up the Attributes for the function.
2664 SmallVector<AttributeWithIndex, 8> Attrs;
2665 if (RetAttrs != Attribute::None)
2666 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2668 SmallVector<Value*, 8> Args;
2670 // Loop through FunctionType's arguments and ensure they are specified
2671 // correctly. Also, gather any parameter attributes.
2672 FunctionType::param_iterator I = Ty->param_begin();
2673 FunctionType::param_iterator E = Ty->param_end();
2674 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2675 const Type *ExpectedTy = 0;
2678 } else if (!Ty->isVarArg()) {
2679 return Error(ArgList[i].Loc, "too many arguments specified");
2682 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2683 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2684 ExpectedTy->getDescription() + "'");
2685 Args.push_back(ArgList[i].V);
2686 if (ArgList[i].Attrs != Attribute::None)
2687 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2691 return Error(CallLoc, "not enough parameters specified for call");
2693 if (FnAttrs != Attribute::None)
2694 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2696 // Finish off the Attributes and check them
2697 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2699 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2700 cast<BasicBlock>(UnwindBB),
2701 Args.begin(), Args.end());
2702 II->setCallingConv(CC);
2703 II->setAttributes(PAL);
2710 //===----------------------------------------------------------------------===//
2711 // Binary Operators.
2712 //===----------------------------------------------------------------------===//
2715 /// ::= ArithmeticOps TypeAndValue ',' Value
2717 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2718 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2719 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2720 unsigned Opc, unsigned OperandType) {
2721 LocTy Loc; Value *LHS, *RHS;
2722 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2723 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2724 ParseValue(LHS->getType(), RHS, PFS))
2728 switch (OperandType) {
2729 default: assert(0 && "Unknown operand type!");
2730 case 0: // int or FP.
2731 Valid = LHS->getType()->isIntOrIntVector() ||
2732 LHS->getType()->isFPOrFPVector();
2734 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2735 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2739 return Error(Loc, "invalid operand type for instruction");
2741 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2746 /// ::= ArithmeticOps TypeAndValue ',' Value {
2747 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2749 LocTy Loc; Value *LHS, *RHS;
2750 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2751 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2752 ParseValue(LHS->getType(), RHS, PFS))
2755 if (!LHS->getType()->isIntOrIntVector())
2756 return Error(Loc,"instruction requires integer or integer vector operands");
2758 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2764 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2765 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2766 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2767 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2768 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2770 // Parse the integer/fp comparison predicate.
2774 if (ParseCmpPredicate(Pred, Opc) ||
2775 ParseTypeAndValue(LHS, Loc, PFS) ||
2776 ParseToken(lltok::comma, "expected ',' after compare value") ||
2777 ParseValue(LHS->getType(), RHS, PFS))
2780 if (Opc == Instruction::FCmp) {
2781 if (!LHS->getType()->isFPOrFPVector())
2782 return Error(Loc, "fcmp requires floating point operands");
2783 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2784 } else if (Opc == Instruction::ICmp) {
2785 if (!LHS->getType()->isIntOrIntVector() &&
2786 !isa<PointerType>(LHS->getType()))
2787 return Error(Loc, "icmp requires integer operands");
2788 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2789 } else if (Opc == Instruction::VFCmp) {
2790 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2791 return Error(Loc, "vfcmp requires vector floating point operands");
2792 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2793 } else if (Opc == Instruction::VICmp) {
2794 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2795 return Error(Loc, "vicmp requires vector floating point operands");
2796 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2801 //===----------------------------------------------------------------------===//
2802 // Other Instructions.
2803 //===----------------------------------------------------------------------===//
2807 /// ::= CastOpc TypeAndValue 'to' Type
2808 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2810 LocTy Loc; Value *Op;
2811 PATypeHolder DestTy(Type::VoidTy);
2812 if (ParseTypeAndValue(Op, Loc, PFS) ||
2813 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2817 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2818 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2819 return Error(Loc, "invalid cast opcode for cast from '" +
2820 Op->getType()->getDescription() + "' to '" +
2821 DestTy->getDescription() + "'");
2823 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2828 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2829 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2831 Value *Op0, *Op1, *Op2;
2832 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2833 ParseToken(lltok::comma, "expected ',' after select condition") ||
2834 ParseTypeAndValue(Op1, PFS) ||
2835 ParseToken(lltok::comma, "expected ',' after select value") ||
2836 ParseTypeAndValue(Op2, PFS))
2839 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2840 return Error(Loc, Reason);
2842 Inst = SelectInst::Create(Op0, Op1, Op2);
2847 /// ::= 'va_arg' TypeAndValue ',' Type
2848 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2850 PATypeHolder EltTy(Type::VoidTy);
2852 if (ParseTypeAndValue(Op, PFS) ||
2853 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2854 ParseType(EltTy, TypeLoc))
2857 if (!EltTy->isFirstClassType())
2858 return Error(TypeLoc, "va_arg requires operand with first class type");
2860 Inst = new VAArgInst(Op, EltTy);
2864 /// ParseExtractElement
2865 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2866 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2869 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2870 ParseToken(lltok::comma, "expected ',' after extract value") ||
2871 ParseTypeAndValue(Op1, PFS))
2874 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2875 return Error(Loc, "invalid extractelement operands");
2877 Inst = new ExtractElementInst(Op0, Op1);
2881 /// ParseInsertElement
2882 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2883 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2885 Value *Op0, *Op1, *Op2;
2886 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2887 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2888 ParseTypeAndValue(Op1, PFS) ||
2889 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2890 ParseTypeAndValue(Op2, PFS))
2893 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2894 return Error(Loc, "invalid extractelement operands");
2896 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2900 /// ParseShuffleVector
2901 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2902 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2904 Value *Op0, *Op1, *Op2;
2905 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2906 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2907 ParseTypeAndValue(Op1, PFS) ||
2908 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2909 ParseTypeAndValue(Op2, PFS))
2912 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2913 return Error(Loc, "invalid extractelement operands");
2915 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2920 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2921 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2922 PATypeHolder Ty(Type::VoidTy);
2924 LocTy TypeLoc = Lex.getLoc();
2926 if (ParseType(Ty) ||
2927 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2928 ParseValue(Ty, Op0, PFS) ||
2929 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2930 ParseValue(Type::LabelTy, Op1, PFS) ||
2931 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2934 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2936 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2938 if (!EatIfPresent(lltok::comma))
2941 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2942 ParseValue(Ty, Op0, PFS) ||
2943 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2944 ParseValue(Type::LabelTy, Op1, PFS) ||
2945 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2949 if (!Ty->isFirstClassType())
2950 return Error(TypeLoc, "phi node must have first class type");
2952 PHINode *PN = PHINode::Create(Ty);
2953 PN->reserveOperandSpace(PHIVals.size());
2954 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2955 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2961 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2962 /// ParameterList OptionalAttrs
2963 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2965 unsigned CC, RetAttrs, FnAttrs;
2966 PATypeHolder RetType(Type::VoidTy);
2969 SmallVector<ParamInfo, 16> ArgList;
2970 LocTy CallLoc = Lex.getLoc();
2972 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2973 ParseOptionalCallingConv(CC) ||
2974 ParseOptionalAttrs(RetAttrs, 1) ||
2975 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2976 ParseValID(CalleeID) ||
2977 ParseParameterList(ArgList, PFS) ||
2978 ParseOptionalAttrs(FnAttrs, 2))
2981 // If RetType is a non-function pointer type, then this is the short syntax
2982 // for the call, which means that RetType is just the return type. Infer the
2983 // rest of the function argument types from the arguments that are present.
2984 const PointerType *PFTy = 0;
2985 const FunctionType *Ty = 0;
2986 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2987 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2988 // Pull out the types of all of the arguments...
2989 std::vector<const Type*> ParamTypes;
2990 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2991 ParamTypes.push_back(ArgList[i].V->getType());
2993 if (!FunctionType::isValidReturnType(RetType))
2994 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2996 Ty = FunctionType::get(RetType, ParamTypes, false);
2997 PFTy = PointerType::getUnqual(Ty);
3000 // Look up the callee.
3002 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3004 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3005 // function attributes.
3006 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3007 if (FnAttrs & ObsoleteFuncAttrs) {
3008 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3009 FnAttrs &= ~ObsoleteFuncAttrs;
3012 // Set up the Attributes for the function.
3013 SmallVector<AttributeWithIndex, 8> Attrs;
3014 if (RetAttrs != Attribute::None)
3015 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3017 SmallVector<Value*, 8> Args;
3019 // Loop through FunctionType's arguments and ensure they are specified
3020 // correctly. Also, gather any parameter attributes.
3021 FunctionType::param_iterator I = Ty->param_begin();
3022 FunctionType::param_iterator E = Ty->param_end();
3023 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3024 const Type *ExpectedTy = 0;
3027 } else if (!Ty->isVarArg()) {
3028 return Error(ArgList[i].Loc, "too many arguments specified");
3031 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3032 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3033 ExpectedTy->getDescription() + "'");
3034 Args.push_back(ArgList[i].V);
3035 if (ArgList[i].Attrs != Attribute::None)
3036 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3040 return Error(CallLoc, "not enough parameters specified for call");
3042 if (FnAttrs != Attribute::None)
3043 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3045 // Finish off the Attributes and check them
3046 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3048 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3049 CI->setTailCall(isTail);
3050 CI->setCallingConv(CC);
3051 CI->setAttributes(PAL);
3056 //===----------------------------------------------------------------------===//
3057 // Memory Instructions.
3058 //===----------------------------------------------------------------------===//
3061 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3062 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3063 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3065 PATypeHolder Ty(Type::VoidTy);
3068 unsigned Alignment = 0;
3069 if (ParseType(Ty)) return true;
3071 if (EatIfPresent(lltok::comma)) {
3072 if (Lex.getKind() == lltok::kw_align) {
3073 if (ParseOptionalAlignment(Alignment)) return true;
3074 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3075 ParseOptionalCommaAlignment(Alignment)) {
3080 if (Size && Size->getType() != Type::Int32Ty)
3081 return Error(SizeLoc, "element count must be i32");
3083 if (Opc == Instruction::Malloc)
3084 Inst = new MallocInst(Ty, Size, Alignment);
3086 Inst = new AllocaInst(Ty, Size, Alignment);
3091 /// ::= 'free' TypeAndValue
3092 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3093 Value *Val; LocTy Loc;
3094 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3095 if (!isa<PointerType>(Val->getType()))
3096 return Error(Loc, "operand to free must be a pointer");
3097 Inst = new FreeInst(Val);
3102 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3103 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3105 Value *Val; LocTy Loc;
3107 if (ParseTypeAndValue(Val, Loc, PFS) ||
3108 ParseOptionalCommaAlignment(Alignment))
3111 if (!isa<PointerType>(Val->getType()) ||
3112 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3113 return Error(Loc, "load operand must be a pointer to a first class type");
3115 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3120 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3121 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3123 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3125 if (ParseTypeAndValue(Val, Loc, PFS) ||
3126 ParseToken(lltok::comma, "expected ',' after store operand") ||
3127 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3128 ParseOptionalCommaAlignment(Alignment))
3131 if (!isa<PointerType>(Ptr->getType()))
3132 return Error(PtrLoc, "store operand must be a pointer");
3133 if (!Val->getType()->isFirstClassType())
3134 return Error(Loc, "store operand must be a first class value");
3135 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3136 return Error(Loc, "stored value and pointer type do not match");
3138 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3143 /// ::= 'getresult' TypeAndValue ',' uint
3144 /// FIXME: Remove support for getresult in LLVM 3.0
3145 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3146 Value *Val; LocTy ValLoc, EltLoc;
3148 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3149 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3150 ParseUInt32(Element, EltLoc))
3153 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3154 return Error(ValLoc, "getresult inst requires an aggregate operand");
3155 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3156 return Error(EltLoc, "invalid getresult index for value");
3157 Inst = ExtractValueInst::Create(Val, Element);
3161 /// ParseGetElementPtr
3162 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3163 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3164 Value *Ptr, *Val; LocTy Loc, EltLoc;
3165 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3167 if (!isa<PointerType>(Ptr->getType()))
3168 return Error(Loc, "base of getelementptr must be a pointer");
3170 SmallVector<Value*, 16> Indices;
3171 while (EatIfPresent(lltok::comma)) {
3172 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3173 if (!isa<IntegerType>(Val->getType()))
3174 return Error(EltLoc, "getelementptr index must be an integer");
3175 Indices.push_back(Val);
3178 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3179 Indices.begin(), Indices.end()))
3180 return Error(Loc, "invalid getelementptr indices");
3181 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3185 /// ParseExtractValue
3186 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3187 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3188 Value *Val; LocTy Loc;
3189 SmallVector<unsigned, 4> Indices;
3190 if (ParseTypeAndValue(Val, Loc, PFS) ||
3191 ParseIndexList(Indices))
3194 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3195 return Error(Loc, "extractvalue operand must be array or struct");
3197 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3199 return Error(Loc, "invalid indices for extractvalue");
3200 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3204 /// ParseInsertValue
3205 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3206 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3207 Value *Val0, *Val1; LocTy Loc0, Loc1;
3208 SmallVector<unsigned, 4> Indices;
3209 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3210 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3211 ParseTypeAndValue(Val1, Loc1, PFS) ||
3212 ParseIndexList(Indices))
3215 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3216 return Error(Loc0, "extractvalue operand must be array or struct");
3218 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3220 return Error(Loc0, "invalid indices for insertvalue");
3221 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());