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_internal: // OptionalLinkage
117 case lltok::kw_weak: // OptionalLinkage
118 case lltok::kw_linkonce: // OptionalLinkage
119 case lltok::kw_appending: // OptionalLinkage
120 case lltok::kw_dllexport: // OptionalLinkage
121 case lltok::kw_common: // OptionalLinkage
122 case lltok::kw_dllimport: // OptionalLinkage
123 case lltok::kw_extern_weak: // OptionalLinkage
124 case lltok::kw_external: { // OptionalLinkage
125 unsigned Linkage, Visibility;
126 if (ParseOptionalLinkage(Linkage) ||
127 ParseOptionalVisibility(Visibility) ||
128 ParseGlobal("", 0, Linkage, true, Visibility))
132 case lltok::kw_default: // OptionalVisibility
133 case lltok::kw_hidden: // OptionalVisibility
134 case lltok::kw_protected: { // OptionalVisibility
136 if (ParseOptionalVisibility(Visibility) ||
137 ParseGlobal("", 0, 0, false, Visibility))
142 case lltok::kw_thread_local: // OptionalThreadLocal
143 case lltok::kw_addrspace: // OptionalAddrSpace
144 case lltok::kw_constant: // GlobalType
145 case lltok::kw_global: // GlobalType
146 if (ParseGlobal("", 0, 0, false, 0)) return true;
154 /// ::= 'module' 'asm' STRINGCONSTANT
155 bool LLParser::ParseModuleAsm() {
156 assert(Lex.getKind() == lltok::kw_module);
160 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
161 ParseStringConstant(AsmStr)) return true;
163 const std::string &AsmSoFar = M->getModuleInlineAsm();
164 if (AsmSoFar.empty())
165 M->setModuleInlineAsm(AsmStr);
167 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
172 /// ::= 'target' 'triple' '=' STRINGCONSTANT
173 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
174 bool LLParser::ParseTargetDefinition() {
175 assert(Lex.getKind() == lltok::kw_target);
178 default: return TokError("unknown target property");
179 case lltok::kw_triple:
181 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
182 ParseStringConstant(Str))
184 M->setTargetTriple(Str);
186 case lltok::kw_datalayout:
188 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
189 ParseStringConstant(Str))
191 M->setDataLayout(Str);
197 /// ::= 'deplibs' '=' '[' ']'
198 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
199 bool LLParser::ParseDepLibs() {
200 assert(Lex.getKind() == lltok::kw_deplibs);
202 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
203 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
206 if (EatIfPresent(lltok::rsquare))
210 if (ParseStringConstant(Str)) return true;
213 while (EatIfPresent(lltok::comma)) {
214 if (ParseStringConstant(Str)) return true;
218 return ParseToken(lltok::rsquare, "expected ']' at end of list");
223 bool LLParser::ParseUnnamedType() {
224 assert(Lex.getKind() == lltok::kw_type);
225 LocTy TypeLoc = Lex.getLoc();
226 Lex.Lex(); // eat kw_type
228 PATypeHolder Ty(Type::VoidTy);
229 if (ParseType(Ty)) return true;
231 unsigned TypeID = NumberedTypes.size();
233 // We don't allow assigning names to void type
234 if (Ty == Type::VoidTy)
235 return Error(TypeLoc, "can't assign name to the void type");
237 // See if this type was previously referenced.
238 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
239 FI = ForwardRefTypeIDs.find(TypeID);
240 if (FI != ForwardRefTypeIDs.end()) {
241 if (FI->second.first.get() == Ty)
242 return Error(TypeLoc, "self referential type is invalid");
244 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
245 Ty = FI->second.first.get();
246 ForwardRefTypeIDs.erase(FI);
249 NumberedTypes.push_back(Ty);
255 /// ::= LocalVar '=' 'type' type
256 bool LLParser::ParseNamedType() {
257 std::string Name = Lex.getStrVal();
258 LocTy NameLoc = Lex.getLoc();
259 Lex.Lex(); // eat LocalVar.
261 PATypeHolder Ty(Type::VoidTy);
263 if (ParseToken(lltok::equal, "expected '=' after name") ||
264 ParseToken(lltok::kw_type, "expected 'type' after name") ||
268 // We don't allow assigning names to void type
269 if (Ty == Type::VoidTy)
270 return Error(NameLoc, "can't assign name '" + Name + "' to the void type");
272 // Set the type name, checking for conflicts as we do so.
273 bool AlreadyExists = M->addTypeName(Name, Ty);
274 if (!AlreadyExists) return false;
276 // See if this type is a forward reference. We need to eagerly resolve
277 // types to allow recursive type redefinitions below.
278 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
279 FI = ForwardRefTypes.find(Name);
280 if (FI != ForwardRefTypes.end()) {
281 if (FI->second.first.get() == Ty)
282 return Error(NameLoc, "self referential type is invalid");
284 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
285 Ty = FI->second.first.get();
286 ForwardRefTypes.erase(FI);
289 // Inserting a name that is already defined, get the existing name.
290 const Type *Existing = M->getTypeByName(Name);
291 assert(Existing && "Conflict but no matching type?!");
293 // Otherwise, this is an attempt to redefine a type. That's okay if
294 // the redefinition is identical to the original.
295 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
296 if (Existing == Ty) return false;
298 // Any other kind of (non-equivalent) redefinition is an error.
299 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
300 Ty->getDescription() + "'");
305 /// ::= 'declare' FunctionHeader
306 bool LLParser::ParseDeclare() {
307 assert(Lex.getKind() == lltok::kw_declare);
311 return ParseFunctionHeader(F, false);
315 /// ::= 'define' FunctionHeader '{' ...
316 bool LLParser::ParseDefine() {
317 assert(Lex.getKind() == lltok::kw_define);
321 return ParseFunctionHeader(F, true) ||
322 ParseFunctionBody(*F);
328 bool LLParser::ParseGlobalType(bool &IsConstant) {
329 if (Lex.getKind() == lltok::kw_constant)
331 else if (Lex.getKind() == lltok::kw_global)
334 return TokError("expected 'global' or 'constant'");
339 /// ParseNamedGlobal:
340 /// GlobalVar '=' OptionalVisibility ALIAS ...
341 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
342 bool LLParser::ParseNamedGlobal() {
343 assert(Lex.getKind() == lltok::GlobalVar);
344 LocTy NameLoc = Lex.getLoc();
345 std::string Name = Lex.getStrVal();
349 unsigned Linkage, Visibility;
350 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
351 ParseOptionalLinkage(Linkage, HasLinkage) ||
352 ParseOptionalVisibility(Visibility))
355 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
356 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
357 return ParseAlias(Name, NameLoc, Visibility);
361 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
363 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
365 /// Everything through visibility has already been parsed.
367 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
368 unsigned Visibility) {
369 assert(Lex.getKind() == lltok::kw_alias);
372 LocTy LinkageLoc = Lex.getLoc();
373 if (ParseOptionalLinkage(Linkage))
376 if (Linkage != GlobalValue::ExternalLinkage &&
377 Linkage != GlobalValue::WeakLinkage &&
378 Linkage != GlobalValue::InternalLinkage)
379 return Error(LinkageLoc, "invalid linkage type for alias");
382 LocTy AliaseeLoc = Lex.getLoc();
383 if (Lex.getKind() != lltok::kw_bitcast) {
384 if (ParseGlobalTypeAndValue(Aliasee)) return true;
386 // The bitcast dest type is not present, it is implied by the dest type.
388 if (ParseValID(ID)) return true;
389 if (ID.Kind != ValID::t_Constant)
390 return Error(AliaseeLoc, "invalid aliasee");
391 Aliasee = ID.ConstantVal;
394 if (!isa<PointerType>(Aliasee->getType()))
395 return Error(AliaseeLoc, "alias must have pointer type");
397 // Okay, create the alias but do not insert it into the module yet.
398 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
399 (GlobalValue::LinkageTypes)Linkage, Name,
401 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
403 // See if this value already exists in the symbol table. If so, it is either
404 // a redefinition or a definition of a forward reference.
405 if (GlobalValue *Val =
406 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
407 // See if this was a redefinition. If so, there is no entry in
409 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
410 I = ForwardRefVals.find(Name);
411 if (I == ForwardRefVals.end())
412 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
414 // Otherwise, this was a definition of forward ref. Verify that types
416 if (Val->getType() != GA->getType())
417 return Error(NameLoc,
418 "forward reference and definition of alias have different types");
420 // If they agree, just RAUW the old value with the alias and remove the
422 Val->replaceAllUsesWith(GA);
423 Val->eraseFromParent();
424 ForwardRefVals.erase(I);
427 // Insert into the module, we know its name won't collide now.
428 M->getAliasList().push_back(GA);
429 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
435 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
436 /// OptionalAddrSpace GlobalType Type Const
437 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
438 /// OptionalAddrSpace GlobalType Type Const
440 /// Everything through visibility has been parsed already.
442 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
443 unsigned Linkage, bool HasLinkage,
444 unsigned Visibility) {
446 bool ThreadLocal, IsConstant;
449 PATypeHolder Ty(Type::VoidTy);
450 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
451 ParseOptionalAddrSpace(AddrSpace) ||
452 ParseGlobalType(IsConstant) ||
453 ParseType(Ty, TyLoc))
456 // If the linkage is specified and is external, then no initializer is
459 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
460 Linkage != GlobalValue::ExternalWeakLinkage &&
461 Linkage != GlobalValue::ExternalLinkage)) {
462 if (ParseGlobalValue(Ty, Init))
466 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
467 return Error(TyLoc, "invald type for global variable");
469 GlobalVariable *GV = 0;
471 // See if the global was forward referenced, if so, use the global.
472 if (!Name.empty() && (GV = M->getGlobalVariable(Name, true))) {
473 if (!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 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
570 FwdVal = new GlobalVariable(PTy->getElementType(), false,
571 GlobalValue::ExternalWeakLinkage, 0, Name, M);
573 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
577 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
578 const PointerType *PTy = dyn_cast<PointerType>(Ty);
580 Error(Loc, "global variable reference must have pointer type");
584 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
586 // If this is a forward reference for the value, see if we already created a
587 // forward ref record.
589 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
590 I = ForwardRefValIDs.find(ID);
591 if (I != ForwardRefValIDs.end())
592 Val = I->second.first;
595 // If we have the value in the symbol table or fwd-ref table, return it.
597 if (Val->getType() == Ty) return Val;
598 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
599 Val->getType()->getDescription() + "'");
603 // Otherwise, create a new forward reference for this value and remember it.
605 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
606 // Function types can return opaque but functions can't.
607 if (isa<OpaqueType>(FT->getReturnType())) {
608 Error(Loc, "function may not return return opaque type");
611 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
613 FwdVal = new GlobalVariable(PTy->getElementType(), false,
614 GlobalValue::ExternalWeakLinkage, 0, "", M);
617 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
622 //===----------------------------------------------------------------------===//
624 //===----------------------------------------------------------------------===//
626 /// ParseToken - If the current token has the specified kind, eat it and return
627 /// success. Otherwise, emit the specified error and return failure.
628 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
629 if (Lex.getKind() != T)
630 return TokError(ErrMsg);
635 /// ParseStringConstant
636 /// ::= StringConstant
637 bool LLParser::ParseStringConstant(std::string &Result) {
638 if (Lex.getKind() != lltok::StringConstant)
639 return TokError("expected string constant");
640 Result = Lex.getStrVal();
647 bool LLParser::ParseUInt32(unsigned &Val) {
648 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
649 return TokError("expected integer");
650 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
651 if (Val64 != unsigned(Val64))
652 return TokError("expected 32-bit integer (too large)");
659 /// ParseOptionalAddrSpace
661 /// := 'addrspace' '(' uint32 ')'
662 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
664 if (!EatIfPresent(lltok::kw_addrspace))
666 return ParseToken(lltok::lparen, "expected '(' in address space") ||
667 ParseUInt32(AddrSpace) ||
668 ParseToken(lltok::rparen, "expected ')' in address space");
671 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
672 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
673 /// 2: function attr.
674 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
675 Attrs = Attribute::None;
676 LocTy AttrLoc = Lex.getLoc();
679 switch (Lex.getKind()) {
682 // Treat these as signext/zeroext unless they are function attrs.
683 // FIXME: REMOVE THIS IN LLVM 3.0
685 if (Lex.getKind() == lltok::kw_sext)
686 Attrs |= Attribute::SExt;
688 Attrs |= Attribute::ZExt;
692 default: // End of attributes.
693 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
694 return Error(AttrLoc, "invalid use of function-only attribute");
696 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
697 return Error(AttrLoc, "invalid use of parameter-only attribute");
700 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
701 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
702 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
703 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
704 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
705 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
706 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
707 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
709 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
710 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
711 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
712 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
713 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
714 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
715 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
716 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
717 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
720 case lltok::kw_align: {
722 if (ParseOptionalAlignment(Alignment))
724 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
732 /// ParseOptionalLinkage
741 /// ::= 'extern_weak'
743 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
745 switch (Lex.getKind()) {
746 default: Res = GlobalValue::ExternalLinkage; return false;
747 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
748 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
749 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
750 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
751 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
752 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
753 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
754 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
755 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
762 /// ParseOptionalVisibility
768 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
769 switch (Lex.getKind()) {
770 default: Res = GlobalValue::DefaultVisibility; return false;
771 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
772 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
773 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
779 /// ParseOptionalCallingConv
784 /// ::= 'x86_stdcallcc'
785 /// ::= 'x86_fastcallcc'
788 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
789 switch (Lex.getKind()) {
790 default: CC = CallingConv::C; return false;
791 case lltok::kw_ccc: CC = CallingConv::C; break;
792 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
793 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
794 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
795 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
796 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
802 /// ParseOptionalAlignment
805 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
807 if (!EatIfPresent(lltok::kw_align))
809 LocTy AlignLoc = Lex.getLoc();
810 if (ParseUInt32(Alignment)) return true;
811 if (!isPowerOf2_32(Alignment))
812 return Error(AlignLoc, "alignment is not a power of two");
816 /// ParseOptionalCommaAlignment
818 /// ::= ',' 'align' 4
819 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
821 if (!EatIfPresent(lltok::comma))
823 return ParseToken(lltok::kw_align, "expected 'align'") ||
824 ParseUInt32(Alignment);
828 /// ::= (',' uint32)+
829 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
830 if (Lex.getKind() != lltok::comma)
831 return TokError("expected ',' as start of index list");
833 while (EatIfPresent(lltok::comma)) {
835 if (ParseUInt32(Idx)) return true;
836 Indices.push_back(Idx);
842 //===----------------------------------------------------------------------===//
844 //===----------------------------------------------------------------------===//
846 /// ParseType - Parse and resolve a full type.
847 bool LLParser::ParseType(PATypeHolder &Result) {
848 if (ParseTypeRec(Result)) return true;
850 // Verify no unresolved uprefs.
852 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
857 /// HandleUpRefs - Every time we finish a new layer of types, this function is
858 /// called. It loops through the UpRefs vector, which is a list of the
859 /// currently active types. For each type, if the up-reference is contained in
860 /// the newly completed type, we decrement the level count. When the level
861 /// count reaches zero, the up-referenced type is the type that is passed in:
862 /// thus we can complete the cycle.
864 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
865 // If Ty isn't abstract, or if there are no up-references in it, then there is
866 // nothing to resolve here.
867 if (!ty->isAbstract() || UpRefs.empty()) return ty;
871 errs() << "Type '" << Ty->getDescription()
872 << "' newly formed. Resolving upreferences.\n"
873 << UpRefs.size() << " upreferences active!\n";
876 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
877 // to zero), we resolve them all together before we resolve them to Ty. At
878 // the end of the loop, if there is anything to resolve to Ty, it will be in
880 OpaqueType *TypeToResolve = 0;
882 for (unsigned i = 0; i != UpRefs.size(); ++i) {
883 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
885 std::find(Ty->subtype_begin(), Ty->subtype_end(),
886 UpRefs[i].LastContainedTy) != Ty->subtype_end();
889 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
890 << UpRefs[i].LastContainedTy->getDescription() << ") = "
891 << (ContainsType ? "true" : "false")
892 << " level=" << UpRefs[i].NestingLevel << "\n";
897 // Decrement level of upreference
898 unsigned Level = --UpRefs[i].NestingLevel;
899 UpRefs[i].LastContainedTy = Ty;
901 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
906 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
909 TypeToResolve = UpRefs[i].UpRefTy;
911 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
912 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
913 --i; // Do not skip the next element.
917 TypeToResolve->refineAbstractTypeTo(Ty);
923 /// ParseTypeRec - The recursive function used to process the internal
924 /// implementation details of types.
925 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
926 switch (Lex.getKind()) {
928 return TokError("expected type");
930 // TypeRec ::= 'float' | 'void' (etc)
931 Result = Lex.getTyVal();
934 case lltok::kw_opaque:
935 // TypeRec ::= 'opaque'
936 Result = OpaqueType::get();
940 // TypeRec ::= '{' ... '}'
941 if (ParseStructType(Result, false))
945 // TypeRec ::= '[' ... ']'
946 Lex.Lex(); // eat the lsquare.
947 if (ParseArrayVectorType(Result, false))
950 case lltok::less: // Either vector or packed struct.
951 // TypeRec ::= '<' ... '>'
953 if (Lex.getKind() == lltok::lbrace) {
954 if (ParseStructType(Result, true) ||
955 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
957 } else if (ParseArrayVectorType(Result, true))
960 case lltok::LocalVar:
961 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
963 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
966 Result = OpaqueType::get();
967 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
968 std::make_pair(Result,
970 M->addTypeName(Lex.getStrVal(), Result.get());
975 case lltok::LocalVarID:
977 if (Lex.getUIntVal() < NumberedTypes.size())
978 Result = NumberedTypes[Lex.getUIntVal()];
980 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
981 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
982 if (I != ForwardRefTypeIDs.end())
983 Result = I->second.first;
985 Result = OpaqueType::get();
986 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
987 std::make_pair(Result,
993 case lltok::backslash: {
997 if (ParseUInt32(Val)) return true;
998 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
999 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1005 // Parse the type suffixes.
1007 switch (Lex.getKind()) {
1009 default: return false;
1011 // TypeRec ::= TypeRec '*'
1013 if (Result.get() == Type::LabelTy)
1014 return TokError("basic block pointers are invalid");
1015 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1019 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1020 case lltok::kw_addrspace: {
1021 if (Result.get() == Type::LabelTy)
1022 return TokError("basic block pointers are invalid");
1024 if (ParseOptionalAddrSpace(AddrSpace) ||
1025 ParseToken(lltok::star, "expected '*' in address space"))
1028 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1032 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1034 if (ParseFunctionType(Result))
1041 /// ParseParameterList
1043 /// ::= '(' Arg (',' Arg)* ')'
1045 /// ::= Type OptionalAttributes Value OptionalAttributes
1046 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1047 PerFunctionState &PFS) {
1048 if (ParseToken(lltok::lparen, "expected '(' in call"))
1051 while (Lex.getKind() != lltok::rparen) {
1052 // If this isn't the first argument, we need a comma.
1053 if (!ArgList.empty() &&
1054 ParseToken(lltok::comma, "expected ',' in argument list"))
1057 // Parse the argument.
1059 PATypeHolder ArgTy(Type::VoidTy);
1060 unsigned ArgAttrs1, ArgAttrs2;
1062 if (ParseType(ArgTy, ArgLoc) ||
1063 ParseOptionalAttrs(ArgAttrs1, 0) ||
1064 ParseValue(ArgTy, V, PFS) ||
1065 // FIXME: Should not allow attributes after the argument, remove this in
1067 ParseOptionalAttrs(ArgAttrs2, 0))
1069 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1072 Lex.Lex(); // Lex the ')'.
1078 /// ParseArgumentList
1079 /// ::= '(' ArgTypeListI ')'
1083 /// ::= ArgTypeList ',' '...'
1084 /// ::= ArgType (',' ArgType)*
1085 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1088 assert(Lex.getKind() == lltok::lparen);
1089 Lex.Lex(); // eat the (.
1091 if (Lex.getKind() == lltok::rparen) {
1093 } else if (Lex.getKind() == lltok::dotdotdot) {
1097 LocTy TypeLoc = Lex.getLoc();
1098 PATypeHolder ArgTy(Type::VoidTy);
1102 if (ParseTypeRec(ArgTy) ||
1103 ParseOptionalAttrs(Attrs, 0)) return true;
1105 if (Lex.getKind() == lltok::LocalVar ||
1106 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1107 Name = Lex.getStrVal();
1111 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1112 return Error(TypeLoc, "invalid type for function argument");
1114 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1116 while (EatIfPresent(lltok::comma)) {
1117 // Handle ... at end of arg list.
1118 if (EatIfPresent(lltok::dotdotdot)) {
1123 // Otherwise must be an argument type.
1124 TypeLoc = Lex.getLoc();
1125 if (ParseTypeRec(ArgTy) ||
1126 ParseOptionalAttrs(Attrs, 0)) return true;
1128 if (Lex.getKind() == lltok::LocalVar ||
1129 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1130 Name = Lex.getStrVal();
1136 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1137 return Error(TypeLoc, "invalid type for function argument");
1139 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1143 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1146 /// ParseFunctionType
1147 /// ::= Type ArgumentList OptionalAttrs
1148 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1149 assert(Lex.getKind() == lltok::lparen);
1151 if (!FunctionType::isValidReturnType(Result))
1152 return TokError("invalid function return type");
1154 std::vector<ArgInfo> ArgList;
1157 if (ParseArgumentList(ArgList, isVarArg) ||
1158 // FIXME: Allow, but ignore attributes on function types!
1159 // FIXME: Remove in LLVM 3.0
1160 ParseOptionalAttrs(Attrs, 2))
1163 // Reject names on the arguments lists.
1164 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1165 if (!ArgList[i].Name.empty())
1166 return Error(ArgList[i].Loc, "argument name invalid in function type");
1167 if (!ArgList[i].Attrs != 0) {
1168 // Allow but ignore attributes on function types; this permits
1170 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1174 std::vector<const Type*> ArgListTy;
1175 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1176 ArgListTy.push_back(ArgList[i].Type);
1178 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1182 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1185 /// ::= '{' TypeRec (',' TypeRec)* '}'
1186 /// ::= '<' '{' '}' '>'
1187 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1188 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1189 assert(Lex.getKind() == lltok::lbrace);
1190 Lex.Lex(); // Consume the '{'
1192 if (EatIfPresent(lltok::rbrace)) {
1193 Result = StructType::get(std::vector<const Type*>(), Packed);
1197 std::vector<PATypeHolder> ParamsList;
1198 if (ParseTypeRec(Result)) return true;
1199 ParamsList.push_back(Result);
1201 while (EatIfPresent(lltok::comma)) {
1202 if (ParseTypeRec(Result)) return true;
1203 ParamsList.push_back(Result);
1206 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1209 std::vector<const Type*> ParamsListTy;
1210 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1211 ParamsListTy.push_back(ParamsList[i].get());
1212 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1216 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1217 /// token has already been consumed.
1219 /// ::= '[' APSINTVAL 'x' Types ']'
1220 /// ::= '<' APSINTVAL 'x' Types '>'
1221 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1222 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1223 Lex.getAPSIntVal().getBitWidth() > 64)
1224 return TokError("expected number in address space");
1226 LocTy SizeLoc = Lex.getLoc();
1227 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1230 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1233 LocTy TypeLoc = Lex.getLoc();
1234 PATypeHolder EltTy(Type::VoidTy);
1235 if (ParseTypeRec(EltTy)) return true;
1237 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1238 "expected end of sequential type"))
1242 if ((unsigned)Size != Size)
1243 return Error(SizeLoc, "size too large for vector");
1244 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1245 return Error(TypeLoc, "vector element type must be fp or integer");
1246 Result = VectorType::get(EltTy, unsigned(Size));
1248 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1249 return Error(TypeLoc, "invalid array element type");
1250 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1255 //===----------------------------------------------------------------------===//
1256 // Function Semantic Analysis.
1257 //===----------------------------------------------------------------------===//
1259 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1262 // Insert unnamed arguments into the NumberedVals list.
1263 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1266 NumberedVals.push_back(AI);
1269 LLParser::PerFunctionState::~PerFunctionState() {
1270 // If there were any forward referenced non-basicblock values, delete them.
1271 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1272 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1273 if (!isa<BasicBlock>(I->second.first)) {
1274 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1276 delete I->second.first;
1277 I->second.first = 0;
1280 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1281 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1282 if (!isa<BasicBlock>(I->second.first)) {
1283 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1285 delete I->second.first;
1286 I->second.first = 0;
1290 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1291 if (!ForwardRefVals.empty())
1292 return P.Error(ForwardRefVals.begin()->second.second,
1293 "use of undefined value '%" + ForwardRefVals.begin()->first +
1295 if (!ForwardRefValIDs.empty())
1296 return P.Error(ForwardRefValIDs.begin()->second.second,
1297 "use of undefined value '%" +
1298 utostr(ForwardRefValIDs.begin()->first) + "'");
1303 /// GetVal - Get a value with the specified name or ID, creating a
1304 /// forward reference record if needed. This can return null if the value
1305 /// exists but does not have the right type.
1306 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1307 const Type *Ty, LocTy Loc) {
1308 // Look this name up in the normal function symbol table.
1309 Value *Val = F.getValueSymbolTable().lookup(Name);
1311 // If this is a forward reference for the value, see if we already created a
1312 // forward ref record.
1314 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1315 I = ForwardRefVals.find(Name);
1316 if (I != ForwardRefVals.end())
1317 Val = I->second.first;
1320 // If we have the value in the symbol table or fwd-ref table, return it.
1322 if (Val->getType() == Ty) return Val;
1323 if (Ty == Type::LabelTy)
1324 P.Error(Loc, "'%" + Name + "' is not a basic block");
1326 P.Error(Loc, "'%" + Name + "' defined with type '" +
1327 Val->getType()->getDescription() + "'");
1331 // Don't make placeholders with invalid type.
1332 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1333 P.Error(Loc, "invalid use of a non-first-class type");
1337 // Otherwise, create a new forward reference for this value and remember it.
1339 if (Ty == Type::LabelTy)
1340 FwdVal = BasicBlock::Create(Name, &F);
1342 FwdVal = new Argument(Ty, Name);
1344 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1348 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1350 // Look this name up in the normal function symbol table.
1351 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1353 // If this is a forward reference for the value, see if we already created a
1354 // forward ref record.
1356 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1357 I = ForwardRefValIDs.find(ID);
1358 if (I != ForwardRefValIDs.end())
1359 Val = I->second.first;
1362 // If we have the value in the symbol table or fwd-ref table, return it.
1364 if (Val->getType() == Ty) return Val;
1365 if (Ty == Type::LabelTy)
1366 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1368 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1369 Val->getType()->getDescription() + "'");
1373 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1374 P.Error(Loc, "invalid use of a non-first-class type");
1378 // Otherwise, create a new forward reference for this value and remember it.
1380 if (Ty == Type::LabelTy)
1381 FwdVal = BasicBlock::Create("", &F);
1383 FwdVal = new Argument(Ty);
1385 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1389 /// SetInstName - After an instruction is parsed and inserted into its
1390 /// basic block, this installs its name.
1391 bool LLParser::PerFunctionState::SetInstName(int NameID,
1392 const std::string &NameStr,
1393 LocTy NameLoc, Instruction *Inst) {
1394 // If this instruction has void type, it cannot have a name or ID specified.
1395 if (Inst->getType() == Type::VoidTy) {
1396 if (NameID != -1 || !NameStr.empty())
1397 return P.Error(NameLoc, "instructions returning void cannot have a name");
1401 // If this was a numbered instruction, verify that the instruction is the
1402 // expected value and resolve any forward references.
1403 if (NameStr.empty()) {
1404 // If neither a name nor an ID was specified, just use the next ID.
1406 NameID = NumberedVals.size();
1408 if (unsigned(NameID) != NumberedVals.size())
1409 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1410 utostr(NumberedVals.size()) + "'");
1412 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1413 ForwardRefValIDs.find(NameID);
1414 if (FI != ForwardRefValIDs.end()) {
1415 if (FI->second.first->getType() != Inst->getType())
1416 return P.Error(NameLoc, "instruction forward referenced with type '" +
1417 FI->second.first->getType()->getDescription() + "'");
1418 FI->second.first->replaceAllUsesWith(Inst);
1419 ForwardRefValIDs.erase(FI);
1422 NumberedVals.push_back(Inst);
1426 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1427 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1428 FI = ForwardRefVals.find(NameStr);
1429 if (FI != ForwardRefVals.end()) {
1430 if (FI->second.first->getType() != Inst->getType())
1431 return P.Error(NameLoc, "instruction forward referenced with type '" +
1432 FI->second.first->getType()->getDescription() + "'");
1433 FI->second.first->replaceAllUsesWith(Inst);
1434 ForwardRefVals.erase(FI);
1437 // Set the name on the instruction.
1438 Inst->setName(NameStr);
1440 if (Inst->getNameStr() != NameStr)
1441 return P.Error(NameLoc, "multiple definition of local value named '" +
1446 /// GetBB - Get a basic block with the specified name or ID, creating a
1447 /// forward reference record if needed.
1448 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1450 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1453 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1454 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1457 /// DefineBB - Define the specified basic block, which is either named or
1458 /// unnamed. If there is an error, this returns null otherwise it returns
1459 /// the block being defined.
1460 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1464 BB = GetBB(NumberedVals.size(), Loc);
1466 BB = GetBB(Name, Loc);
1467 if (BB == 0) return 0; // Already diagnosed error.
1469 // Move the block to the end of the function. Forward ref'd blocks are
1470 // inserted wherever they happen to be referenced.
1471 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1473 // Remove the block from forward ref sets.
1475 ForwardRefValIDs.erase(NumberedVals.size());
1476 NumberedVals.push_back(BB);
1478 // BB forward references are already in the function symbol table.
1479 ForwardRefVals.erase(Name);
1485 //===----------------------------------------------------------------------===//
1487 //===----------------------------------------------------------------------===//
1489 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1490 /// type implied. For example, if we parse "4" we don't know what integer type
1491 /// it has. The value will later be combined with its type and checked for
1493 bool LLParser::ParseValID(ValID &ID) {
1494 ID.Loc = Lex.getLoc();
1495 switch (Lex.getKind()) {
1496 default: return TokError("expected value token");
1497 case lltok::GlobalID: // @42
1498 ID.UIntVal = Lex.getUIntVal();
1499 ID.Kind = ValID::t_GlobalID;
1501 case lltok::GlobalVar: // @foo
1502 ID.StrVal = Lex.getStrVal();
1503 ID.Kind = ValID::t_GlobalName;
1505 case lltok::LocalVarID: // %42
1506 ID.UIntVal = Lex.getUIntVal();
1507 ID.Kind = ValID::t_LocalID;
1509 case lltok::LocalVar: // %foo
1510 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1511 ID.StrVal = Lex.getStrVal();
1512 ID.Kind = ValID::t_LocalName;
1515 ID.APSIntVal = Lex.getAPSIntVal();
1516 ID.Kind = ValID::t_APSInt;
1518 case lltok::APFloat:
1519 ID.APFloatVal = Lex.getAPFloatVal();
1520 ID.Kind = ValID::t_APFloat;
1522 case lltok::kw_true:
1523 ID.ConstantVal = ConstantInt::getTrue();
1524 ID.Kind = ValID::t_Constant;
1526 case lltok::kw_false:
1527 ID.ConstantVal = ConstantInt::getFalse();
1528 ID.Kind = ValID::t_Constant;
1530 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1531 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1532 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1534 case lltok::lbrace: {
1535 // ValID ::= '{' ConstVector '}'
1537 SmallVector<Constant*, 16> Elts;
1538 if (ParseGlobalValueVector(Elts) ||
1539 ParseToken(lltok::rbrace, "expected end of struct constant"))
1542 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1543 ID.Kind = ValID::t_Constant;
1547 // ValID ::= '<' ConstVector '>' --> Vector.
1548 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1550 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1552 SmallVector<Constant*, 16> Elts;
1553 LocTy FirstEltLoc = Lex.getLoc();
1554 if (ParseGlobalValueVector(Elts) ||
1556 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1557 ParseToken(lltok::greater, "expected end of constant"))
1560 if (isPackedStruct) {
1561 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1562 ID.Kind = ValID::t_Constant;
1567 return Error(ID.Loc, "constant vector must not be empty");
1569 if (!Elts[0]->getType()->isInteger() &&
1570 !Elts[0]->getType()->isFloatingPoint())
1571 return Error(FirstEltLoc,
1572 "vector elements must have integer or floating point type");
1574 // Verify that all the vector elements have the same type.
1575 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1576 if (Elts[i]->getType() != Elts[0]->getType())
1577 return Error(FirstEltLoc,
1578 "vector element #" + utostr(i) +
1579 " is not of type '" + Elts[0]->getType()->getDescription());
1581 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1582 ID.Kind = ValID::t_Constant;
1585 case lltok::lsquare: { // Array Constant
1587 SmallVector<Constant*, 16> Elts;
1588 LocTy FirstEltLoc = Lex.getLoc();
1589 if (ParseGlobalValueVector(Elts) ||
1590 ParseToken(lltok::rsquare, "expected end of array constant"))
1593 // Handle empty element.
1595 // Use undef instead of an array because it's inconvenient to determine
1596 // the element type at this point, there being no elements to examine.
1597 ID.Kind = ValID::t_EmptyArray;
1601 if (!Elts[0]->getType()->isFirstClassType())
1602 return Error(FirstEltLoc, "invalid array element type: " +
1603 Elts[0]->getType()->getDescription());
1605 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1607 // Verify all elements are correct type!
1608 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1609 if (Elts[i]->getType() != Elts[0]->getType())
1610 return Error(FirstEltLoc,
1611 "array element #" + utostr(i) +
1612 " is not of type '" +Elts[0]->getType()->getDescription());
1615 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1616 ID.Kind = ValID::t_Constant;
1619 case lltok::kw_c: // c "foo"
1621 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1622 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1623 ID.Kind = ValID::t_Constant;
1626 case lltok::kw_asm: {
1627 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1630 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1631 ParseStringConstant(ID.StrVal) ||
1632 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1633 ParseToken(lltok::StringConstant, "expected constraint string"))
1635 ID.StrVal2 = Lex.getStrVal();
1636 ID.UIntVal = HasSideEffect;
1637 ID.Kind = ValID::t_InlineAsm;
1641 case lltok::kw_trunc:
1642 case lltok::kw_zext:
1643 case lltok::kw_sext:
1644 case lltok::kw_fptrunc:
1645 case lltok::kw_fpext:
1646 case lltok::kw_bitcast:
1647 case lltok::kw_uitofp:
1648 case lltok::kw_sitofp:
1649 case lltok::kw_fptoui:
1650 case lltok::kw_fptosi:
1651 case lltok::kw_inttoptr:
1652 case lltok::kw_ptrtoint: {
1653 unsigned Opc = Lex.getUIntVal();
1654 PATypeHolder DestTy(Type::VoidTy);
1657 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1658 ParseGlobalTypeAndValue(SrcVal) ||
1659 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1660 ParseType(DestTy) ||
1661 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1663 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1664 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1665 SrcVal->getType()->getDescription() + "' to '" +
1666 DestTy->getDescription() + "'");
1667 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1669 ID.Kind = ValID::t_Constant;
1672 case lltok::kw_extractvalue: {
1675 SmallVector<unsigned, 4> Indices;
1676 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1677 ParseGlobalTypeAndValue(Val) ||
1678 ParseIndexList(Indices) ||
1679 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1681 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1682 return Error(ID.Loc, "extractvalue operand must be array or struct");
1683 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1685 return Error(ID.Loc, "invalid indices for extractvalue");
1686 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1687 &Indices[0], Indices.size());
1688 ID.Kind = ValID::t_Constant;
1691 case lltok::kw_insertvalue: {
1693 Constant *Val0, *Val1;
1694 SmallVector<unsigned, 4> Indices;
1695 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1696 ParseGlobalTypeAndValue(Val0) ||
1697 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1698 ParseGlobalTypeAndValue(Val1) ||
1699 ParseIndexList(Indices) ||
1700 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1702 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1703 return Error(ID.Loc, "extractvalue operand must be array or struct");
1704 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1706 return Error(ID.Loc, "invalid indices for insertvalue");
1707 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1708 &Indices[0], Indices.size());
1709 ID.Kind = ValID::t_Constant;
1712 case lltok::kw_icmp:
1713 case lltok::kw_fcmp:
1714 case lltok::kw_vicmp:
1715 case lltok::kw_vfcmp: {
1716 unsigned PredVal, Opc = Lex.getUIntVal();
1717 Constant *Val0, *Val1;
1719 if (ParseCmpPredicate(PredVal, Opc) ||
1720 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1721 ParseGlobalTypeAndValue(Val0) ||
1722 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1723 ParseGlobalTypeAndValue(Val1) ||
1724 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1727 if (Val0->getType() != Val1->getType())
1728 return Error(ID.Loc, "compare operands must have the same type");
1730 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1732 if (Opc == Instruction::FCmp) {
1733 if (!Val0->getType()->isFPOrFPVector())
1734 return Error(ID.Loc, "fcmp requires floating point operands");
1735 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1736 } else if (Opc == Instruction::ICmp) {
1737 if (!Val0->getType()->isIntOrIntVector() &&
1738 !isa<PointerType>(Val0->getType()))
1739 return Error(ID.Loc, "icmp requires pointer or integer operands");
1740 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1741 } else if (Opc == Instruction::VFCmp) {
1742 // FIXME: REMOVE VFCMP Support
1743 if (!Val0->getType()->isFPOrFPVector() ||
1744 !isa<VectorType>(Val0->getType()))
1745 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1746 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1747 } else if (Opc == Instruction::VICmp) {
1748 // FIXME: REMOVE VICMP Support
1749 if (!Val0->getType()->isIntOrIntVector() ||
1750 !isa<VectorType>(Val0->getType()))
1751 return Error(ID.Loc, "vicmp requires vector floating point operands");
1752 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1754 ID.Kind = ValID::t_Constant;
1758 // Binary Operators.
1762 case lltok::kw_udiv:
1763 case lltok::kw_sdiv:
1764 case lltok::kw_fdiv:
1765 case lltok::kw_urem:
1766 case lltok::kw_srem:
1767 case lltok::kw_frem: {
1768 unsigned Opc = Lex.getUIntVal();
1769 Constant *Val0, *Val1;
1771 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1772 ParseGlobalTypeAndValue(Val0) ||
1773 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1774 ParseGlobalTypeAndValue(Val1) ||
1775 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1777 if (Val0->getType() != Val1->getType())
1778 return Error(ID.Loc, "operands of constexpr must have same type");
1779 if (!Val0->getType()->isIntOrIntVector() &&
1780 !Val0->getType()->isFPOrFPVector())
1781 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1782 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1783 ID.Kind = ValID::t_Constant;
1787 // Logical Operations
1789 case lltok::kw_lshr:
1790 case lltok::kw_ashr:
1793 case lltok::kw_xor: {
1794 unsigned Opc = Lex.getUIntVal();
1795 Constant *Val0, *Val1;
1797 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1798 ParseGlobalTypeAndValue(Val0) ||
1799 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1800 ParseGlobalTypeAndValue(Val1) ||
1801 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1803 if (Val0->getType() != Val1->getType())
1804 return Error(ID.Loc, "operands of constexpr must have same type");
1805 if (!Val0->getType()->isIntOrIntVector())
1806 return Error(ID.Loc,
1807 "constexpr requires integer or integer vector operands");
1808 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1809 ID.Kind = ValID::t_Constant;
1813 case lltok::kw_getelementptr:
1814 case lltok::kw_shufflevector:
1815 case lltok::kw_insertelement:
1816 case lltok::kw_extractelement:
1817 case lltok::kw_select: {
1818 unsigned Opc = Lex.getUIntVal();
1819 SmallVector<Constant*, 16> Elts;
1821 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1822 ParseGlobalValueVector(Elts) ||
1823 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1826 if (Opc == Instruction::GetElementPtr) {
1827 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1828 return Error(ID.Loc, "getelementptr requires pointer operand");
1830 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1831 (Value**)&Elts[1], Elts.size()-1))
1832 return Error(ID.Loc, "invalid indices for getelementptr");
1833 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1834 &Elts[1], Elts.size()-1);
1835 } else if (Opc == Instruction::Select) {
1836 if (Elts.size() != 3)
1837 return Error(ID.Loc, "expected three operands to select");
1838 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1840 return Error(ID.Loc, Reason);
1841 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1842 } else if (Opc == Instruction::ShuffleVector) {
1843 if (Elts.size() != 3)
1844 return Error(ID.Loc, "expected three operands to shufflevector");
1845 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1846 return Error(ID.Loc, "invalid operands to shufflevector");
1847 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1848 } else if (Opc == Instruction::ExtractElement) {
1849 if (Elts.size() != 2)
1850 return Error(ID.Loc, "expected two operands to extractelement");
1851 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1852 return Error(ID.Loc, "invalid extractelement operands");
1853 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1855 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1856 if (Elts.size() != 3)
1857 return Error(ID.Loc, "expected three operands to insertelement");
1858 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1859 return Error(ID.Loc, "invalid insertelement operands");
1860 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1863 ID.Kind = ValID::t_Constant;
1872 /// ParseGlobalValue - Parse a global value with the specified type.
1873 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1876 return ParseValID(ID) ||
1877 ConvertGlobalValIDToValue(Ty, ID, V);
1880 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1882 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1884 if (isa<FunctionType>(Ty))
1885 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1888 default: assert(0 && "Unknown ValID!");
1889 case ValID::t_LocalID:
1890 case ValID::t_LocalName:
1891 return Error(ID.Loc, "invalid use of function-local name");
1892 case ValID::t_InlineAsm:
1893 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1894 case ValID::t_GlobalName:
1895 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1897 case ValID::t_GlobalID:
1898 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1900 case ValID::t_APSInt:
1901 if (!isa<IntegerType>(Ty))
1902 return Error(ID.Loc, "integer constant must have integer type");
1903 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1904 V = ConstantInt::get(ID.APSIntVal);
1906 case ValID::t_APFloat:
1907 if (!Ty->isFloatingPoint() ||
1908 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1909 return Error(ID.Loc, "floating point constant invalid for type");
1911 // The lexer has no type info, so builds all float and double FP constants
1912 // as double. Fix this here. Long double does not need this.
1913 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1914 Ty == Type::FloatTy) {
1916 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1919 V = ConstantFP::get(ID.APFloatVal);
1921 if (V->getType() != Ty)
1922 return Error(ID.Loc, "floating point constant does not have type '" +
1923 Ty->getDescription() + "'");
1927 if (!isa<PointerType>(Ty))
1928 return Error(ID.Loc, "null must be a pointer type");
1929 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1931 case ValID::t_Undef:
1932 // FIXME: LabelTy should not be a first-class type.
1933 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1934 !isa<OpaqueType>(Ty))
1935 return Error(ID.Loc, "invalid type for undef constant");
1936 V = UndefValue::get(Ty);
1938 case ValID::t_EmptyArray:
1939 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1940 return Error(ID.Loc, "invalid empty array initializer");
1941 V = UndefValue::get(Ty);
1944 // FIXME: LabelTy should not be a first-class type.
1945 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1946 return Error(ID.Loc, "invalid type for null constant");
1947 V = Constant::getNullValue(Ty);
1949 case ValID::t_Constant:
1950 if (ID.ConstantVal->getType() != Ty)
1951 return Error(ID.Loc, "constant expression type mismatch");
1957 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1958 PATypeHolder Type(Type::VoidTy);
1959 return ParseType(Type) ||
1960 ParseGlobalValue(Type, V);
1963 /// ParseGlobalValueVector
1965 /// ::= TypeAndValue (',' TypeAndValue)*
1966 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1968 if (Lex.getKind() == lltok::rbrace ||
1969 Lex.getKind() == lltok::rsquare ||
1970 Lex.getKind() == lltok::greater ||
1971 Lex.getKind() == lltok::rparen)
1975 if (ParseGlobalTypeAndValue(C)) return true;
1978 while (EatIfPresent(lltok::comma)) {
1979 if (ParseGlobalTypeAndValue(C)) return true;
1987 //===----------------------------------------------------------------------===//
1988 // Function Parsing.
1989 //===----------------------------------------------------------------------===//
1991 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
1992 PerFunctionState &PFS) {
1993 if (ID.Kind == ValID::t_LocalID)
1994 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
1995 else if (ID.Kind == ValID::t_LocalName)
1996 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
1997 else if (ID.Kind == ValID::ValID::t_InlineAsm) {
1998 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1999 const FunctionType *FTy =
2000 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2001 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2002 return Error(ID.Loc, "invalid type for inline asm constraint string");
2003 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2007 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2015 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2018 return ParseValID(ID) ||
2019 ConvertValIDToValue(Ty, ID, V, PFS);
2022 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2023 PATypeHolder T(Type::VoidTy);
2024 return ParseType(T) ||
2025 ParseValue(T, V, PFS);
2029 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2030 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2031 /// OptionalAlign OptGC
2032 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2033 // Parse the linkage.
2034 LocTy LinkageLoc = Lex.getLoc();
2037 unsigned Visibility, CC, RetAttrs;
2038 PATypeHolder RetType(Type::VoidTy);
2039 LocTy RetTypeLoc = Lex.getLoc();
2040 if (ParseOptionalLinkage(Linkage) ||
2041 ParseOptionalVisibility(Visibility) ||
2042 ParseOptionalCallingConv(CC) ||
2043 ParseOptionalAttrs(RetAttrs, 1) ||
2044 ParseType(RetType, RetTypeLoc))
2047 // Verify that the linkage is ok.
2048 switch ((GlobalValue::LinkageTypes)Linkage) {
2049 case GlobalValue::ExternalLinkage:
2050 break; // always ok.
2051 case GlobalValue::DLLImportLinkage:
2052 case GlobalValue::ExternalWeakLinkage:
2054 return Error(LinkageLoc, "invalid linkage for function definition");
2056 case GlobalValue::InternalLinkage:
2057 case GlobalValue::LinkOnceLinkage:
2058 case GlobalValue::WeakLinkage:
2059 case GlobalValue::DLLExportLinkage:
2061 return Error(LinkageLoc, "invalid linkage for function declaration");
2063 case GlobalValue::AppendingLinkage:
2064 case GlobalValue::GhostLinkage:
2065 case GlobalValue::CommonLinkage:
2066 return Error(LinkageLoc, "invalid function linkage type");
2069 if (!FunctionType::isValidReturnType(RetType) ||
2070 isa<OpaqueType>(RetType))
2071 return Error(RetTypeLoc, "invalid function return type");
2073 if (Lex.getKind() != lltok::GlobalVar)
2074 return TokError("expected function name");
2076 LocTy NameLoc = Lex.getLoc();
2077 std::string FunctionName = Lex.getStrVal();
2080 if (Lex.getKind() != lltok::lparen)
2081 return TokError("expected '(' in function argument list");
2083 std::vector<ArgInfo> ArgList;
2086 std::string Section;
2090 if (ParseArgumentList(ArgList, isVarArg) ||
2091 ParseOptionalAttrs(FuncAttrs, 2) ||
2092 (EatIfPresent(lltok::kw_section) &&
2093 ParseStringConstant(Section)) ||
2094 ParseOptionalAlignment(Alignment) ||
2095 (EatIfPresent(lltok::kw_gc) &&
2096 ParseStringConstant(GC)))
2099 // If the alignment was parsed as an attribute, move to the alignment field.
2100 if (FuncAttrs & Attribute::Alignment) {
2101 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2102 FuncAttrs &= ~Attribute::Alignment;
2105 // Okay, if we got here, the function is syntactically valid. Convert types
2106 // and do semantic checks.
2107 std::vector<const Type*> ParamTypeList;
2108 SmallVector<AttributeWithIndex, 8> Attrs;
2109 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2111 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2112 if (FuncAttrs & ObsoleteFuncAttrs) {
2113 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2114 FuncAttrs &= ~ObsoleteFuncAttrs;
2117 if (RetAttrs != Attribute::None)
2118 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2120 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2121 ParamTypeList.push_back(ArgList[i].Type);
2122 if (ArgList[i].Attrs != Attribute::None)
2123 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2126 if (FuncAttrs != Attribute::None)
2127 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2129 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2131 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2132 const PointerType *PFT = PointerType::getUnqual(FT);
2135 if (!FunctionName.empty()) {
2136 // If this was a definition of a forward reference, remove the definition
2137 // from the forward reference table and fill in the forward ref.
2138 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2139 ForwardRefVals.find(FunctionName);
2140 if (FRVI != ForwardRefVals.end()) {
2141 Fn = M->getFunction(FunctionName);
2142 ForwardRefVals.erase(FRVI);
2143 } else if ((Fn = M->getFunction(FunctionName))) {
2144 // If this function already exists in the symbol table, then it is
2145 // multiply defined. We accept a few cases for old backwards compat.
2146 // FIXME: Remove this stuff for LLVM 3.0.
2147 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2148 (!Fn->isDeclaration() && isDefine)) {
2149 // If the redefinition has different type or different attributes,
2150 // reject it. If both have bodies, reject it.
2151 return Error(NameLoc, "invalid redefinition of function '" +
2152 FunctionName + "'");
2153 } else if (Fn->isDeclaration()) {
2154 // Make sure to strip off any argument names so we can't get conflicts.
2155 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2161 } else if (FunctionName.empty()) {
2162 // If this is a definition of a forward referenced function, make sure the
2164 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2165 = ForwardRefValIDs.find(NumberedVals.size());
2166 if (I != ForwardRefValIDs.end()) {
2167 Fn = cast<Function>(I->second.first);
2168 if (Fn->getType() != PFT)
2169 return Error(NameLoc, "type of definition and forward reference of '@" +
2170 utostr(NumberedVals.size()) +"' disagree");
2171 ForwardRefValIDs.erase(I);
2176 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2177 else // Move the forward-reference to the correct spot in the module.
2178 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2180 if (FunctionName.empty())
2181 NumberedVals.push_back(Fn);
2183 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2184 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2185 Fn->setCallingConv(CC);
2186 Fn->setAttributes(PAL);
2187 Fn->setAlignment(Alignment);
2188 Fn->setSection(Section);
2189 if (!GC.empty()) Fn->setGC(GC.c_str());
2191 // Add all of the arguments we parsed to the function.
2192 Function::arg_iterator ArgIt = Fn->arg_begin();
2193 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2194 // If the argument has a name, insert it into the argument symbol table.
2195 if (ArgList[i].Name.empty()) continue;
2197 // Set the name, if it conflicted, it will be auto-renamed.
2198 ArgIt->setName(ArgList[i].Name);
2200 if (ArgIt->getNameStr() != ArgList[i].Name)
2201 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2202 ArgList[i].Name + "'");
2209 /// ParseFunctionBody
2210 /// ::= '{' BasicBlock+ '}'
2211 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2213 bool LLParser::ParseFunctionBody(Function &Fn) {
2214 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2215 return TokError("expected '{' in function body");
2216 Lex.Lex(); // eat the {.
2218 PerFunctionState PFS(*this, Fn);
2220 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2221 if (ParseBasicBlock(PFS)) return true;
2226 // Verify function is ok.
2227 return PFS.VerifyFunctionComplete();
2231 /// ::= LabelStr? Instruction*
2232 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2233 // If this basic block starts out with a name, remember it.
2235 LocTy NameLoc = Lex.getLoc();
2236 if (Lex.getKind() == lltok::LabelStr) {
2237 Name = Lex.getStrVal();
2241 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2242 if (BB == 0) return true;
2244 std::string NameStr;
2246 // Parse the instructions in this block until we get a terminator.
2249 // This instruction may have three possibilities for a name: a) none
2250 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2251 LocTy NameLoc = Lex.getLoc();
2255 if (Lex.getKind() == lltok::LocalVarID) {
2256 NameID = Lex.getUIntVal();
2258 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2260 } else if (Lex.getKind() == lltok::LocalVar ||
2261 // FIXME: REMOVE IN LLVM 3.0
2262 Lex.getKind() == lltok::StringConstant) {
2263 NameStr = Lex.getStrVal();
2265 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2269 if (ParseInstruction(Inst, BB, PFS)) return true;
2271 BB->getInstList().push_back(Inst);
2273 // Set the name on the instruction.
2274 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2275 } while (!isa<TerminatorInst>(Inst));
2280 //===----------------------------------------------------------------------===//
2281 // Instruction Parsing.
2282 //===----------------------------------------------------------------------===//
2284 /// ParseInstruction - Parse one of the many different instructions.
2286 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2287 PerFunctionState &PFS) {
2288 lltok::Kind Token = Lex.getKind();
2289 if (Token == lltok::Eof)
2290 return TokError("found end of file when expecting more instructions");
2291 LocTy Loc = Lex.getLoc();
2292 Lex.Lex(); // Eat the keyword.
2295 default: return Error(Loc, "expected instruction opcode");
2296 // Terminator Instructions.
2297 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2298 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2299 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2300 case lltok::kw_br: return ParseBr(Inst, PFS);
2301 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2302 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2303 // Binary Operators.
2306 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0);
2308 case lltok::kw_udiv:
2309 case lltok::kw_sdiv:
2310 case lltok::kw_urem:
2311 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1);
2312 case lltok::kw_fdiv:
2313 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2);
2315 case lltok::kw_lshr:
2316 case lltok::kw_ashr:
2319 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2320 case lltok::kw_icmp:
2321 case lltok::kw_fcmp:
2322 case lltok::kw_vicmp:
2323 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2325 case lltok::kw_trunc:
2326 case lltok::kw_zext:
2327 case lltok::kw_sext:
2328 case lltok::kw_fptrunc:
2329 case lltok::kw_fpext:
2330 case lltok::kw_bitcast:
2331 case lltok::kw_uitofp:
2332 case lltok::kw_sitofp:
2333 case lltok::kw_fptoui:
2334 case lltok::kw_fptosi:
2335 case lltok::kw_inttoptr:
2336 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2338 case lltok::kw_select: return ParseSelect(Inst, PFS);
2339 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2340 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2341 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2342 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2343 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2344 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2345 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2347 case lltok::kw_alloca:
2348 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2349 case lltok::kw_free: return ParseFree(Inst, PFS);
2350 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2351 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2352 case lltok::kw_volatile:
2353 if (EatIfPresent(lltok::kw_load))
2354 return ParseLoad(Inst, PFS, true);
2355 else if (EatIfPresent(lltok::kw_store))
2356 return ParseStore(Inst, PFS, true);
2358 return TokError("expected 'load' or 'store'");
2359 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2360 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2361 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2362 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2366 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2367 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2368 // FIXME: REMOVE vicmp/vfcmp!
2369 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2370 switch (Lex.getKind()) {
2371 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2372 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2373 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2374 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2375 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2376 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2377 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2378 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2379 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2380 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2381 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2382 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2383 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2384 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2385 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2386 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2387 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2390 switch (Lex.getKind()) {
2391 default: TokError("expected icmp predicate (e.g. 'eq')");
2392 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2393 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2394 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2395 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2396 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2397 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2398 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2399 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2400 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2401 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2408 //===----------------------------------------------------------------------===//
2409 // Terminator Instructions.
2410 //===----------------------------------------------------------------------===//
2412 /// ParseRet - Parse a return instruction.
2414 /// ::= 'ret' TypeAndValue
2415 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2416 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2417 PerFunctionState &PFS) {
2418 PATypeHolder Ty(Type::VoidTy);
2419 if (ParseType(Ty)) return true;
2421 if (Ty == Type::VoidTy) {
2422 Inst = ReturnInst::Create();
2427 if (ParseValue(Ty, RV, PFS)) return true;
2429 // The normal case is one return value.
2430 if (Lex.getKind() == lltok::comma) {
2431 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2432 // of 'ret {i32,i32} {i32 1, i32 2}'
2433 SmallVector<Value*, 8> RVs;
2436 while (EatIfPresent(lltok::comma)) {
2437 if (ParseTypeAndValue(RV, PFS)) return true;
2441 RV = UndefValue::get(PFS.getFunction().getReturnType());
2442 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2443 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2444 BB->getInstList().push_back(I);
2448 Inst = ReturnInst::Create(RV);
2454 /// ::= 'br' TypeAndValue
2455 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2456 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2458 Value *Op0, *Op1, *Op2;
2459 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2461 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2462 Inst = BranchInst::Create(BB);
2466 if (Op0->getType() != Type::Int1Ty)
2467 return Error(Loc, "branch condition must have 'i1' type");
2469 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2470 ParseTypeAndValue(Op1, Loc, PFS) ||
2471 ParseToken(lltok::comma, "expected ',' after true destination") ||
2472 ParseTypeAndValue(Op2, Loc2, PFS))
2475 if (!isa<BasicBlock>(Op1))
2476 return Error(Loc, "true destination of branch must be a basic block");
2477 if (!isa<BasicBlock>(Op2))
2478 return Error(Loc2, "true destination of branch must be a basic block");
2480 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2486 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2488 /// ::= (TypeAndValue ',' TypeAndValue)*
2489 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2490 LocTy CondLoc, BBLoc;
2491 Value *Cond, *DefaultBB;
2492 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2493 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2494 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2495 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2498 if (!isa<IntegerType>(Cond->getType()))
2499 return Error(CondLoc, "switch condition must have integer type");
2500 if (!isa<BasicBlock>(DefaultBB))
2501 return Error(BBLoc, "default destination must be a basic block");
2503 // Parse the jump table pairs.
2504 SmallPtrSet<Value*, 32> SeenCases;
2505 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2506 while (Lex.getKind() != lltok::rsquare) {
2507 Value *Constant, *DestBB;
2509 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2510 ParseToken(lltok::comma, "expected ',' after case value") ||
2511 ParseTypeAndValue(DestBB, BBLoc, PFS))
2514 if (!SeenCases.insert(Constant))
2515 return Error(CondLoc, "duplicate case value in switch");
2516 if (!isa<ConstantInt>(Constant))
2517 return Error(CondLoc, "case value is not a constant integer");
2518 if (!isa<BasicBlock>(DestBB))
2519 return Error(BBLoc, "case destination is not a basic block");
2521 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2522 cast<BasicBlock>(DestBB)));
2525 Lex.Lex(); // Eat the ']'.
2527 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2529 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2530 SI->addCase(Table[i].first, Table[i].second);
2536 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2537 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2538 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2539 LocTy CallLoc = Lex.getLoc();
2540 unsigned CC, RetAttrs, FnAttrs;
2541 PATypeHolder RetType(Type::VoidTy);
2544 SmallVector<ParamInfo, 16> ArgList;
2546 Value *NormalBB, *UnwindBB;
2547 if (ParseOptionalCallingConv(CC) ||
2548 ParseOptionalAttrs(RetAttrs, 1) ||
2549 ParseType(RetType, RetTypeLoc) ||
2550 ParseValID(CalleeID) ||
2551 ParseParameterList(ArgList, PFS) ||
2552 ParseOptionalAttrs(FnAttrs, 2) ||
2553 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2554 ParseTypeAndValue(NormalBB, PFS) ||
2555 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2556 ParseTypeAndValue(UnwindBB, PFS))
2559 if (!isa<BasicBlock>(NormalBB))
2560 return Error(CallLoc, "normal destination is not a basic block");
2561 if (!isa<BasicBlock>(UnwindBB))
2562 return Error(CallLoc, "unwind destination is not a basic block");
2564 // If RetType is a non-function pointer type, then this is the short syntax
2565 // for the call, which means that RetType is just the return type. Infer the
2566 // rest of the function argument types from the arguments that are present.
2567 const PointerType *PFTy = 0;
2568 const FunctionType *Ty = 0;
2569 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2570 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2571 // Pull out the types of all of the arguments...
2572 std::vector<const Type*> ParamTypes;
2573 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2574 ParamTypes.push_back(ArgList[i].V->getType());
2576 if (!FunctionType::isValidReturnType(RetType))
2577 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2579 Ty = FunctionType::get(RetType, ParamTypes, false);
2580 PFTy = PointerType::getUnqual(Ty);
2583 // Look up the callee.
2585 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2587 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2588 // function attributes.
2589 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2590 if (FnAttrs & ObsoleteFuncAttrs) {
2591 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2592 FnAttrs &= ~ObsoleteFuncAttrs;
2595 // Set up the Attributes for the function.
2596 SmallVector<AttributeWithIndex, 8> Attrs;
2597 if (RetAttrs != Attribute::None)
2598 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2600 SmallVector<Value*, 8> Args;
2602 // Loop through FunctionType's arguments and ensure they are specified
2603 // correctly. Also, gather any parameter attributes.
2604 FunctionType::param_iterator I = Ty->param_begin();
2605 FunctionType::param_iterator E = Ty->param_end();
2606 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2607 const Type *ExpectedTy = 0;
2610 } else if (!Ty->isVarArg()) {
2611 return Error(ArgList[i].Loc, "too many arguments specified");
2614 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2615 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2616 ExpectedTy->getDescription() + "'");
2617 Args.push_back(ArgList[i].V);
2618 if (ArgList[i].Attrs != Attribute::None)
2619 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2623 return Error(CallLoc, "not enough parameters specified for call");
2625 if (FnAttrs != Attribute::None)
2626 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2628 // Finish off the Attributes and check them
2629 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2631 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2632 cast<BasicBlock>(UnwindBB),
2633 Args.begin(), Args.end());
2634 II->setCallingConv(CC);
2635 II->setAttributes(PAL);
2642 //===----------------------------------------------------------------------===//
2643 // Binary Operators.
2644 //===----------------------------------------------------------------------===//
2647 /// ::= ArithmeticOps TypeAndValue ',' Value
2649 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2650 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2651 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2652 unsigned Opc, unsigned OperandType) {
2653 LocTy Loc; Value *LHS, *RHS;
2654 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2655 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2656 ParseValue(LHS->getType(), RHS, PFS))
2660 switch (OperandType) {
2661 default: assert(0 && "Unknown operand type!");
2662 case 0: // int or FP.
2663 Valid = LHS->getType()->isIntOrIntVector() ||
2664 LHS->getType()->isFPOrFPVector();
2666 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2667 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2671 return Error(Loc, "invalid operand type for instruction");
2673 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2678 /// ::= ArithmeticOps TypeAndValue ',' Value {
2679 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2681 LocTy Loc; Value *LHS, *RHS;
2682 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2683 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2684 ParseValue(LHS->getType(), RHS, PFS))
2687 if (!LHS->getType()->isIntOrIntVector())
2688 return Error(Loc,"instruction requires integer or integer vector operands");
2690 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2696 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2697 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2698 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2699 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2700 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2702 // Parse the integer/fp comparison predicate.
2706 if (ParseCmpPredicate(Pred, Opc) ||
2707 ParseTypeAndValue(LHS, Loc, PFS) ||
2708 ParseToken(lltok::comma, "expected ',' after compare value") ||
2709 ParseValue(LHS->getType(), RHS, PFS))
2712 if (Opc == Instruction::FCmp) {
2713 if (!LHS->getType()->isFPOrFPVector())
2714 return Error(Loc, "fcmp requires floating point operands");
2715 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2716 } else if (Opc == Instruction::ICmp) {
2717 if (!LHS->getType()->isIntOrIntVector() &&
2718 !isa<PointerType>(LHS->getType()))
2719 return Error(Loc, "icmp requires integer operands");
2720 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2721 } else if (Opc == Instruction::VFCmp) {
2722 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2723 return Error(Loc, "vfcmp requires vector floating point operands");
2724 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2725 } else if (Opc == Instruction::VICmp) {
2726 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2727 return Error(Loc, "vicmp requires vector floating point operands");
2728 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2733 //===----------------------------------------------------------------------===//
2734 // Other Instructions.
2735 //===----------------------------------------------------------------------===//
2739 /// ::= CastOpc TypeAndValue 'to' Type
2740 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2742 LocTy Loc; Value *Op;
2743 PATypeHolder DestTy(Type::VoidTy);
2744 if (ParseTypeAndValue(Op, Loc, PFS) ||
2745 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2749 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2750 return Error(Loc, "invalid cast opcode for cast from '" +
2751 Op->getType()->getDescription() + "' to '" +
2752 DestTy->getDescription() + "'");
2753 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2758 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2759 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2761 Value *Op0, *Op1, *Op2;
2762 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2763 ParseToken(lltok::comma, "expected ',' after select condition") ||
2764 ParseTypeAndValue(Op1, PFS) ||
2765 ParseToken(lltok::comma, "expected ',' after select value") ||
2766 ParseTypeAndValue(Op2, PFS))
2769 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2770 return Error(Loc, Reason);
2772 Inst = SelectInst::Create(Op0, Op1, Op2);
2777 /// ::= 'va_arg' TypeAndValue ',' Type
2778 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2780 PATypeHolder EltTy(Type::VoidTy);
2782 if (ParseTypeAndValue(Op, PFS) ||
2783 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2784 ParseType(EltTy, TypeLoc))
2787 if (!EltTy->isFirstClassType())
2788 return Error(TypeLoc, "va_arg requires operand with first class type");
2790 Inst = new VAArgInst(Op, EltTy);
2794 /// ParseExtractElement
2795 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2796 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2799 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2800 ParseToken(lltok::comma, "expected ',' after extract value") ||
2801 ParseTypeAndValue(Op1, PFS))
2804 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2805 return Error(Loc, "invalid extractelement operands");
2807 Inst = new ExtractElementInst(Op0, Op1);
2811 /// ParseInsertElement
2812 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2813 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2815 Value *Op0, *Op1, *Op2;
2816 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2817 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2818 ParseTypeAndValue(Op1, PFS) ||
2819 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2820 ParseTypeAndValue(Op2, PFS))
2823 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2824 return Error(Loc, "invalid extractelement operands");
2826 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2830 /// ParseShuffleVector
2831 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2832 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2834 Value *Op0, *Op1, *Op2;
2835 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2836 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2837 ParseTypeAndValue(Op1, PFS) ||
2838 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2839 ParseTypeAndValue(Op2, PFS))
2842 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2843 return Error(Loc, "invalid extractelement operands");
2845 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2850 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2851 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2852 PATypeHolder Ty(Type::VoidTy);
2854 LocTy TypeLoc = Lex.getLoc();
2856 if (ParseType(Ty) ||
2857 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2858 ParseValue(Ty, Op0, PFS) ||
2859 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2860 ParseValue(Type::LabelTy, Op1, PFS) ||
2861 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2864 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2866 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2868 if (!EatIfPresent(lltok::comma))
2871 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2872 ParseValue(Ty, Op0, PFS) ||
2873 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2874 ParseValue(Type::LabelTy, Op1, PFS) ||
2875 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2879 if (!Ty->isFirstClassType())
2880 return Error(TypeLoc, "phi node must have first class type");
2882 PHINode *PN = PHINode::Create(Ty);
2883 PN->reserveOperandSpace(PHIVals.size());
2884 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2885 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2891 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2892 /// ParameterList OptionalAttrs
2893 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2895 unsigned CC, RetAttrs, FnAttrs;
2896 PATypeHolder RetType(Type::VoidTy);
2899 SmallVector<ParamInfo, 16> ArgList;
2900 LocTy CallLoc = Lex.getLoc();
2902 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2903 ParseOptionalCallingConv(CC) ||
2904 ParseOptionalAttrs(RetAttrs, 1) ||
2905 ParseType(RetType, RetTypeLoc) ||
2906 ParseValID(CalleeID) ||
2907 ParseParameterList(ArgList, PFS) ||
2908 ParseOptionalAttrs(FnAttrs, 2))
2911 // If RetType is a non-function pointer type, then this is the short syntax
2912 // for the call, which means that RetType is just the return type. Infer the
2913 // rest of the function argument types from the arguments that are present.
2914 const PointerType *PFTy = 0;
2915 const FunctionType *Ty = 0;
2916 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2917 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2918 // Pull out the types of all of the arguments...
2919 std::vector<const Type*> ParamTypes;
2920 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2921 ParamTypes.push_back(ArgList[i].V->getType());
2923 if (!FunctionType::isValidReturnType(RetType))
2924 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2926 Ty = FunctionType::get(RetType, ParamTypes, false);
2927 PFTy = PointerType::getUnqual(Ty);
2930 // Look up the callee.
2932 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2934 // Check for call to invalid intrinsic to avoid crashing later.
2935 if (Function *F = dyn_cast<Function>(Callee)) {
2936 if (F->hasName() && F->getNameLen() >= 5 &&
2937 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
2938 !F->getIntrinsicID(true))
2939 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
2940 F->getNameStr() + "'");
2943 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2944 // function attributes.
2945 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2946 if (FnAttrs & ObsoleteFuncAttrs) {
2947 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2948 FnAttrs &= ~ObsoleteFuncAttrs;
2951 // Set up the Attributes for the function.
2952 SmallVector<AttributeWithIndex, 8> Attrs;
2953 if (RetAttrs != Attribute::None)
2954 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2956 SmallVector<Value*, 8> Args;
2958 // Loop through FunctionType's arguments and ensure they are specified
2959 // correctly. Also, gather any parameter attributes.
2960 FunctionType::param_iterator I = Ty->param_begin();
2961 FunctionType::param_iterator E = Ty->param_end();
2962 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2963 const Type *ExpectedTy = 0;
2966 } else if (!Ty->isVarArg()) {
2967 return Error(ArgList[i].Loc, "too many arguments specified");
2970 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2971 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2972 ExpectedTy->getDescription() + "'");
2973 Args.push_back(ArgList[i].V);
2974 if (ArgList[i].Attrs != Attribute::None)
2975 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2979 return Error(CallLoc, "not enough parameters specified for call");
2981 if (FnAttrs != Attribute::None)
2982 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2984 // Finish off the Attributes and check them
2985 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2987 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
2988 CI->setTailCall(isTail);
2989 CI->setCallingConv(CC);
2990 CI->setAttributes(PAL);
2995 //===----------------------------------------------------------------------===//
2996 // Memory Instructions.
2997 //===----------------------------------------------------------------------===//
3000 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3001 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3002 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3004 PATypeHolder Ty(Type::VoidTy);
3007 unsigned Alignment = 0;
3008 if (ParseType(Ty)) return true;
3010 if (EatIfPresent(lltok::comma)) {
3011 if (Lex.getKind() == lltok::kw_align) {
3012 if (ParseOptionalAlignment(Alignment)) return true;
3013 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3014 ParseOptionalCommaAlignment(Alignment)) {
3019 if (Size && Size->getType() != Type::Int32Ty)
3020 return Error(SizeLoc, "element count must be i32");
3022 if (Opc == Instruction::Malloc)
3023 Inst = new MallocInst(Ty, Size, Alignment);
3025 Inst = new AllocaInst(Ty, Size, Alignment);
3030 /// ::= 'free' TypeAndValue
3031 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3032 Value *Val; LocTy Loc;
3033 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3034 if (!isa<PointerType>(Val->getType()))
3035 return Error(Loc, "operand to free must be a pointer");
3036 Inst = new FreeInst(Val);
3041 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3042 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3044 Value *Val; LocTy Loc;
3046 if (ParseTypeAndValue(Val, Loc, PFS) ||
3047 ParseOptionalCommaAlignment(Alignment))
3050 if (!isa<PointerType>(Val->getType()) ||
3051 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3052 return Error(Loc, "load operand must be a pointer to a first class type");
3054 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3059 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3060 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3062 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3064 if (ParseTypeAndValue(Val, Loc, PFS) ||
3065 ParseToken(lltok::comma, "expected ',' after store operand") ||
3066 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3067 ParseOptionalCommaAlignment(Alignment))
3070 if (!isa<PointerType>(Ptr->getType()))
3071 return Error(PtrLoc, "store operand must be a pointer");
3072 if (!Val->getType()->isFirstClassType())
3073 return Error(Loc, "store operand must be a first class value");
3074 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3075 return Error(Loc, "stored value and pointer type do not match");
3077 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3082 /// ::= 'getresult' TypeAndValue ',' uint
3083 /// FIXME: Remove support for getresult in LLVM 3.0
3084 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3085 Value *Val; LocTy ValLoc, EltLoc;
3087 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3088 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3089 ParseUInt32(Element, EltLoc))
3092 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3093 return Error(ValLoc, "getresult inst requires an aggregate operand");
3094 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3095 return Error(EltLoc, "invalid getresult index for value");
3096 Inst = ExtractValueInst::Create(Val, Element);
3100 /// ParseGetElementPtr
3101 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3102 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3103 Value *Ptr, *Val; LocTy Loc, EltLoc;
3104 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3106 if (!isa<PointerType>(Ptr->getType()))
3107 return Error(Loc, "base of getelementptr must be a pointer");
3109 SmallVector<Value*, 16> Indices;
3110 while (EatIfPresent(lltok::comma)) {
3111 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3112 if (!isa<IntegerType>(Val->getType()))
3113 return Error(EltLoc, "getelementptr index must be an integer");
3114 Indices.push_back(Val);
3117 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3118 Indices.begin(), Indices.end()))
3119 return Error(Loc, "invalid getelementptr indices");
3120 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3124 /// ParseExtractValue
3125 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3126 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3127 Value *Val; LocTy Loc;
3128 SmallVector<unsigned, 4> Indices;
3129 if (ParseTypeAndValue(Val, Loc, PFS) ||
3130 ParseIndexList(Indices))
3133 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3134 return Error(Loc, "extractvalue operand must be array or struct");
3136 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3138 return Error(Loc, "invalid indices for extractvalue");
3139 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3143 /// ParseInsertValue
3144 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3145 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3146 Value *Val0, *Val1; LocTy Loc0, Loc1;
3147 SmallVector<unsigned, 4> Indices;
3148 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3149 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3150 ParseTypeAndValue(Val1, Loc1, PFS) ||
3151 ParseIndexList(Indices))
3154 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3155 return Error(Loc0, "extractvalue operand must be array or struct");
3157 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3159 return Error(Loc0, "invalid indices for insertvalue");
3160 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());