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 - Parse the argument list for a function type or function
1079 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1080 /// ::= '(' ArgTypeListI ')'
1084 /// ::= ArgTypeList ',' '...'
1085 /// ::= ArgType (',' ArgType)*
1087 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1088 bool &isVarArg, bool inType) {
1090 assert(Lex.getKind() == lltok::lparen);
1091 Lex.Lex(); // eat the (.
1093 if (Lex.getKind() == lltok::rparen) {
1095 } else if (Lex.getKind() == lltok::dotdotdot) {
1099 LocTy TypeLoc = Lex.getLoc();
1100 PATypeHolder ArgTy(Type::VoidTy);
1104 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1105 // types (such as a function returning a pointer to itself). If parsing a
1106 // function prototype, we require fully resolved types.
1107 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1108 ParseOptionalAttrs(Attrs, 0)) return true;
1110 if (Lex.getKind() == lltok::LocalVar ||
1111 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1112 Name = Lex.getStrVal();
1116 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1117 return Error(TypeLoc, "invalid type for function argument");
1119 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1121 while (EatIfPresent(lltok::comma)) {
1122 // Handle ... at end of arg list.
1123 if (EatIfPresent(lltok::dotdotdot)) {
1128 // Otherwise must be an argument type.
1129 TypeLoc = Lex.getLoc();
1130 if (ParseTypeRec(ArgTy) ||
1131 ParseOptionalAttrs(Attrs, 0)) return true;
1133 if (Lex.getKind() == lltok::LocalVar ||
1134 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1135 Name = Lex.getStrVal();
1141 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1142 return Error(TypeLoc, "invalid type for function argument");
1144 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1148 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1151 /// ParseFunctionType
1152 /// ::= Type ArgumentList OptionalAttrs
1153 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1154 assert(Lex.getKind() == lltok::lparen);
1156 if (!FunctionType::isValidReturnType(Result))
1157 return TokError("invalid function return type");
1159 std::vector<ArgInfo> ArgList;
1162 if (ParseArgumentList(ArgList, isVarArg, true) ||
1163 // FIXME: Allow, but ignore attributes on function types!
1164 // FIXME: Remove in LLVM 3.0
1165 ParseOptionalAttrs(Attrs, 2))
1168 // Reject names on the arguments lists.
1169 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1170 if (!ArgList[i].Name.empty())
1171 return Error(ArgList[i].Loc, "argument name invalid in function type");
1172 if (!ArgList[i].Attrs != 0) {
1173 // Allow but ignore attributes on function types; this permits
1175 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1179 std::vector<const Type*> ArgListTy;
1180 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1181 ArgListTy.push_back(ArgList[i].Type);
1183 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1187 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1190 /// ::= '{' TypeRec (',' TypeRec)* '}'
1191 /// ::= '<' '{' '}' '>'
1192 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1193 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1194 assert(Lex.getKind() == lltok::lbrace);
1195 Lex.Lex(); // Consume the '{'
1197 if (EatIfPresent(lltok::rbrace)) {
1198 Result = StructType::get(std::vector<const Type*>(), Packed);
1202 std::vector<PATypeHolder> ParamsList;
1203 if (ParseTypeRec(Result)) return true;
1204 ParamsList.push_back(Result);
1206 while (EatIfPresent(lltok::comma)) {
1207 if (ParseTypeRec(Result)) return true;
1208 ParamsList.push_back(Result);
1211 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1214 std::vector<const Type*> ParamsListTy;
1215 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1216 ParamsListTy.push_back(ParamsList[i].get());
1217 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1221 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1222 /// token has already been consumed.
1224 /// ::= '[' APSINTVAL 'x' Types ']'
1225 /// ::= '<' APSINTVAL 'x' Types '>'
1226 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1227 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1228 Lex.getAPSIntVal().getBitWidth() > 64)
1229 return TokError("expected number in address space");
1231 LocTy SizeLoc = Lex.getLoc();
1232 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1235 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1238 LocTy TypeLoc = Lex.getLoc();
1239 PATypeHolder EltTy(Type::VoidTy);
1240 if (ParseTypeRec(EltTy)) return true;
1242 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1243 "expected end of sequential type"))
1247 if ((unsigned)Size != Size)
1248 return Error(SizeLoc, "size too large for vector");
1249 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1250 return Error(TypeLoc, "vector element type must be fp or integer");
1251 Result = VectorType::get(EltTy, unsigned(Size));
1253 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1254 return Error(TypeLoc, "invalid array element type");
1255 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1260 //===----------------------------------------------------------------------===//
1261 // Function Semantic Analysis.
1262 //===----------------------------------------------------------------------===//
1264 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1267 // Insert unnamed arguments into the NumberedVals list.
1268 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1271 NumberedVals.push_back(AI);
1274 LLParser::PerFunctionState::~PerFunctionState() {
1275 // If there were any forward referenced non-basicblock values, delete them.
1276 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1277 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1278 if (!isa<BasicBlock>(I->second.first)) {
1279 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1281 delete I->second.first;
1282 I->second.first = 0;
1285 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1286 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1287 if (!isa<BasicBlock>(I->second.first)) {
1288 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1290 delete I->second.first;
1291 I->second.first = 0;
1295 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1296 if (!ForwardRefVals.empty())
1297 return P.Error(ForwardRefVals.begin()->second.second,
1298 "use of undefined value '%" + ForwardRefVals.begin()->first +
1300 if (!ForwardRefValIDs.empty())
1301 return P.Error(ForwardRefValIDs.begin()->second.second,
1302 "use of undefined value '%" +
1303 utostr(ForwardRefValIDs.begin()->first) + "'");
1308 /// GetVal - Get a value with the specified name or ID, creating a
1309 /// forward reference record if needed. This can return null if the value
1310 /// exists but does not have the right type.
1311 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1312 const Type *Ty, LocTy Loc) {
1313 // Look this name up in the normal function symbol table.
1314 Value *Val = F.getValueSymbolTable().lookup(Name);
1316 // If this is a forward reference for the value, see if we already created a
1317 // forward ref record.
1319 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1320 I = ForwardRefVals.find(Name);
1321 if (I != ForwardRefVals.end())
1322 Val = I->second.first;
1325 // If we have the value in the symbol table or fwd-ref table, return it.
1327 if (Val->getType() == Ty) return Val;
1328 if (Ty == Type::LabelTy)
1329 P.Error(Loc, "'%" + Name + "' is not a basic block");
1331 P.Error(Loc, "'%" + Name + "' defined with type '" +
1332 Val->getType()->getDescription() + "'");
1336 // Don't make placeholders with invalid type.
1337 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1338 P.Error(Loc, "invalid use of a non-first-class type");
1342 // Otherwise, create a new forward reference for this value and remember it.
1344 if (Ty == Type::LabelTy)
1345 FwdVal = BasicBlock::Create(Name, &F);
1347 FwdVal = new Argument(Ty, Name);
1349 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1353 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1355 // Look this name up in the normal function symbol table.
1356 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1358 // If this is a forward reference for the value, see if we already created a
1359 // forward ref record.
1361 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1362 I = ForwardRefValIDs.find(ID);
1363 if (I != ForwardRefValIDs.end())
1364 Val = I->second.first;
1367 // If we have the value in the symbol table or fwd-ref table, return it.
1369 if (Val->getType() == Ty) return Val;
1370 if (Ty == Type::LabelTy)
1371 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1373 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1374 Val->getType()->getDescription() + "'");
1378 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1379 P.Error(Loc, "invalid use of a non-first-class type");
1383 // Otherwise, create a new forward reference for this value and remember it.
1385 if (Ty == Type::LabelTy)
1386 FwdVal = BasicBlock::Create("", &F);
1388 FwdVal = new Argument(Ty);
1390 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1394 /// SetInstName - After an instruction is parsed and inserted into its
1395 /// basic block, this installs its name.
1396 bool LLParser::PerFunctionState::SetInstName(int NameID,
1397 const std::string &NameStr,
1398 LocTy NameLoc, Instruction *Inst) {
1399 // If this instruction has void type, it cannot have a name or ID specified.
1400 if (Inst->getType() == Type::VoidTy) {
1401 if (NameID != -1 || !NameStr.empty())
1402 return P.Error(NameLoc, "instructions returning void cannot have a name");
1406 // If this was a numbered instruction, verify that the instruction is the
1407 // expected value and resolve any forward references.
1408 if (NameStr.empty()) {
1409 // If neither a name nor an ID was specified, just use the next ID.
1411 NameID = NumberedVals.size();
1413 if (unsigned(NameID) != NumberedVals.size())
1414 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1415 utostr(NumberedVals.size()) + "'");
1417 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1418 ForwardRefValIDs.find(NameID);
1419 if (FI != ForwardRefValIDs.end()) {
1420 if (FI->second.first->getType() != Inst->getType())
1421 return P.Error(NameLoc, "instruction forward referenced with type '" +
1422 FI->second.first->getType()->getDescription() + "'");
1423 FI->second.first->replaceAllUsesWith(Inst);
1424 ForwardRefValIDs.erase(FI);
1427 NumberedVals.push_back(Inst);
1431 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1432 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1433 FI = ForwardRefVals.find(NameStr);
1434 if (FI != ForwardRefVals.end()) {
1435 if (FI->second.first->getType() != Inst->getType())
1436 return P.Error(NameLoc, "instruction forward referenced with type '" +
1437 FI->second.first->getType()->getDescription() + "'");
1438 FI->second.first->replaceAllUsesWith(Inst);
1439 ForwardRefVals.erase(FI);
1442 // Set the name on the instruction.
1443 Inst->setName(NameStr);
1445 if (Inst->getNameStr() != NameStr)
1446 return P.Error(NameLoc, "multiple definition of local value named '" +
1451 /// GetBB - Get a basic block with the specified name or ID, creating a
1452 /// forward reference record if needed.
1453 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1455 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1458 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1459 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1462 /// DefineBB - Define the specified basic block, which is either named or
1463 /// unnamed. If there is an error, this returns null otherwise it returns
1464 /// the block being defined.
1465 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1469 BB = GetBB(NumberedVals.size(), Loc);
1471 BB = GetBB(Name, Loc);
1472 if (BB == 0) return 0; // Already diagnosed error.
1474 // Move the block to the end of the function. Forward ref'd blocks are
1475 // inserted wherever they happen to be referenced.
1476 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1478 // Remove the block from forward ref sets.
1480 ForwardRefValIDs.erase(NumberedVals.size());
1481 NumberedVals.push_back(BB);
1483 // BB forward references are already in the function symbol table.
1484 ForwardRefVals.erase(Name);
1490 //===----------------------------------------------------------------------===//
1492 //===----------------------------------------------------------------------===//
1494 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1495 /// type implied. For example, if we parse "4" we don't know what integer type
1496 /// it has. The value will later be combined with its type and checked for
1498 bool LLParser::ParseValID(ValID &ID) {
1499 ID.Loc = Lex.getLoc();
1500 switch (Lex.getKind()) {
1501 default: return TokError("expected value token");
1502 case lltok::GlobalID: // @42
1503 ID.UIntVal = Lex.getUIntVal();
1504 ID.Kind = ValID::t_GlobalID;
1506 case lltok::GlobalVar: // @foo
1507 ID.StrVal = Lex.getStrVal();
1508 ID.Kind = ValID::t_GlobalName;
1510 case lltok::LocalVarID: // %42
1511 ID.UIntVal = Lex.getUIntVal();
1512 ID.Kind = ValID::t_LocalID;
1514 case lltok::LocalVar: // %foo
1515 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1516 ID.StrVal = Lex.getStrVal();
1517 ID.Kind = ValID::t_LocalName;
1520 ID.APSIntVal = Lex.getAPSIntVal();
1521 ID.Kind = ValID::t_APSInt;
1523 case lltok::APFloat:
1524 ID.APFloatVal = Lex.getAPFloatVal();
1525 ID.Kind = ValID::t_APFloat;
1527 case lltok::kw_true:
1528 ID.ConstantVal = ConstantInt::getTrue();
1529 ID.Kind = ValID::t_Constant;
1531 case lltok::kw_false:
1532 ID.ConstantVal = ConstantInt::getFalse();
1533 ID.Kind = ValID::t_Constant;
1535 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1536 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1537 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1539 case lltok::lbrace: {
1540 // ValID ::= '{' ConstVector '}'
1542 SmallVector<Constant*, 16> Elts;
1543 if (ParseGlobalValueVector(Elts) ||
1544 ParseToken(lltok::rbrace, "expected end of struct constant"))
1547 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1548 ID.Kind = ValID::t_Constant;
1552 // ValID ::= '<' ConstVector '>' --> Vector.
1553 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1555 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1557 SmallVector<Constant*, 16> Elts;
1558 LocTy FirstEltLoc = Lex.getLoc();
1559 if (ParseGlobalValueVector(Elts) ||
1561 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1562 ParseToken(lltok::greater, "expected end of constant"))
1565 if (isPackedStruct) {
1566 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1567 ID.Kind = ValID::t_Constant;
1572 return Error(ID.Loc, "constant vector must not be empty");
1574 if (!Elts[0]->getType()->isInteger() &&
1575 !Elts[0]->getType()->isFloatingPoint())
1576 return Error(FirstEltLoc,
1577 "vector elements must have integer or floating point type");
1579 // Verify that all the vector elements have the same type.
1580 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1581 if (Elts[i]->getType() != Elts[0]->getType())
1582 return Error(FirstEltLoc,
1583 "vector element #" + utostr(i) +
1584 " is not of type '" + Elts[0]->getType()->getDescription());
1586 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1587 ID.Kind = ValID::t_Constant;
1590 case lltok::lsquare: { // Array Constant
1592 SmallVector<Constant*, 16> Elts;
1593 LocTy FirstEltLoc = Lex.getLoc();
1594 if (ParseGlobalValueVector(Elts) ||
1595 ParseToken(lltok::rsquare, "expected end of array constant"))
1598 // Handle empty element.
1600 // Use undef instead of an array because it's inconvenient to determine
1601 // the element type at this point, there being no elements to examine.
1602 ID.Kind = ValID::t_EmptyArray;
1606 if (!Elts[0]->getType()->isFirstClassType())
1607 return Error(FirstEltLoc, "invalid array element type: " +
1608 Elts[0]->getType()->getDescription());
1610 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1612 // Verify all elements are correct type!
1613 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1614 if (Elts[i]->getType() != Elts[0]->getType())
1615 return Error(FirstEltLoc,
1616 "array element #" + utostr(i) +
1617 " is not of type '" +Elts[0]->getType()->getDescription());
1620 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1621 ID.Kind = ValID::t_Constant;
1624 case lltok::kw_c: // c "foo"
1626 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1627 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1628 ID.Kind = ValID::t_Constant;
1631 case lltok::kw_asm: {
1632 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1635 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1636 ParseStringConstant(ID.StrVal) ||
1637 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1638 ParseToken(lltok::StringConstant, "expected constraint string"))
1640 ID.StrVal2 = Lex.getStrVal();
1641 ID.UIntVal = HasSideEffect;
1642 ID.Kind = ValID::t_InlineAsm;
1646 case lltok::kw_trunc:
1647 case lltok::kw_zext:
1648 case lltok::kw_sext:
1649 case lltok::kw_fptrunc:
1650 case lltok::kw_fpext:
1651 case lltok::kw_bitcast:
1652 case lltok::kw_uitofp:
1653 case lltok::kw_sitofp:
1654 case lltok::kw_fptoui:
1655 case lltok::kw_fptosi:
1656 case lltok::kw_inttoptr:
1657 case lltok::kw_ptrtoint: {
1658 unsigned Opc = Lex.getUIntVal();
1659 PATypeHolder DestTy(Type::VoidTy);
1662 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1663 ParseGlobalTypeAndValue(SrcVal) ||
1664 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1665 ParseType(DestTy) ||
1666 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1668 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1669 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1670 SrcVal->getType()->getDescription() + "' to '" +
1671 DestTy->getDescription() + "'");
1672 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1674 ID.Kind = ValID::t_Constant;
1677 case lltok::kw_extractvalue: {
1680 SmallVector<unsigned, 4> Indices;
1681 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1682 ParseGlobalTypeAndValue(Val) ||
1683 ParseIndexList(Indices) ||
1684 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1686 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1687 return Error(ID.Loc, "extractvalue operand must be array or struct");
1688 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1690 return Error(ID.Loc, "invalid indices for extractvalue");
1691 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1692 &Indices[0], Indices.size());
1693 ID.Kind = ValID::t_Constant;
1696 case lltok::kw_insertvalue: {
1698 Constant *Val0, *Val1;
1699 SmallVector<unsigned, 4> Indices;
1700 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1701 ParseGlobalTypeAndValue(Val0) ||
1702 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1703 ParseGlobalTypeAndValue(Val1) ||
1704 ParseIndexList(Indices) ||
1705 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1707 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1708 return Error(ID.Loc, "extractvalue operand must be array or struct");
1709 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1711 return Error(ID.Loc, "invalid indices for insertvalue");
1712 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1713 &Indices[0], Indices.size());
1714 ID.Kind = ValID::t_Constant;
1717 case lltok::kw_icmp:
1718 case lltok::kw_fcmp:
1719 case lltok::kw_vicmp:
1720 case lltok::kw_vfcmp: {
1721 unsigned PredVal, Opc = Lex.getUIntVal();
1722 Constant *Val0, *Val1;
1724 if (ParseCmpPredicate(PredVal, Opc) ||
1725 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1726 ParseGlobalTypeAndValue(Val0) ||
1727 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1728 ParseGlobalTypeAndValue(Val1) ||
1729 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1732 if (Val0->getType() != Val1->getType())
1733 return Error(ID.Loc, "compare operands must have the same type");
1735 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1737 if (Opc == Instruction::FCmp) {
1738 if (!Val0->getType()->isFPOrFPVector())
1739 return Error(ID.Loc, "fcmp requires floating point operands");
1740 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1741 } else if (Opc == Instruction::ICmp) {
1742 if (!Val0->getType()->isIntOrIntVector() &&
1743 !isa<PointerType>(Val0->getType()))
1744 return Error(ID.Loc, "icmp requires pointer or integer operands");
1745 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1746 } else if (Opc == Instruction::VFCmp) {
1747 // FIXME: REMOVE VFCMP Support
1748 if (!Val0->getType()->isFPOrFPVector() ||
1749 !isa<VectorType>(Val0->getType()))
1750 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1751 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1752 } else if (Opc == Instruction::VICmp) {
1753 // FIXME: REMOVE VICMP Support
1754 if (!Val0->getType()->isIntOrIntVector() ||
1755 !isa<VectorType>(Val0->getType()))
1756 return Error(ID.Loc, "vicmp requires vector floating point operands");
1757 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1759 ID.Kind = ValID::t_Constant;
1763 // Binary Operators.
1767 case lltok::kw_udiv:
1768 case lltok::kw_sdiv:
1769 case lltok::kw_fdiv:
1770 case lltok::kw_urem:
1771 case lltok::kw_srem:
1772 case lltok::kw_frem: {
1773 unsigned Opc = Lex.getUIntVal();
1774 Constant *Val0, *Val1;
1776 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1777 ParseGlobalTypeAndValue(Val0) ||
1778 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1779 ParseGlobalTypeAndValue(Val1) ||
1780 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1782 if (Val0->getType() != Val1->getType())
1783 return Error(ID.Loc, "operands of constexpr must have same type");
1784 if (!Val0->getType()->isIntOrIntVector() &&
1785 !Val0->getType()->isFPOrFPVector())
1786 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1787 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1788 ID.Kind = ValID::t_Constant;
1792 // Logical Operations
1794 case lltok::kw_lshr:
1795 case lltok::kw_ashr:
1798 case lltok::kw_xor: {
1799 unsigned Opc = Lex.getUIntVal();
1800 Constant *Val0, *Val1;
1802 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1803 ParseGlobalTypeAndValue(Val0) ||
1804 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1805 ParseGlobalTypeAndValue(Val1) ||
1806 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1808 if (Val0->getType() != Val1->getType())
1809 return Error(ID.Loc, "operands of constexpr must have same type");
1810 if (!Val0->getType()->isIntOrIntVector())
1811 return Error(ID.Loc,
1812 "constexpr requires integer or integer vector operands");
1813 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1814 ID.Kind = ValID::t_Constant;
1818 case lltok::kw_getelementptr:
1819 case lltok::kw_shufflevector:
1820 case lltok::kw_insertelement:
1821 case lltok::kw_extractelement:
1822 case lltok::kw_select: {
1823 unsigned Opc = Lex.getUIntVal();
1824 SmallVector<Constant*, 16> Elts;
1826 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1827 ParseGlobalValueVector(Elts) ||
1828 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1831 if (Opc == Instruction::GetElementPtr) {
1832 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1833 return Error(ID.Loc, "getelementptr requires pointer operand");
1835 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1836 (Value**)&Elts[1], Elts.size()-1))
1837 return Error(ID.Loc, "invalid indices for getelementptr");
1838 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1839 &Elts[1], Elts.size()-1);
1840 } else if (Opc == Instruction::Select) {
1841 if (Elts.size() != 3)
1842 return Error(ID.Loc, "expected three operands to select");
1843 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1845 return Error(ID.Loc, Reason);
1846 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1847 } else if (Opc == Instruction::ShuffleVector) {
1848 if (Elts.size() != 3)
1849 return Error(ID.Loc, "expected three operands to shufflevector");
1850 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1851 return Error(ID.Loc, "invalid operands to shufflevector");
1852 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1853 } else if (Opc == Instruction::ExtractElement) {
1854 if (Elts.size() != 2)
1855 return Error(ID.Loc, "expected two operands to extractelement");
1856 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1857 return Error(ID.Loc, "invalid extractelement operands");
1858 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1860 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1861 if (Elts.size() != 3)
1862 return Error(ID.Loc, "expected three operands to insertelement");
1863 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1864 return Error(ID.Loc, "invalid insertelement operands");
1865 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1868 ID.Kind = ValID::t_Constant;
1877 /// ParseGlobalValue - Parse a global value with the specified type.
1878 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1881 return ParseValID(ID) ||
1882 ConvertGlobalValIDToValue(Ty, ID, V);
1885 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1887 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1889 if (isa<FunctionType>(Ty))
1890 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1893 default: assert(0 && "Unknown ValID!");
1894 case ValID::t_LocalID:
1895 case ValID::t_LocalName:
1896 return Error(ID.Loc, "invalid use of function-local name");
1897 case ValID::t_InlineAsm:
1898 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1899 case ValID::t_GlobalName:
1900 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1902 case ValID::t_GlobalID:
1903 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1905 case ValID::t_APSInt:
1906 if (!isa<IntegerType>(Ty))
1907 return Error(ID.Loc, "integer constant must have integer type");
1908 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1909 V = ConstantInt::get(ID.APSIntVal);
1911 case ValID::t_APFloat:
1912 if (!Ty->isFloatingPoint() ||
1913 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1914 return Error(ID.Loc, "floating point constant invalid for type");
1916 // The lexer has no type info, so builds all float and double FP constants
1917 // as double. Fix this here. Long double does not need this.
1918 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1919 Ty == Type::FloatTy) {
1921 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1924 V = ConstantFP::get(ID.APFloatVal);
1926 if (V->getType() != Ty)
1927 return Error(ID.Loc, "floating point constant does not have type '" +
1928 Ty->getDescription() + "'");
1932 if (!isa<PointerType>(Ty))
1933 return Error(ID.Loc, "null must be a pointer type");
1934 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1936 case ValID::t_Undef:
1937 // FIXME: LabelTy should not be a first-class type.
1938 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1939 !isa<OpaqueType>(Ty))
1940 return Error(ID.Loc, "invalid type for undef constant");
1941 V = UndefValue::get(Ty);
1943 case ValID::t_EmptyArray:
1944 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1945 return Error(ID.Loc, "invalid empty array initializer");
1946 V = UndefValue::get(Ty);
1949 // FIXME: LabelTy should not be a first-class type.
1950 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1951 return Error(ID.Loc, "invalid type for null constant");
1952 V = Constant::getNullValue(Ty);
1954 case ValID::t_Constant:
1955 if (ID.ConstantVal->getType() != Ty)
1956 return Error(ID.Loc, "constant expression type mismatch");
1962 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1963 PATypeHolder Type(Type::VoidTy);
1964 return ParseType(Type) ||
1965 ParseGlobalValue(Type, V);
1968 /// ParseGlobalValueVector
1970 /// ::= TypeAndValue (',' TypeAndValue)*
1971 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1973 if (Lex.getKind() == lltok::rbrace ||
1974 Lex.getKind() == lltok::rsquare ||
1975 Lex.getKind() == lltok::greater ||
1976 Lex.getKind() == lltok::rparen)
1980 if (ParseGlobalTypeAndValue(C)) return true;
1983 while (EatIfPresent(lltok::comma)) {
1984 if (ParseGlobalTypeAndValue(C)) return true;
1992 //===----------------------------------------------------------------------===//
1993 // Function Parsing.
1994 //===----------------------------------------------------------------------===//
1996 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
1997 PerFunctionState &PFS) {
1998 if (ID.Kind == ValID::t_LocalID)
1999 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2000 else if (ID.Kind == ValID::t_LocalName)
2001 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2002 else if (ID.Kind == ValID::ValID::t_InlineAsm) {
2003 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2004 const FunctionType *FTy =
2005 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2006 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2007 return Error(ID.Loc, "invalid type for inline asm constraint string");
2008 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2012 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2020 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2023 return ParseValID(ID) ||
2024 ConvertValIDToValue(Ty, ID, V, PFS);
2027 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2028 PATypeHolder T(Type::VoidTy);
2029 return ParseType(T) ||
2030 ParseValue(T, V, PFS);
2034 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2035 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2036 /// OptionalAlign OptGC
2037 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2038 // Parse the linkage.
2039 LocTy LinkageLoc = Lex.getLoc();
2042 unsigned Visibility, CC, RetAttrs;
2043 PATypeHolder RetType(Type::VoidTy);
2044 LocTy RetTypeLoc = Lex.getLoc();
2045 if (ParseOptionalLinkage(Linkage) ||
2046 ParseOptionalVisibility(Visibility) ||
2047 ParseOptionalCallingConv(CC) ||
2048 ParseOptionalAttrs(RetAttrs, 1) ||
2049 ParseType(RetType, RetTypeLoc))
2052 // Verify that the linkage is ok.
2053 switch ((GlobalValue::LinkageTypes)Linkage) {
2054 case GlobalValue::ExternalLinkage:
2055 break; // always ok.
2056 case GlobalValue::DLLImportLinkage:
2057 case GlobalValue::ExternalWeakLinkage:
2059 return Error(LinkageLoc, "invalid linkage for function definition");
2061 case GlobalValue::InternalLinkage:
2062 case GlobalValue::LinkOnceLinkage:
2063 case GlobalValue::WeakLinkage:
2064 case GlobalValue::DLLExportLinkage:
2066 return Error(LinkageLoc, "invalid linkage for function declaration");
2068 case GlobalValue::AppendingLinkage:
2069 case GlobalValue::GhostLinkage:
2070 case GlobalValue::CommonLinkage:
2071 return Error(LinkageLoc, "invalid function linkage type");
2074 if (!FunctionType::isValidReturnType(RetType) ||
2075 isa<OpaqueType>(RetType))
2076 return Error(RetTypeLoc, "invalid function return type");
2078 if (Lex.getKind() != lltok::GlobalVar)
2079 return TokError("expected function name");
2081 LocTy NameLoc = Lex.getLoc();
2082 std::string FunctionName = Lex.getStrVal();
2085 if (Lex.getKind() != lltok::lparen)
2086 return TokError("expected '(' in function argument list");
2088 std::vector<ArgInfo> ArgList;
2091 std::string Section;
2095 if (ParseArgumentList(ArgList, isVarArg, false) ||
2096 ParseOptionalAttrs(FuncAttrs, 2) ||
2097 (EatIfPresent(lltok::kw_section) &&
2098 ParseStringConstant(Section)) ||
2099 ParseOptionalAlignment(Alignment) ||
2100 (EatIfPresent(lltok::kw_gc) &&
2101 ParseStringConstant(GC)))
2104 // If the alignment was parsed as an attribute, move to the alignment field.
2105 if (FuncAttrs & Attribute::Alignment) {
2106 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2107 FuncAttrs &= ~Attribute::Alignment;
2110 // Okay, if we got here, the function is syntactically valid. Convert types
2111 // and do semantic checks.
2112 std::vector<const Type*> ParamTypeList;
2113 SmallVector<AttributeWithIndex, 8> Attrs;
2114 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2116 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2117 if (FuncAttrs & ObsoleteFuncAttrs) {
2118 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2119 FuncAttrs &= ~ObsoleteFuncAttrs;
2122 if (RetAttrs != Attribute::None)
2123 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2125 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2126 ParamTypeList.push_back(ArgList[i].Type);
2127 if (ArgList[i].Attrs != Attribute::None)
2128 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2131 if (FuncAttrs != Attribute::None)
2132 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2134 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2136 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2137 const PointerType *PFT = PointerType::getUnqual(FT);
2140 if (!FunctionName.empty()) {
2141 // If this was a definition of a forward reference, remove the definition
2142 // from the forward reference table and fill in the forward ref.
2143 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2144 ForwardRefVals.find(FunctionName);
2145 if (FRVI != ForwardRefVals.end()) {
2146 Fn = M->getFunction(FunctionName);
2147 ForwardRefVals.erase(FRVI);
2148 } else if ((Fn = M->getFunction(FunctionName))) {
2149 // If this function already exists in the symbol table, then it is
2150 // multiply defined. We accept a few cases for old backwards compat.
2151 // FIXME: Remove this stuff for LLVM 3.0.
2152 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2153 (!Fn->isDeclaration() && isDefine)) {
2154 // If the redefinition has different type or different attributes,
2155 // reject it. If both have bodies, reject it.
2156 return Error(NameLoc, "invalid redefinition of function '" +
2157 FunctionName + "'");
2158 } else if (Fn->isDeclaration()) {
2159 // Make sure to strip off any argument names so we can't get conflicts.
2160 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2166 } else if (FunctionName.empty()) {
2167 // If this is a definition of a forward referenced function, make sure the
2169 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2170 = ForwardRefValIDs.find(NumberedVals.size());
2171 if (I != ForwardRefValIDs.end()) {
2172 Fn = cast<Function>(I->second.first);
2173 if (Fn->getType() != PFT)
2174 return Error(NameLoc, "type of definition and forward reference of '@" +
2175 utostr(NumberedVals.size()) +"' disagree");
2176 ForwardRefValIDs.erase(I);
2181 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2182 else // Move the forward-reference to the correct spot in the module.
2183 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2185 if (FunctionName.empty())
2186 NumberedVals.push_back(Fn);
2188 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2189 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2190 Fn->setCallingConv(CC);
2191 Fn->setAttributes(PAL);
2192 Fn->setAlignment(Alignment);
2193 Fn->setSection(Section);
2194 if (!GC.empty()) Fn->setGC(GC.c_str());
2196 // Add all of the arguments we parsed to the function.
2197 Function::arg_iterator ArgIt = Fn->arg_begin();
2198 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2199 // If the argument has a name, insert it into the argument symbol table.
2200 if (ArgList[i].Name.empty()) continue;
2202 // Set the name, if it conflicted, it will be auto-renamed.
2203 ArgIt->setName(ArgList[i].Name);
2205 if (ArgIt->getNameStr() != ArgList[i].Name)
2206 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2207 ArgList[i].Name + "'");
2214 /// ParseFunctionBody
2215 /// ::= '{' BasicBlock+ '}'
2216 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2218 bool LLParser::ParseFunctionBody(Function &Fn) {
2219 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2220 return TokError("expected '{' in function body");
2221 Lex.Lex(); // eat the {.
2223 PerFunctionState PFS(*this, Fn);
2225 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2226 if (ParseBasicBlock(PFS)) return true;
2231 // Verify function is ok.
2232 return PFS.VerifyFunctionComplete();
2236 /// ::= LabelStr? Instruction*
2237 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2238 // If this basic block starts out with a name, remember it.
2240 LocTy NameLoc = Lex.getLoc();
2241 if (Lex.getKind() == lltok::LabelStr) {
2242 Name = Lex.getStrVal();
2246 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2247 if (BB == 0) return true;
2249 std::string NameStr;
2251 // Parse the instructions in this block until we get a terminator.
2254 // This instruction may have three possibilities for a name: a) none
2255 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2256 LocTy NameLoc = Lex.getLoc();
2260 if (Lex.getKind() == lltok::LocalVarID) {
2261 NameID = Lex.getUIntVal();
2263 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2265 } else if (Lex.getKind() == lltok::LocalVar ||
2266 // FIXME: REMOVE IN LLVM 3.0
2267 Lex.getKind() == lltok::StringConstant) {
2268 NameStr = Lex.getStrVal();
2270 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2274 if (ParseInstruction(Inst, BB, PFS)) return true;
2276 BB->getInstList().push_back(Inst);
2278 // Set the name on the instruction.
2279 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2280 } while (!isa<TerminatorInst>(Inst));
2285 //===----------------------------------------------------------------------===//
2286 // Instruction Parsing.
2287 //===----------------------------------------------------------------------===//
2289 /// ParseInstruction - Parse one of the many different instructions.
2291 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2292 PerFunctionState &PFS) {
2293 lltok::Kind Token = Lex.getKind();
2294 if (Token == lltok::Eof)
2295 return TokError("found end of file when expecting more instructions");
2296 LocTy Loc = Lex.getLoc();
2297 Lex.Lex(); // Eat the keyword.
2300 default: return Error(Loc, "expected instruction opcode");
2301 // Terminator Instructions.
2302 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2303 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2304 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2305 case lltok::kw_br: return ParseBr(Inst, PFS);
2306 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2307 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2308 // Binary Operators.
2311 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0);
2313 case lltok::kw_udiv:
2314 case lltok::kw_sdiv:
2315 case lltok::kw_urem:
2316 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1);
2317 case lltok::kw_fdiv:
2318 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2);
2320 case lltok::kw_lshr:
2321 case lltok::kw_ashr:
2324 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2325 case lltok::kw_icmp:
2326 case lltok::kw_fcmp:
2327 case lltok::kw_vicmp:
2328 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2330 case lltok::kw_trunc:
2331 case lltok::kw_zext:
2332 case lltok::kw_sext:
2333 case lltok::kw_fptrunc:
2334 case lltok::kw_fpext:
2335 case lltok::kw_bitcast:
2336 case lltok::kw_uitofp:
2337 case lltok::kw_sitofp:
2338 case lltok::kw_fptoui:
2339 case lltok::kw_fptosi:
2340 case lltok::kw_inttoptr:
2341 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2343 case lltok::kw_select: return ParseSelect(Inst, PFS);
2344 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2345 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2346 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2347 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2348 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2349 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2350 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2352 case lltok::kw_alloca:
2353 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2354 case lltok::kw_free: return ParseFree(Inst, PFS);
2355 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2356 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2357 case lltok::kw_volatile:
2358 if (EatIfPresent(lltok::kw_load))
2359 return ParseLoad(Inst, PFS, true);
2360 else if (EatIfPresent(lltok::kw_store))
2361 return ParseStore(Inst, PFS, true);
2363 return TokError("expected 'load' or 'store'");
2364 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2365 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2366 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2367 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2371 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2372 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2373 // FIXME: REMOVE vicmp/vfcmp!
2374 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2375 switch (Lex.getKind()) {
2376 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2377 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2378 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2379 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2380 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2381 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2382 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2383 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2384 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2385 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2386 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2387 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2388 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2389 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2390 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2391 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2392 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2395 switch (Lex.getKind()) {
2396 default: TokError("expected icmp predicate (e.g. 'eq')");
2397 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2398 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2399 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2400 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2401 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2402 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2403 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2404 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2405 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2406 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2413 //===----------------------------------------------------------------------===//
2414 // Terminator Instructions.
2415 //===----------------------------------------------------------------------===//
2417 /// ParseRet - Parse a return instruction.
2419 /// ::= 'ret' TypeAndValue
2420 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2421 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2422 PerFunctionState &PFS) {
2423 PATypeHolder Ty(Type::VoidTy);
2424 if (ParseType(Ty)) return true;
2426 if (Ty == Type::VoidTy) {
2427 Inst = ReturnInst::Create();
2432 if (ParseValue(Ty, RV, PFS)) return true;
2434 // The normal case is one return value.
2435 if (Lex.getKind() == lltok::comma) {
2436 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2437 // of 'ret {i32,i32} {i32 1, i32 2}'
2438 SmallVector<Value*, 8> RVs;
2441 while (EatIfPresent(lltok::comma)) {
2442 if (ParseTypeAndValue(RV, PFS)) return true;
2446 RV = UndefValue::get(PFS.getFunction().getReturnType());
2447 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2448 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2449 BB->getInstList().push_back(I);
2453 Inst = ReturnInst::Create(RV);
2459 /// ::= 'br' TypeAndValue
2460 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2461 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2463 Value *Op0, *Op1, *Op2;
2464 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2466 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2467 Inst = BranchInst::Create(BB);
2471 if (Op0->getType() != Type::Int1Ty)
2472 return Error(Loc, "branch condition must have 'i1' type");
2474 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2475 ParseTypeAndValue(Op1, Loc, PFS) ||
2476 ParseToken(lltok::comma, "expected ',' after true destination") ||
2477 ParseTypeAndValue(Op2, Loc2, PFS))
2480 if (!isa<BasicBlock>(Op1))
2481 return Error(Loc, "true destination of branch must be a basic block");
2482 if (!isa<BasicBlock>(Op2))
2483 return Error(Loc2, "true destination of branch must be a basic block");
2485 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2491 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2493 /// ::= (TypeAndValue ',' TypeAndValue)*
2494 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2495 LocTy CondLoc, BBLoc;
2496 Value *Cond, *DefaultBB;
2497 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2498 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2499 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2500 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2503 if (!isa<IntegerType>(Cond->getType()))
2504 return Error(CondLoc, "switch condition must have integer type");
2505 if (!isa<BasicBlock>(DefaultBB))
2506 return Error(BBLoc, "default destination must be a basic block");
2508 // Parse the jump table pairs.
2509 SmallPtrSet<Value*, 32> SeenCases;
2510 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2511 while (Lex.getKind() != lltok::rsquare) {
2512 Value *Constant, *DestBB;
2514 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2515 ParseToken(lltok::comma, "expected ',' after case value") ||
2516 ParseTypeAndValue(DestBB, BBLoc, PFS))
2519 if (!SeenCases.insert(Constant))
2520 return Error(CondLoc, "duplicate case value in switch");
2521 if (!isa<ConstantInt>(Constant))
2522 return Error(CondLoc, "case value is not a constant integer");
2523 if (!isa<BasicBlock>(DestBB))
2524 return Error(BBLoc, "case destination is not a basic block");
2526 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2527 cast<BasicBlock>(DestBB)));
2530 Lex.Lex(); // Eat the ']'.
2532 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2534 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2535 SI->addCase(Table[i].first, Table[i].second);
2541 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2542 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2543 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2544 LocTy CallLoc = Lex.getLoc();
2545 unsigned CC, RetAttrs, FnAttrs;
2546 PATypeHolder RetType(Type::VoidTy);
2549 SmallVector<ParamInfo, 16> ArgList;
2551 Value *NormalBB, *UnwindBB;
2552 if (ParseOptionalCallingConv(CC) ||
2553 ParseOptionalAttrs(RetAttrs, 1) ||
2554 ParseType(RetType, RetTypeLoc) ||
2555 ParseValID(CalleeID) ||
2556 ParseParameterList(ArgList, PFS) ||
2557 ParseOptionalAttrs(FnAttrs, 2) ||
2558 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2559 ParseTypeAndValue(NormalBB, PFS) ||
2560 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2561 ParseTypeAndValue(UnwindBB, PFS))
2564 if (!isa<BasicBlock>(NormalBB))
2565 return Error(CallLoc, "normal destination is not a basic block");
2566 if (!isa<BasicBlock>(UnwindBB))
2567 return Error(CallLoc, "unwind destination is not a basic block");
2569 // If RetType is a non-function pointer type, then this is the short syntax
2570 // for the call, which means that RetType is just the return type. Infer the
2571 // rest of the function argument types from the arguments that are present.
2572 const PointerType *PFTy = 0;
2573 const FunctionType *Ty = 0;
2574 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2575 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2576 // Pull out the types of all of the arguments...
2577 std::vector<const Type*> ParamTypes;
2578 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2579 ParamTypes.push_back(ArgList[i].V->getType());
2581 if (!FunctionType::isValidReturnType(RetType))
2582 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2584 Ty = FunctionType::get(RetType, ParamTypes, false);
2585 PFTy = PointerType::getUnqual(Ty);
2588 // Look up the callee.
2590 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2592 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2593 // function attributes.
2594 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2595 if (FnAttrs & ObsoleteFuncAttrs) {
2596 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2597 FnAttrs &= ~ObsoleteFuncAttrs;
2600 // Set up the Attributes for the function.
2601 SmallVector<AttributeWithIndex, 8> Attrs;
2602 if (RetAttrs != Attribute::None)
2603 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2605 SmallVector<Value*, 8> Args;
2607 // Loop through FunctionType's arguments and ensure they are specified
2608 // correctly. Also, gather any parameter attributes.
2609 FunctionType::param_iterator I = Ty->param_begin();
2610 FunctionType::param_iterator E = Ty->param_end();
2611 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2612 const Type *ExpectedTy = 0;
2615 } else if (!Ty->isVarArg()) {
2616 return Error(ArgList[i].Loc, "too many arguments specified");
2619 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2620 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2621 ExpectedTy->getDescription() + "'");
2622 Args.push_back(ArgList[i].V);
2623 if (ArgList[i].Attrs != Attribute::None)
2624 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2628 return Error(CallLoc, "not enough parameters specified for call");
2630 if (FnAttrs != Attribute::None)
2631 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2633 // Finish off the Attributes and check them
2634 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2636 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2637 cast<BasicBlock>(UnwindBB),
2638 Args.begin(), Args.end());
2639 II->setCallingConv(CC);
2640 II->setAttributes(PAL);
2647 //===----------------------------------------------------------------------===//
2648 // Binary Operators.
2649 //===----------------------------------------------------------------------===//
2652 /// ::= ArithmeticOps TypeAndValue ',' Value
2654 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2655 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2656 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2657 unsigned Opc, unsigned OperandType) {
2658 LocTy Loc; Value *LHS, *RHS;
2659 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2660 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2661 ParseValue(LHS->getType(), RHS, PFS))
2665 switch (OperandType) {
2666 default: assert(0 && "Unknown operand type!");
2667 case 0: // int or FP.
2668 Valid = LHS->getType()->isIntOrIntVector() ||
2669 LHS->getType()->isFPOrFPVector();
2671 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2672 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2676 return Error(Loc, "invalid operand type for instruction");
2678 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2683 /// ::= ArithmeticOps TypeAndValue ',' Value {
2684 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2686 LocTy Loc; Value *LHS, *RHS;
2687 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2688 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2689 ParseValue(LHS->getType(), RHS, PFS))
2692 if (!LHS->getType()->isIntOrIntVector())
2693 return Error(Loc,"instruction requires integer or integer vector operands");
2695 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2701 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2702 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2703 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2704 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2705 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2707 // Parse the integer/fp comparison predicate.
2711 if (ParseCmpPredicate(Pred, Opc) ||
2712 ParseTypeAndValue(LHS, Loc, PFS) ||
2713 ParseToken(lltok::comma, "expected ',' after compare value") ||
2714 ParseValue(LHS->getType(), RHS, PFS))
2717 if (Opc == Instruction::FCmp) {
2718 if (!LHS->getType()->isFPOrFPVector())
2719 return Error(Loc, "fcmp requires floating point operands");
2720 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2721 } else if (Opc == Instruction::ICmp) {
2722 if (!LHS->getType()->isIntOrIntVector() &&
2723 !isa<PointerType>(LHS->getType()))
2724 return Error(Loc, "icmp requires integer operands");
2725 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2726 } else if (Opc == Instruction::VFCmp) {
2727 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2728 return Error(Loc, "vfcmp requires vector floating point operands");
2729 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2730 } else if (Opc == Instruction::VICmp) {
2731 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2732 return Error(Loc, "vicmp requires vector floating point operands");
2733 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2738 //===----------------------------------------------------------------------===//
2739 // Other Instructions.
2740 //===----------------------------------------------------------------------===//
2744 /// ::= CastOpc TypeAndValue 'to' Type
2745 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2747 LocTy Loc; Value *Op;
2748 PATypeHolder DestTy(Type::VoidTy);
2749 if (ParseTypeAndValue(Op, Loc, PFS) ||
2750 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2754 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2755 return Error(Loc, "invalid cast opcode for cast from '" +
2756 Op->getType()->getDescription() + "' to '" +
2757 DestTy->getDescription() + "'");
2758 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2763 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2764 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2766 Value *Op0, *Op1, *Op2;
2767 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2768 ParseToken(lltok::comma, "expected ',' after select condition") ||
2769 ParseTypeAndValue(Op1, PFS) ||
2770 ParseToken(lltok::comma, "expected ',' after select value") ||
2771 ParseTypeAndValue(Op2, PFS))
2774 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2775 return Error(Loc, Reason);
2777 Inst = SelectInst::Create(Op0, Op1, Op2);
2782 /// ::= 'va_arg' TypeAndValue ',' Type
2783 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2785 PATypeHolder EltTy(Type::VoidTy);
2787 if (ParseTypeAndValue(Op, PFS) ||
2788 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2789 ParseType(EltTy, TypeLoc))
2792 if (!EltTy->isFirstClassType())
2793 return Error(TypeLoc, "va_arg requires operand with first class type");
2795 Inst = new VAArgInst(Op, EltTy);
2799 /// ParseExtractElement
2800 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2801 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2804 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2805 ParseToken(lltok::comma, "expected ',' after extract value") ||
2806 ParseTypeAndValue(Op1, PFS))
2809 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2810 return Error(Loc, "invalid extractelement operands");
2812 Inst = new ExtractElementInst(Op0, Op1);
2816 /// ParseInsertElement
2817 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2818 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2820 Value *Op0, *Op1, *Op2;
2821 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2822 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2823 ParseTypeAndValue(Op1, PFS) ||
2824 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2825 ParseTypeAndValue(Op2, PFS))
2828 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2829 return Error(Loc, "invalid extractelement operands");
2831 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2835 /// ParseShuffleVector
2836 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2837 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2839 Value *Op0, *Op1, *Op2;
2840 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2841 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2842 ParseTypeAndValue(Op1, PFS) ||
2843 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2844 ParseTypeAndValue(Op2, PFS))
2847 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2848 return Error(Loc, "invalid extractelement operands");
2850 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2855 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2856 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2857 PATypeHolder Ty(Type::VoidTy);
2859 LocTy TypeLoc = Lex.getLoc();
2861 if (ParseType(Ty) ||
2862 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2863 ParseValue(Ty, Op0, PFS) ||
2864 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2865 ParseValue(Type::LabelTy, Op1, PFS) ||
2866 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2869 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2871 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2873 if (!EatIfPresent(lltok::comma))
2876 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2877 ParseValue(Ty, Op0, PFS) ||
2878 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2879 ParseValue(Type::LabelTy, Op1, PFS) ||
2880 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2884 if (!Ty->isFirstClassType())
2885 return Error(TypeLoc, "phi node must have first class type");
2887 PHINode *PN = PHINode::Create(Ty);
2888 PN->reserveOperandSpace(PHIVals.size());
2889 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2890 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2896 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2897 /// ParameterList OptionalAttrs
2898 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2900 unsigned CC, RetAttrs, FnAttrs;
2901 PATypeHolder RetType(Type::VoidTy);
2904 SmallVector<ParamInfo, 16> ArgList;
2905 LocTy CallLoc = Lex.getLoc();
2907 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2908 ParseOptionalCallingConv(CC) ||
2909 ParseOptionalAttrs(RetAttrs, 1) ||
2910 ParseType(RetType, RetTypeLoc) ||
2911 ParseValID(CalleeID) ||
2912 ParseParameterList(ArgList, PFS) ||
2913 ParseOptionalAttrs(FnAttrs, 2))
2916 // If RetType is a non-function pointer type, then this is the short syntax
2917 // for the call, which means that RetType is just the return type. Infer the
2918 // rest of the function argument types from the arguments that are present.
2919 const PointerType *PFTy = 0;
2920 const FunctionType *Ty = 0;
2921 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2922 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2923 // Pull out the types of all of the arguments...
2924 std::vector<const Type*> ParamTypes;
2925 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2926 ParamTypes.push_back(ArgList[i].V->getType());
2928 if (!FunctionType::isValidReturnType(RetType))
2929 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2931 Ty = FunctionType::get(RetType, ParamTypes, false);
2932 PFTy = PointerType::getUnqual(Ty);
2935 // Look up the callee.
2937 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2939 // Check for call to invalid intrinsic to avoid crashing later.
2940 if (Function *F = dyn_cast<Function>(Callee)) {
2941 if (F->hasName() && F->getNameLen() >= 5 &&
2942 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
2943 !F->getIntrinsicID(true))
2944 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
2945 F->getNameStr() + "'");
2948 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2949 // function attributes.
2950 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2951 if (FnAttrs & ObsoleteFuncAttrs) {
2952 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2953 FnAttrs &= ~ObsoleteFuncAttrs;
2956 // Set up the Attributes for the function.
2957 SmallVector<AttributeWithIndex, 8> Attrs;
2958 if (RetAttrs != Attribute::None)
2959 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2961 SmallVector<Value*, 8> Args;
2963 // Loop through FunctionType's arguments and ensure they are specified
2964 // correctly. Also, gather any parameter attributes.
2965 FunctionType::param_iterator I = Ty->param_begin();
2966 FunctionType::param_iterator E = Ty->param_end();
2967 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2968 const Type *ExpectedTy = 0;
2971 } else if (!Ty->isVarArg()) {
2972 return Error(ArgList[i].Loc, "too many arguments specified");
2975 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2976 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2977 ExpectedTy->getDescription() + "'");
2978 Args.push_back(ArgList[i].V);
2979 if (ArgList[i].Attrs != Attribute::None)
2980 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2984 return Error(CallLoc, "not enough parameters specified for call");
2986 if (FnAttrs != Attribute::None)
2987 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2989 // Finish off the Attributes and check them
2990 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2992 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
2993 CI->setTailCall(isTail);
2994 CI->setCallingConv(CC);
2995 CI->setAttributes(PAL);
3000 //===----------------------------------------------------------------------===//
3001 // Memory Instructions.
3002 //===----------------------------------------------------------------------===//
3005 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3006 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3007 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3009 PATypeHolder Ty(Type::VoidTy);
3012 unsigned Alignment = 0;
3013 if (ParseType(Ty)) return true;
3015 if (EatIfPresent(lltok::comma)) {
3016 if (Lex.getKind() == lltok::kw_align) {
3017 if (ParseOptionalAlignment(Alignment)) return true;
3018 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3019 ParseOptionalCommaAlignment(Alignment)) {
3024 if (Size && Size->getType() != Type::Int32Ty)
3025 return Error(SizeLoc, "element count must be i32");
3027 if (Opc == Instruction::Malloc)
3028 Inst = new MallocInst(Ty, Size, Alignment);
3030 Inst = new AllocaInst(Ty, Size, Alignment);
3035 /// ::= 'free' TypeAndValue
3036 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3037 Value *Val; LocTy Loc;
3038 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3039 if (!isa<PointerType>(Val->getType()))
3040 return Error(Loc, "operand to free must be a pointer");
3041 Inst = new FreeInst(Val);
3046 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3047 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3049 Value *Val; LocTy Loc;
3051 if (ParseTypeAndValue(Val, Loc, PFS) ||
3052 ParseOptionalCommaAlignment(Alignment))
3055 if (!isa<PointerType>(Val->getType()) ||
3056 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3057 return Error(Loc, "load operand must be a pointer to a first class type");
3059 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3064 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3065 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3067 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3069 if (ParseTypeAndValue(Val, Loc, PFS) ||
3070 ParseToken(lltok::comma, "expected ',' after store operand") ||
3071 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3072 ParseOptionalCommaAlignment(Alignment))
3075 if (!isa<PointerType>(Ptr->getType()))
3076 return Error(PtrLoc, "store operand must be a pointer");
3077 if (!Val->getType()->isFirstClassType())
3078 return Error(Loc, "store operand must be a first class value");
3079 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3080 return Error(Loc, "stored value and pointer type do not match");
3082 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3087 /// ::= 'getresult' TypeAndValue ',' uint
3088 /// FIXME: Remove support for getresult in LLVM 3.0
3089 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3090 Value *Val; LocTy ValLoc, EltLoc;
3092 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3093 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3094 ParseUInt32(Element, EltLoc))
3097 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3098 return Error(ValLoc, "getresult inst requires an aggregate operand");
3099 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3100 return Error(EltLoc, "invalid getresult index for value");
3101 Inst = ExtractValueInst::Create(Val, Element);
3105 /// ParseGetElementPtr
3106 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3107 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3108 Value *Ptr, *Val; LocTy Loc, EltLoc;
3109 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3111 if (!isa<PointerType>(Ptr->getType()))
3112 return Error(Loc, "base of getelementptr must be a pointer");
3114 SmallVector<Value*, 16> Indices;
3115 while (EatIfPresent(lltok::comma)) {
3116 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3117 if (!isa<IntegerType>(Val->getType()))
3118 return Error(EltLoc, "getelementptr index must be an integer");
3119 Indices.push_back(Val);
3122 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3123 Indices.begin(), Indices.end()))
3124 return Error(Loc, "invalid getelementptr indices");
3125 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3129 /// ParseExtractValue
3130 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3131 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3132 Value *Val; LocTy Loc;
3133 SmallVector<unsigned, 4> Indices;
3134 if (ParseTypeAndValue(Val, Loc, PFS) ||
3135 ParseIndexList(Indices))
3138 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3139 return Error(Loc, "extractvalue operand must be array or struct");
3141 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3143 return Error(Loc, "invalid indices for extractvalue");
3144 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3148 /// ParseInsertValue
3149 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3150 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3151 Value *Val0, *Val1; LocTy Loc0, Loc1;
3152 SmallVector<unsigned, 4> Indices;
3153 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3154 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3155 ParseTypeAndValue(Val1, Loc1, PFS) ||
3156 ParseIndexList(Indices))
3159 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3160 return Error(Loc0, "extractvalue operand must be array or struct");
3162 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3164 return Error(Loc0, "invalid indices for insertvalue");
3165 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());