LLParser.cpp revision 5f4ee1fc5d00ae55c30fa2ce450c69be4c6d6e63
1//===-- LLParser.cpp - Parser Class ---------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the parser class for .ll files. 11// 12//===----------------------------------------------------------------------===// 13 14#include "LLParser.h" 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" 26using namespace llvm; 27 28namespace llvm { 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. 33 struct ValID { 34 enum { 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. 42 } Kind; 43 44 LLParser::LocTy Loc; 45 unsigned UIntVal; 46 std::string StrVal, StrVal2; 47 APSInt APSIntVal; 48 APFloat APFloatVal; 49 Constant *ConstantVal; 50 ValID() : APFloatVal(0.0) {} 51 }; 52} 53 54/// Run: module ::= toplevelentity* 55bool LLParser::Run() { 56 // Prime the lexer. 57 Lex.Lex(); 58 59 return ParseTopLevelEntities() || 60 ValidateEndOfModule(); 61} 62 63/// ValidateEndOfModule - Do final validity and sanity checks at the end of the 64/// module. 65bool 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) + "'"); 74 75 if (!ForwardRefVals.empty()) 76 return Error(ForwardRefVals.begin()->second.second, 77 "use of undefined value '@" + ForwardRefVals.begin()->first + 78 "'"); 79 80 if (!ForwardRefValIDs.empty()) 81 return Error(ForwardRefValIDs.begin()->second.second, 82 "use of undefined value '@" + 83 utostr(ForwardRefValIDs.begin()->first) + "'"); 84 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 88 89 return false; 90} 91 92//===----------------------------------------------------------------------===// 93// Top-Level Entities 94//===----------------------------------------------------------------------===// 95 96bool LLParser::ParseTopLevelEntities() { 97 while (1) { 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; 111 112 // The Global variable production with no name can have many different 113 // optional leading prefixes, the production is: 114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 115 // OptionalAddrSpace ('constant'|'global') ... 116 case lltok::kw_private: // OptionalLinkage 117 case lltok::kw_internal: // OptionalLinkage 118 case lltok::kw_weak: // OptionalLinkage 119 case lltok::kw_weak_odr: // OptionalLinkage 120 case lltok::kw_linkonce: // OptionalLinkage 121 case lltok::kw_linkonce_odr: // OptionalLinkage 122 case lltok::kw_appending: // OptionalLinkage 123 case lltok::kw_dllexport: // OptionalLinkage 124 case lltok::kw_common: // OptionalLinkage 125 case lltok::kw_common_odr: // OptionalLinkage 126 case lltok::kw_dllimport: // OptionalLinkage 127 case lltok::kw_extern_weak: // OptionalLinkage 128 case lltok::kw_external: { // OptionalLinkage 129 unsigned Linkage, Visibility; 130 if (ParseOptionalLinkage(Linkage) || 131 ParseOptionalVisibility(Visibility) || 132 ParseGlobal("", 0, Linkage, true, Visibility)) 133 return true; 134 break; 135 } 136 case lltok::kw_default: // OptionalVisibility 137 case lltok::kw_hidden: // OptionalVisibility 138 case lltok::kw_protected: { // OptionalVisibility 139 unsigned Visibility; 140 if (ParseOptionalVisibility(Visibility) || 141 ParseGlobal("", 0, 0, false, Visibility)) 142 return true; 143 break; 144 } 145 146 case lltok::kw_thread_local: // OptionalThreadLocal 147 case lltok::kw_addrspace: // OptionalAddrSpace 148 case lltok::kw_constant: // GlobalType 149 case lltok::kw_global: // GlobalType 150 if (ParseGlobal("", 0, 0, false, 0)) return true; 151 break; 152 } 153 } 154} 155 156 157/// toplevelentity 158/// ::= 'module' 'asm' STRINGCONSTANT 159bool LLParser::ParseModuleAsm() { 160 assert(Lex.getKind() == lltok::kw_module); 161 Lex.Lex(); 162 163 std::string AsmStr; 164 if (ParseToken(lltok::kw_asm, "expected 'module asm'") || 165 ParseStringConstant(AsmStr)) return true; 166 167 const std::string &AsmSoFar = M->getModuleInlineAsm(); 168 if (AsmSoFar.empty()) 169 M->setModuleInlineAsm(AsmStr); 170 else 171 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr); 172 return false; 173} 174 175/// toplevelentity 176/// ::= 'target' 'triple' '=' STRINGCONSTANT 177/// ::= 'target' 'datalayout' '=' STRINGCONSTANT 178bool LLParser::ParseTargetDefinition() { 179 assert(Lex.getKind() == lltok::kw_target); 180 std::string Str; 181 switch (Lex.Lex()) { 182 default: return TokError("unknown target property"); 183 case lltok::kw_triple: 184 Lex.Lex(); 185 if (ParseToken(lltok::equal, "expected '=' after target triple") || 186 ParseStringConstant(Str)) 187 return true; 188 M->setTargetTriple(Str); 189 return false; 190 case lltok::kw_datalayout: 191 Lex.Lex(); 192 if (ParseToken(lltok::equal, "expected '=' after target datalayout") || 193 ParseStringConstant(Str)) 194 return true; 195 M->setDataLayout(Str); 196 return false; 197 } 198} 199 200/// toplevelentity 201/// ::= 'deplibs' '=' '[' ']' 202/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']' 203bool LLParser::ParseDepLibs() { 204 assert(Lex.getKind() == lltok::kw_deplibs); 205 Lex.Lex(); 206 if (ParseToken(lltok::equal, "expected '=' after deplibs") || 207 ParseToken(lltok::lsquare, "expected '=' after deplibs")) 208 return true; 209 210 if (EatIfPresent(lltok::rsquare)) 211 return false; 212 213 std::string Str; 214 if (ParseStringConstant(Str)) return true; 215 M->addLibrary(Str); 216 217 while (EatIfPresent(lltok::comma)) { 218 if (ParseStringConstant(Str)) return true; 219 M->addLibrary(Str); 220 } 221 222 return ParseToken(lltok::rsquare, "expected ']' at end of list"); 223} 224 225/// toplevelentity 226/// ::= 'type' type 227bool LLParser::ParseUnnamedType() { 228 assert(Lex.getKind() == lltok::kw_type); 229 LocTy TypeLoc = Lex.getLoc(); 230 Lex.Lex(); // eat kw_type 231 232 PATypeHolder Ty(Type::VoidTy); 233 if (ParseType(Ty)) return true; 234 235 unsigned TypeID = NumberedTypes.size(); 236 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"); 243 244 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty); 245 Ty = FI->second.first.get(); 246 ForwardRefTypeIDs.erase(FI); 247 } 248 249 NumberedTypes.push_back(Ty); 250 251 return false; 252} 253 254/// toplevelentity 255/// ::= LocalVar '=' 'type' type 256bool LLParser::ParseNamedType() { 257 std::string Name = Lex.getStrVal(); 258 LocTy NameLoc = Lex.getLoc(); 259 Lex.Lex(); // eat LocalVar. 260 261 PATypeHolder Ty(Type::VoidTy); 262 263 if (ParseToken(lltok::equal, "expected '=' after name") || 264 ParseToken(lltok::kw_type, "expected 'type' after name") || 265 ParseType(Ty)) 266 return true; 267 268 // Set the type name, checking for conflicts as we do so. 269 bool AlreadyExists = M->addTypeName(Name, Ty); 270 if (!AlreadyExists) return false; 271 272 // See if this type is a forward reference. We need to eagerly resolve 273 // types to allow recursive type redefinitions below. 274 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator 275 FI = ForwardRefTypes.find(Name); 276 if (FI != ForwardRefTypes.end()) { 277 if (FI->second.first.get() == Ty) 278 return Error(NameLoc, "self referential type is invalid"); 279 280 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty); 281 Ty = FI->second.first.get(); 282 ForwardRefTypes.erase(FI); 283 } 284 285 // Inserting a name that is already defined, get the existing name. 286 const Type *Existing = M->getTypeByName(Name); 287 assert(Existing && "Conflict but no matching type?!"); 288 289 // Otherwise, this is an attempt to redefine a type. That's okay if 290 // the redefinition is identical to the original. 291 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0 292 if (Existing == Ty) return false; 293 294 // Any other kind of (non-equivalent) redefinition is an error. 295 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" + 296 Ty->getDescription() + "'"); 297} 298 299 300/// toplevelentity 301/// ::= 'declare' FunctionHeader 302bool LLParser::ParseDeclare() { 303 assert(Lex.getKind() == lltok::kw_declare); 304 Lex.Lex(); 305 306 Function *F; 307 return ParseFunctionHeader(F, false); 308} 309 310/// toplevelentity 311/// ::= 'define' FunctionHeader '{' ... 312bool LLParser::ParseDefine() { 313 assert(Lex.getKind() == lltok::kw_define); 314 Lex.Lex(); 315 316 Function *F; 317 return ParseFunctionHeader(F, true) || 318 ParseFunctionBody(*F); 319} 320 321/// ParseGlobalType 322/// ::= 'constant' 323/// ::= 'global' 324bool LLParser::ParseGlobalType(bool &IsConstant) { 325 if (Lex.getKind() == lltok::kw_constant) 326 IsConstant = true; 327 else if (Lex.getKind() == lltok::kw_global) 328 IsConstant = false; 329 else { 330 IsConstant = false; 331 return TokError("expected 'global' or 'constant'"); 332 } 333 Lex.Lex(); 334 return false; 335} 336 337/// ParseNamedGlobal: 338/// GlobalVar '=' OptionalVisibility ALIAS ... 339/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable 340bool LLParser::ParseNamedGlobal() { 341 assert(Lex.getKind() == lltok::GlobalVar); 342 LocTy NameLoc = Lex.getLoc(); 343 std::string Name = Lex.getStrVal(); 344 Lex.Lex(); 345 346 bool HasLinkage; 347 unsigned Linkage, Visibility; 348 if (ParseToken(lltok::equal, "expected '=' in global variable") || 349 ParseOptionalLinkage(Linkage, HasLinkage) || 350 ParseOptionalVisibility(Visibility)) 351 return true; 352 353 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 354 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); 355 return ParseAlias(Name, NameLoc, Visibility); 356} 357 358/// ParseAlias: 359/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee 360/// Aliasee 361/// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')' 362/// 363/// Everything through visibility has already been parsed. 364/// 365bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, 366 unsigned Visibility) { 367 assert(Lex.getKind() == lltok::kw_alias); 368 Lex.Lex(); 369 unsigned Linkage; 370 LocTy LinkageLoc = Lex.getLoc(); 371 if (ParseOptionalLinkage(Linkage)) 372 return true; 373 374 if (Linkage != GlobalValue::ExternalLinkage && 375 Linkage != GlobalValue::WeakAnyLinkage && 376 Linkage != GlobalValue::WeakODRLinkage && 377 Linkage != GlobalValue::InternalLinkage && 378 Linkage != GlobalValue::PrivateLinkage) 379 return Error(LinkageLoc, "invalid linkage type for alias"); 380 381 Constant *Aliasee; 382 LocTy AliaseeLoc = Lex.getLoc(); 383 if (Lex.getKind() != lltok::kw_bitcast) { 384 if (ParseGlobalTypeAndValue(Aliasee)) return true; 385 } else { 386 // The bitcast dest type is not present, it is implied by the dest type. 387 ValID ID; 388 if (ParseValID(ID)) return true; 389 if (ID.Kind != ValID::t_Constant) 390 return Error(AliaseeLoc, "invalid aliasee"); 391 Aliasee = ID.ConstantVal; 392 } 393 394 if (!isa<PointerType>(Aliasee->getType())) 395 return Error(AliaseeLoc, "alias must have pointer type"); 396 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, 400 Aliasee); 401 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); 402 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 408 // ForwardRefVals. 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 + "'"); 413 414 // Otherwise, this was a definition of forward ref. Verify that types 415 // agree. 416 if (Val->getType() != GA->getType()) 417 return Error(NameLoc, 418 "forward reference and definition of alias have different types"); 419 420 // If they agree, just RAUW the old value with the alias and remove the 421 // forward ref info. 422 Val->replaceAllUsesWith(GA); 423 Val->eraseFromParent(); 424 ForwardRefVals.erase(I); 425 } 426 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!"); 430 431 return false; 432} 433 434/// ParseGlobal 435/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal 436/// OptionalAddrSpace GlobalType Type Const 437/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 438/// OptionalAddrSpace GlobalType Type Const 439/// 440/// Everything through visibility has been parsed already. 441/// 442bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, 443 unsigned Linkage, bool HasLinkage, 444 unsigned Visibility) { 445 unsigned AddrSpace; 446 bool ThreadLocal, IsConstant; 447 LocTy TyLoc; 448 449 PATypeHolder Ty(Type::VoidTy); 450 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) || 451 ParseOptionalAddrSpace(AddrSpace) || 452 ParseGlobalType(IsConstant) || 453 ParseType(Ty, TyLoc)) 454 return true; 455 456 // If the linkage is specified and is external, then no initializer is 457 // present. 458 Constant *Init = 0; 459 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage && 460 Linkage != GlobalValue::ExternalWeakLinkage && 461 Linkage != GlobalValue::ExternalLinkage)) { 462 if (ParseGlobalValue(Ty, Init)) 463 return true; 464 } 465 466 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy) 467 return Error(TyLoc, "invalid type for global variable"); 468 469 GlobalVariable *GV = 0; 470 471 // See if the global was forward referenced, if so, use the global. 472 if (!Name.empty()) { 473 if ((GV = M->getGlobalVariable(Name, true)) && 474 !ForwardRefVals.erase(Name)) 475 return Error(NameLoc, "redefinition of global '@" + Name + "'"); 476 } else { 477 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 478 I = ForwardRefValIDs.find(NumberedVals.size()); 479 if (I != ForwardRefValIDs.end()) { 480 GV = cast<GlobalVariable>(I->second.first); 481 ForwardRefValIDs.erase(I); 482 } 483 } 484 485 if (GV == 0) { 486 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name, 487 M, false, AddrSpace); 488 } else { 489 if (GV->getType()->getElementType() != Ty) 490 return Error(TyLoc, 491 "forward reference and definition of global have different types"); 492 493 // Move the forward-reference to the correct spot in the module. 494 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); 495 } 496 497 if (Name.empty()) 498 NumberedVals.push_back(GV); 499 500 // Set the parsed properties on the global. 501 if (Init) 502 GV->setInitializer(Init); 503 GV->setConstant(IsConstant); 504 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 505 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 506 GV->setThreadLocal(ThreadLocal); 507 508 // Parse attributes on the global. 509 while (Lex.getKind() == lltok::comma) { 510 Lex.Lex(); 511 512 if (Lex.getKind() == lltok::kw_section) { 513 Lex.Lex(); 514 GV->setSection(Lex.getStrVal()); 515 if (ParseToken(lltok::StringConstant, "expected global section string")) 516 return true; 517 } else if (Lex.getKind() == lltok::kw_align) { 518 unsigned Alignment; 519 if (ParseOptionalAlignment(Alignment)) return true; 520 GV->setAlignment(Alignment); 521 } else { 522 TokError("unknown global variable property!"); 523 } 524 } 525 526 return false; 527} 528 529 530//===----------------------------------------------------------------------===// 531// GlobalValue Reference/Resolution Routines. 532//===----------------------------------------------------------------------===// 533 534/// GetGlobalVal - Get a value with the specified name or ID, creating a 535/// forward reference record if needed. This can return null if the value 536/// exists but does not have the right type. 537GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, 538 LocTy Loc) { 539 const PointerType *PTy = dyn_cast<PointerType>(Ty); 540 if (PTy == 0) { 541 Error(Loc, "global variable reference must have pointer type"); 542 return 0; 543 } 544 545 // Look this name up in the normal function symbol table. 546 GlobalValue *Val = 547 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 548 549 // If this is a forward reference for the value, see if we already created a 550 // forward ref record. 551 if (Val == 0) { 552 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 553 I = ForwardRefVals.find(Name); 554 if (I != ForwardRefVals.end()) 555 Val = I->second.first; 556 } 557 558 // If we have the value in the symbol table or fwd-ref table, return it. 559 if (Val) { 560 if (Val->getType() == Ty) return Val; 561 Error(Loc, "'@" + Name + "' defined with type '" + 562 Val->getType()->getDescription() + "'"); 563 return 0; 564 } 565 566 // Otherwise, create a new forward reference for this value and remember it. 567 GlobalValue *FwdVal; 568 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) { 569 // Function types can return opaque but functions can't. 570 if (isa<OpaqueType>(FT->getReturnType())) { 571 Error(Loc, "function may not return opaque type"); 572 return 0; 573 } 574 575 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); 576 } else { 577 FwdVal = new GlobalVariable(PTy->getElementType(), false, 578 GlobalValue::ExternalWeakLinkage, 0, Name, M); 579 } 580 581 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 582 return FwdVal; 583} 584 585GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { 586 const PointerType *PTy = dyn_cast<PointerType>(Ty); 587 if (PTy == 0) { 588 Error(Loc, "global variable reference must have pointer type"); 589 return 0; 590 } 591 592 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 593 594 // If this is a forward reference for the value, see if we already created a 595 // forward ref record. 596 if (Val == 0) { 597 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 598 I = ForwardRefValIDs.find(ID); 599 if (I != ForwardRefValIDs.end()) 600 Val = I->second.first; 601 } 602 603 // If we have the value in the symbol table or fwd-ref table, return it. 604 if (Val) { 605 if (Val->getType() == Ty) return Val; 606 Error(Loc, "'@" + utostr(ID) + "' defined with type '" + 607 Val->getType()->getDescription() + "'"); 608 return 0; 609 } 610 611 // Otherwise, create a new forward reference for this value and remember it. 612 GlobalValue *FwdVal; 613 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) { 614 // Function types can return opaque but functions can't. 615 if (isa<OpaqueType>(FT->getReturnType())) { 616 Error(Loc, "function may not return opaque type"); 617 return 0; 618 } 619 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M); 620 } else { 621 FwdVal = new GlobalVariable(PTy->getElementType(), false, 622 GlobalValue::ExternalWeakLinkage, 0, "", M); 623 } 624 625 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 626 return FwdVal; 627} 628 629 630//===----------------------------------------------------------------------===// 631// Helper Routines. 632//===----------------------------------------------------------------------===// 633 634/// ParseToken - If the current token has the specified kind, eat it and return 635/// success. Otherwise, emit the specified error and return failure. 636bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) { 637 if (Lex.getKind() != T) 638 return TokError(ErrMsg); 639 Lex.Lex(); 640 return false; 641} 642 643/// ParseStringConstant 644/// ::= StringConstant 645bool LLParser::ParseStringConstant(std::string &Result) { 646 if (Lex.getKind() != lltok::StringConstant) 647 return TokError("expected string constant"); 648 Result = Lex.getStrVal(); 649 Lex.Lex(); 650 return false; 651} 652 653/// ParseUInt32 654/// ::= uint32 655bool LLParser::ParseUInt32(unsigned &Val) { 656 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 657 return TokError("expected integer"); 658 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 659 if (Val64 != unsigned(Val64)) 660 return TokError("expected 32-bit integer (too large)"); 661 Val = Val64; 662 Lex.Lex(); 663 return false; 664} 665 666 667/// ParseOptionalAddrSpace 668/// := /*empty*/ 669/// := 'addrspace' '(' uint32 ')' 670bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { 671 AddrSpace = 0; 672 if (!EatIfPresent(lltok::kw_addrspace)) 673 return false; 674 return ParseToken(lltok::lparen, "expected '(' in address space") || 675 ParseUInt32(AddrSpace) || 676 ParseToken(lltok::rparen, "expected ')' in address space"); 677} 678 679/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind 680/// indicates what kind of attribute list this is: 0: function arg, 1: result, 681/// 2: function attr. 682bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { 683 Attrs = Attribute::None; 684 LocTy AttrLoc = Lex.getLoc(); 685 686 while (1) { 687 switch (Lex.getKind()) { 688 case lltok::kw_sext: 689 case lltok::kw_zext: 690 // Treat these as signext/zeroext unless they are function attrs. 691 // FIXME: REMOVE THIS IN LLVM 3.0 692 if (AttrKind != 2) { 693 if (Lex.getKind() == lltok::kw_sext) 694 Attrs |= Attribute::SExt; 695 else 696 Attrs |= Attribute::ZExt; 697 break; 698 } 699 // FALL THROUGH. 700 default: // End of attributes. 701 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly)) 702 return Error(AttrLoc, "invalid use of function-only attribute"); 703 704 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly)) 705 return Error(AttrLoc, "invalid use of parameter-only attribute"); 706 707 return false; 708 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break; 709 case lltok::kw_signext: Attrs |= Attribute::SExt; break; 710 case lltok::kw_inreg: Attrs |= Attribute::InReg; break; 711 case lltok::kw_sret: Attrs |= Attribute::StructRet; break; 712 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break; 713 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break; 714 case lltok::kw_byval: Attrs |= Attribute::ByVal; break; 715 case lltok::kw_nest: Attrs |= Attribute::Nest; break; 716 717 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break; 718 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break; 719 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break; 720 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break; 721 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break; 722 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break; 723 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break; 724 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break; 725 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break; 726 727 728 case lltok::kw_align: { 729 unsigned Alignment; 730 if (ParseOptionalAlignment(Alignment)) 731 return true; 732 Attrs |= Attribute::constructAlignmentFromInt(Alignment); 733 continue; 734 } 735 } 736 Lex.Lex(); 737 } 738} 739 740/// ParseOptionalLinkage 741/// ::= /*empty*/ 742/// ::= 'private' 743/// ::= 'internal' 744/// ::= 'weak' 745/// ::= 'weak_odr' 746/// ::= 'linkonce' 747/// ::= 'linkonce_odr' 748/// ::= 'appending' 749/// ::= 'dllexport' 750/// ::= 'common' 751/// ::= 'common_odr' 752/// ::= 'dllimport' 753/// ::= 'extern_weak' 754/// ::= 'external' 755bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { 756 HasLinkage = false; 757 switch (Lex.getKind()) { 758 default: Res = GlobalValue::ExternalLinkage; return false; 759 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break; 760 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break; 761 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break; 762 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break; 763 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break; 764 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break; 765 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break; 766 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break; 767 case lltok::kw_common: Res = GlobalValue::CommonAnyLinkage; break; 768 case lltok::kw_common_odr: Res = GlobalValue::CommonODRLinkage; break; 769 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break; 770 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break; 771 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break; 772 } 773 Lex.Lex(); 774 HasLinkage = true; 775 return false; 776} 777 778/// ParseOptionalVisibility 779/// ::= /*empty*/ 780/// ::= 'default' 781/// ::= 'hidden' 782/// ::= 'protected' 783/// 784bool LLParser::ParseOptionalVisibility(unsigned &Res) { 785 switch (Lex.getKind()) { 786 default: Res = GlobalValue::DefaultVisibility; return false; 787 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break; 788 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break; 789 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break; 790 } 791 Lex.Lex(); 792 return false; 793} 794 795/// ParseOptionalCallingConv 796/// ::= /*empty*/ 797/// ::= 'ccc' 798/// ::= 'fastcc' 799/// ::= 'coldcc' 800/// ::= 'x86_stdcallcc' 801/// ::= 'x86_fastcallcc' 802/// ::= 'cc' UINT 803/// 804bool LLParser::ParseOptionalCallingConv(unsigned &CC) { 805 switch (Lex.getKind()) { 806 default: CC = CallingConv::C; return false; 807 case lltok::kw_ccc: CC = CallingConv::C; break; 808 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 809 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 810 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 811 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 812 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC); 813 } 814 Lex.Lex(); 815 return false; 816} 817 818/// ParseOptionalAlignment 819/// ::= /* empty */ 820/// ::= 'align' 4 821bool LLParser::ParseOptionalAlignment(unsigned &Alignment) { 822 Alignment = 0; 823 if (!EatIfPresent(lltok::kw_align)) 824 return false; 825 LocTy AlignLoc = Lex.getLoc(); 826 if (ParseUInt32(Alignment)) return true; 827 if (!isPowerOf2_32(Alignment)) 828 return Error(AlignLoc, "alignment is not a power of two"); 829 return false; 830} 831 832/// ParseOptionalCommaAlignment 833/// ::= /* empty */ 834/// ::= ',' 'align' 4 835bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) { 836 Alignment = 0; 837 if (!EatIfPresent(lltok::comma)) 838 return false; 839 return ParseToken(lltok::kw_align, "expected 'align'") || 840 ParseUInt32(Alignment); 841} 842 843/// ParseIndexList 844/// ::= (',' uint32)+ 845bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) { 846 if (Lex.getKind() != lltok::comma) 847 return TokError("expected ',' as start of index list"); 848 849 while (EatIfPresent(lltok::comma)) { 850 unsigned Idx; 851 if (ParseUInt32(Idx)) return true; 852 Indices.push_back(Idx); 853 } 854 855 return false; 856} 857 858//===----------------------------------------------------------------------===// 859// Type Parsing. 860//===----------------------------------------------------------------------===// 861 862/// ParseType - Parse and resolve a full type. 863bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) { 864 LocTy TypeLoc = Lex.getLoc(); 865 if (ParseTypeRec(Result)) return true; 866 867 // Verify no unresolved uprefs. 868 if (!UpRefs.empty()) 869 return Error(UpRefs.back().Loc, "invalid unresolved type up reference"); 870 871 if (!AllowVoid && Result.get() == Type::VoidTy) 872 return Error(TypeLoc, "void type only allowed for function results"); 873 874 return false; 875} 876 877/// HandleUpRefs - Every time we finish a new layer of types, this function is 878/// called. It loops through the UpRefs vector, which is a list of the 879/// currently active types. For each type, if the up-reference is contained in 880/// the newly completed type, we decrement the level count. When the level 881/// count reaches zero, the up-referenced type is the type that is passed in: 882/// thus we can complete the cycle. 883/// 884PATypeHolder LLParser::HandleUpRefs(const Type *ty) { 885 // If Ty isn't abstract, or if there are no up-references in it, then there is 886 // nothing to resolve here. 887 if (!ty->isAbstract() || UpRefs.empty()) return ty; 888 889 PATypeHolder Ty(ty); 890#if 0 891 errs() << "Type '" << Ty->getDescription() 892 << "' newly formed. Resolving upreferences.\n" 893 << UpRefs.size() << " upreferences active!\n"; 894#endif 895 896 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes 897 // to zero), we resolve them all together before we resolve them to Ty. At 898 // the end of the loop, if there is anything to resolve to Ty, it will be in 899 // this variable. 900 OpaqueType *TypeToResolve = 0; 901 902 for (unsigned i = 0; i != UpRefs.size(); ++i) { 903 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'. 904 bool ContainsType = 905 std::find(Ty->subtype_begin(), Ty->subtype_end(), 906 UpRefs[i].LastContainedTy) != Ty->subtype_end(); 907 908#if 0 909 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " 910 << UpRefs[i].LastContainedTy->getDescription() << ") = " 911 << (ContainsType ? "true" : "false") 912 << " level=" << UpRefs[i].NestingLevel << "\n"; 913#endif 914 if (!ContainsType) 915 continue; 916 917 // Decrement level of upreference 918 unsigned Level = --UpRefs[i].NestingLevel; 919 UpRefs[i].LastContainedTy = Ty; 920 921 // If the Up-reference has a non-zero level, it shouldn't be resolved yet. 922 if (Level != 0) 923 continue; 924 925#if 0 926 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n"; 927#endif 928 if (!TypeToResolve) 929 TypeToResolve = UpRefs[i].UpRefTy; 930 else 931 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve); 932 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list. 933 --i; // Do not skip the next element. 934 } 935 936 if (TypeToResolve) 937 TypeToResolve->refineAbstractTypeTo(Ty); 938 939 return Ty; 940} 941 942 943/// ParseTypeRec - The recursive function used to process the internal 944/// implementation details of types. 945bool LLParser::ParseTypeRec(PATypeHolder &Result) { 946 switch (Lex.getKind()) { 947 default: 948 return TokError("expected type"); 949 case lltok::Type: 950 // TypeRec ::= 'float' | 'void' (etc) 951 Result = Lex.getTyVal(); 952 Lex.Lex(); 953 break; 954 case lltok::kw_opaque: 955 // TypeRec ::= 'opaque' 956 Result = OpaqueType::get(); 957 Lex.Lex(); 958 break; 959 case lltok::lbrace: 960 // TypeRec ::= '{' ... '}' 961 if (ParseStructType(Result, false)) 962 return true; 963 break; 964 case lltok::lsquare: 965 // TypeRec ::= '[' ... ']' 966 Lex.Lex(); // eat the lsquare. 967 if (ParseArrayVectorType(Result, false)) 968 return true; 969 break; 970 case lltok::less: // Either vector or packed struct. 971 // TypeRec ::= '<' ... '>' 972 Lex.Lex(); 973 if (Lex.getKind() == lltok::lbrace) { 974 if (ParseStructType(Result, true) || 975 ParseToken(lltok::greater, "expected '>' at end of packed struct")) 976 return true; 977 } else if (ParseArrayVectorType(Result, true)) 978 return true; 979 break; 980 case lltok::LocalVar: 981 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0 982 // TypeRec ::= %foo 983 if (const Type *T = M->getTypeByName(Lex.getStrVal())) { 984 Result = T; 985 } else { 986 Result = OpaqueType::get(); 987 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(), 988 std::make_pair(Result, 989 Lex.getLoc()))); 990 M->addTypeName(Lex.getStrVal(), Result.get()); 991 } 992 Lex.Lex(); 993 break; 994 995 case lltok::LocalVarID: 996 // TypeRec ::= %4 997 if (Lex.getUIntVal() < NumberedTypes.size()) 998 Result = NumberedTypes[Lex.getUIntVal()]; 999 else { 1000 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator 1001 I = ForwardRefTypeIDs.find(Lex.getUIntVal()); 1002 if (I != ForwardRefTypeIDs.end()) 1003 Result = I->second.first; 1004 else { 1005 Result = OpaqueType::get(); 1006 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(), 1007 std::make_pair(Result, 1008 Lex.getLoc()))); 1009 } 1010 } 1011 Lex.Lex(); 1012 break; 1013 case lltok::backslash: { 1014 // TypeRec ::= '\' 4 1015 Lex.Lex(); 1016 unsigned Val; 1017 if (ParseUInt32(Val)) return true; 1018 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder. 1019 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT)); 1020 Result = OT; 1021 break; 1022 } 1023 } 1024 1025 // Parse the type suffixes. 1026 while (1) { 1027 switch (Lex.getKind()) { 1028 // End of type. 1029 default: return false; 1030 1031 // TypeRec ::= TypeRec '*' 1032 case lltok::star: 1033 if (Result.get() == Type::LabelTy) 1034 return TokError("basic block pointers are invalid"); 1035 if (Result.get() == Type::VoidTy) 1036 return TokError("pointers to void are invalid; use i8* instead"); 1037 Result = HandleUpRefs(PointerType::getUnqual(Result.get())); 1038 Lex.Lex(); 1039 break; 1040 1041 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*' 1042 case lltok::kw_addrspace: { 1043 if (Result.get() == Type::LabelTy) 1044 return TokError("basic block pointers are invalid"); 1045 if (Result.get() == Type::VoidTy) 1046 return TokError("pointers to void are invalid; use i8* instead"); 1047 unsigned AddrSpace; 1048 if (ParseOptionalAddrSpace(AddrSpace) || 1049 ParseToken(lltok::star, "expected '*' in address space")) 1050 return true; 1051 1052 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace)); 1053 break; 1054 } 1055 1056 /// Types '(' ArgTypeListI ')' OptFuncAttrs 1057 case lltok::lparen: 1058 if (ParseFunctionType(Result)) 1059 return true; 1060 break; 1061 } 1062 } 1063} 1064 1065/// ParseParameterList 1066/// ::= '(' ')' 1067/// ::= '(' Arg (',' Arg)* ')' 1068/// Arg 1069/// ::= Type OptionalAttributes Value OptionalAttributes 1070bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 1071 PerFunctionState &PFS) { 1072 if (ParseToken(lltok::lparen, "expected '(' in call")) 1073 return true; 1074 1075 while (Lex.getKind() != lltok::rparen) { 1076 // If this isn't the first argument, we need a comma. 1077 if (!ArgList.empty() && 1078 ParseToken(lltok::comma, "expected ',' in argument list")) 1079 return true; 1080 1081 // Parse the argument. 1082 LocTy ArgLoc; 1083 PATypeHolder ArgTy(Type::VoidTy); 1084 unsigned ArgAttrs1, ArgAttrs2; 1085 Value *V; 1086 if (ParseType(ArgTy, ArgLoc) || 1087 ParseOptionalAttrs(ArgAttrs1, 0) || 1088 ParseValue(ArgTy, V, PFS) || 1089 // FIXME: Should not allow attributes after the argument, remove this in 1090 // LLVM 3.0. 1091 ParseOptionalAttrs(ArgAttrs2, 0)) 1092 return true; 1093 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2)); 1094 } 1095 1096 Lex.Lex(); // Lex the ')'. 1097 return false; 1098} 1099 1100 1101 1102/// ParseArgumentList - Parse the argument list for a function type or function 1103/// prototype. If 'inType' is true then we are parsing a FunctionType. 1104/// ::= '(' ArgTypeListI ')' 1105/// ArgTypeListI 1106/// ::= /*empty*/ 1107/// ::= '...' 1108/// ::= ArgTypeList ',' '...' 1109/// ::= ArgType (',' ArgType)* 1110/// 1111bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList, 1112 bool &isVarArg, bool inType) { 1113 isVarArg = false; 1114 assert(Lex.getKind() == lltok::lparen); 1115 Lex.Lex(); // eat the (. 1116 1117 if (Lex.getKind() == lltok::rparen) { 1118 // empty 1119 } else if (Lex.getKind() == lltok::dotdotdot) { 1120 isVarArg = true; 1121 Lex.Lex(); 1122 } else { 1123 LocTy TypeLoc = Lex.getLoc(); 1124 PATypeHolder ArgTy(Type::VoidTy); 1125 unsigned Attrs; 1126 std::string Name; 1127 1128 // If we're parsing a type, use ParseTypeRec, because we allow recursive 1129 // types (such as a function returning a pointer to itself). If parsing a 1130 // function prototype, we require fully resolved types. 1131 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) || 1132 ParseOptionalAttrs(Attrs, 0)) return true; 1133 1134 if (ArgTy == Type::VoidTy) 1135 return Error(TypeLoc, "argument can not have void type"); 1136 1137 if (Lex.getKind() == lltok::LocalVar || 1138 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0 1139 Name = Lex.getStrVal(); 1140 Lex.Lex(); 1141 } 1142 1143 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) 1144 return Error(TypeLoc, "invalid type for function argument"); 1145 1146 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); 1147 1148 while (EatIfPresent(lltok::comma)) { 1149 // Handle ... at end of arg list. 1150 if (EatIfPresent(lltok::dotdotdot)) { 1151 isVarArg = true; 1152 break; 1153 } 1154 1155 // Otherwise must be an argument type. 1156 TypeLoc = Lex.getLoc(); 1157 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) || 1158 ParseOptionalAttrs(Attrs, 0)) return true; 1159 1160 if (ArgTy == Type::VoidTy) 1161 return Error(TypeLoc, "argument can not have void type"); 1162 1163 if (Lex.getKind() == lltok::LocalVar || 1164 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0 1165 Name = Lex.getStrVal(); 1166 Lex.Lex(); 1167 } else { 1168 Name = ""; 1169 } 1170 1171 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) 1172 return Error(TypeLoc, "invalid type for function argument"); 1173 1174 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); 1175 } 1176 } 1177 1178 return ParseToken(lltok::rparen, "expected ')' at end of argument list"); 1179} 1180 1181/// ParseFunctionType 1182/// ::= Type ArgumentList OptionalAttrs 1183bool LLParser::ParseFunctionType(PATypeHolder &Result) { 1184 assert(Lex.getKind() == lltok::lparen); 1185 1186 if (!FunctionType::isValidReturnType(Result)) 1187 return TokError("invalid function return type"); 1188 1189 std::vector<ArgInfo> ArgList; 1190 bool isVarArg; 1191 unsigned Attrs; 1192 if (ParseArgumentList(ArgList, isVarArg, true) || 1193 // FIXME: Allow, but ignore attributes on function types! 1194 // FIXME: Remove in LLVM 3.0 1195 ParseOptionalAttrs(Attrs, 2)) 1196 return true; 1197 1198 // Reject names on the arguments lists. 1199 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 1200 if (!ArgList[i].Name.empty()) 1201 return Error(ArgList[i].Loc, "argument name invalid in function type"); 1202 if (!ArgList[i].Attrs != 0) { 1203 // Allow but ignore attributes on function types; this permits 1204 // auto-upgrade. 1205 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0 1206 } 1207 } 1208 1209 std::vector<const Type*> ArgListTy; 1210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 1211 ArgListTy.push_back(ArgList[i].Type); 1212 1213 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg)); 1214 return false; 1215} 1216 1217/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere. 1218/// TypeRec 1219/// ::= '{' '}' 1220/// ::= '{' TypeRec (',' TypeRec)* '}' 1221/// ::= '<' '{' '}' '>' 1222/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>' 1223bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) { 1224 assert(Lex.getKind() == lltok::lbrace); 1225 Lex.Lex(); // Consume the '{' 1226 1227 if (EatIfPresent(lltok::rbrace)) { 1228 Result = StructType::get(std::vector<const Type*>(), Packed); 1229 return false; 1230 } 1231 1232 std::vector<PATypeHolder> ParamsList; 1233 LocTy EltTyLoc = Lex.getLoc(); 1234 if (ParseTypeRec(Result)) return true; 1235 ParamsList.push_back(Result); 1236 1237 if (Result == Type::VoidTy) 1238 return Error(EltTyLoc, "struct element can not have void type"); 1239 1240 while (EatIfPresent(lltok::comma)) { 1241 EltTyLoc = Lex.getLoc(); 1242 if (ParseTypeRec(Result)) return true; 1243 1244 if (Result == Type::VoidTy) 1245 return Error(EltTyLoc, "struct element can not have void type"); 1246 1247 ParamsList.push_back(Result); 1248 } 1249 1250 if (ParseToken(lltok::rbrace, "expected '}' at end of struct")) 1251 return true; 1252 1253 std::vector<const Type*> ParamsListTy; 1254 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i) 1255 ParamsListTy.push_back(ParamsList[i].get()); 1256 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed)); 1257 return false; 1258} 1259 1260/// ParseArrayVectorType - Parse an array or vector type, assuming the first 1261/// token has already been consumed. 1262/// TypeRec 1263/// ::= '[' APSINTVAL 'x' Types ']' 1264/// ::= '<' APSINTVAL 'x' Types '>' 1265bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) { 1266 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 1267 Lex.getAPSIntVal().getBitWidth() > 64) 1268 return TokError("expected number in address space"); 1269 1270 LocTy SizeLoc = Lex.getLoc(); 1271 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 1272 Lex.Lex(); 1273 1274 if (ParseToken(lltok::kw_x, "expected 'x' after element count")) 1275 return true; 1276 1277 LocTy TypeLoc = Lex.getLoc(); 1278 PATypeHolder EltTy(Type::VoidTy); 1279 if (ParseTypeRec(EltTy)) return true; 1280 1281 if (EltTy == Type::VoidTy) 1282 return Error(TypeLoc, "array and vector element type cannot be void"); 1283 1284 if (ParseToken(isVector ? lltok::greater : lltok::rsquare, 1285 "expected end of sequential type")) 1286 return true; 1287 1288 if (isVector) { 1289 if (Size == 0) 1290 return Error(SizeLoc, "zero element vector is illegal"); 1291 if ((unsigned)Size != Size) 1292 return Error(SizeLoc, "size too large for vector"); 1293 if (!EltTy->isFloatingPoint() && !EltTy->isInteger()) 1294 return Error(TypeLoc, "vector element type must be fp or integer"); 1295 Result = VectorType::get(EltTy, unsigned(Size)); 1296 } else { 1297 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy)) 1298 return Error(TypeLoc, "invalid array element type"); 1299 Result = HandleUpRefs(ArrayType::get(EltTy, Size)); 1300 } 1301 return false; 1302} 1303 1304//===----------------------------------------------------------------------===// 1305// Function Semantic Analysis. 1306//===----------------------------------------------------------------------===// 1307 1308LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f) 1309 : P(p), F(f) { 1310 1311 // Insert unnamed arguments into the NumberedVals list. 1312 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 1313 AI != E; ++AI) 1314 if (!AI->hasName()) 1315 NumberedVals.push_back(AI); 1316} 1317 1318LLParser::PerFunctionState::~PerFunctionState() { 1319 // If there were any forward referenced non-basicblock values, delete them. 1320 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator 1321 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I) 1322 if (!isa<BasicBlock>(I->second.first)) { 1323 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first 1324 ->getType())); 1325 delete I->second.first; 1326 I->second.first = 0; 1327 } 1328 1329 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator 1330 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I) 1331 if (!isa<BasicBlock>(I->second.first)) { 1332 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first 1333 ->getType())); 1334 delete I->second.first; 1335 I->second.first = 0; 1336 } 1337} 1338 1339bool LLParser::PerFunctionState::VerifyFunctionComplete() { 1340 if (!ForwardRefVals.empty()) 1341 return P.Error(ForwardRefVals.begin()->second.second, 1342 "use of undefined value '%" + ForwardRefVals.begin()->first + 1343 "'"); 1344 if (!ForwardRefValIDs.empty()) 1345 return P.Error(ForwardRefValIDs.begin()->second.second, 1346 "use of undefined value '%" + 1347 utostr(ForwardRefValIDs.begin()->first) + "'"); 1348 return false; 1349} 1350 1351 1352/// GetVal - Get a value with the specified name or ID, creating a 1353/// forward reference record if needed. This can return null if the value 1354/// exists but does not have the right type. 1355Value *LLParser::PerFunctionState::GetVal(const std::string &Name, 1356 const Type *Ty, LocTy Loc) { 1357 // Look this name up in the normal function symbol table. 1358 Value *Val = F.getValueSymbolTable().lookup(Name); 1359 1360 // If this is a forward reference for the value, see if we already created a 1361 // forward ref record. 1362 if (Val == 0) { 1363 std::map<std::string, std::pair<Value*, LocTy> >::iterator 1364 I = ForwardRefVals.find(Name); 1365 if (I != ForwardRefVals.end()) 1366 Val = I->second.first; 1367 } 1368 1369 // If we have the value in the symbol table or fwd-ref table, return it. 1370 if (Val) { 1371 if (Val->getType() == Ty) return Val; 1372 if (Ty == Type::LabelTy) 1373 P.Error(Loc, "'%" + Name + "' is not a basic block"); 1374 else 1375 P.Error(Loc, "'%" + Name + "' defined with type '" + 1376 Val->getType()->getDescription() + "'"); 1377 return 0; 1378 } 1379 1380 // Don't make placeholders with invalid type. 1381 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) { 1382 P.Error(Loc, "invalid use of a non-first-class type"); 1383 return 0; 1384 } 1385 1386 // Otherwise, create a new forward reference for this value and remember it. 1387 Value *FwdVal; 1388 if (Ty == Type::LabelTy) 1389 FwdVal = BasicBlock::Create(Name, &F); 1390 else 1391 FwdVal = new Argument(Ty, Name); 1392 1393 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 1394 return FwdVal; 1395} 1396 1397Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty, 1398 LocTy Loc) { 1399 // Look this name up in the normal function symbol table. 1400 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 1401 1402 // If this is a forward reference for the value, see if we already created a 1403 // forward ref record. 1404 if (Val == 0) { 1405 std::map<unsigned, std::pair<Value*, LocTy> >::iterator 1406 I = ForwardRefValIDs.find(ID); 1407 if (I != ForwardRefValIDs.end()) 1408 Val = I->second.first; 1409 } 1410 1411 // If we have the value in the symbol table or fwd-ref table, return it. 1412 if (Val) { 1413 if (Val->getType() == Ty) return Val; 1414 if (Ty == Type::LabelTy) 1415 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block"); 1416 else 1417 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" + 1418 Val->getType()->getDescription() + "'"); 1419 return 0; 1420 } 1421 1422 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) { 1423 P.Error(Loc, "invalid use of a non-first-class type"); 1424 return 0; 1425 } 1426 1427 // Otherwise, create a new forward reference for this value and remember it. 1428 Value *FwdVal; 1429 if (Ty == Type::LabelTy) 1430 FwdVal = BasicBlock::Create("", &F); 1431 else 1432 FwdVal = new Argument(Ty); 1433 1434 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 1435 return FwdVal; 1436} 1437 1438/// SetInstName - After an instruction is parsed and inserted into its 1439/// basic block, this installs its name. 1440bool LLParser::PerFunctionState::SetInstName(int NameID, 1441 const std::string &NameStr, 1442 LocTy NameLoc, Instruction *Inst) { 1443 // If this instruction has void type, it cannot have a name or ID specified. 1444 if (Inst->getType() == Type::VoidTy) { 1445 if (NameID != -1 || !NameStr.empty()) 1446 return P.Error(NameLoc, "instructions returning void cannot have a name"); 1447 return false; 1448 } 1449 1450 // If this was a numbered instruction, verify that the instruction is the 1451 // expected value and resolve any forward references. 1452 if (NameStr.empty()) { 1453 // If neither a name nor an ID was specified, just use the next ID. 1454 if (NameID == -1) 1455 NameID = NumberedVals.size(); 1456 1457 if (unsigned(NameID) != NumberedVals.size()) 1458 return P.Error(NameLoc, "instruction expected to be numbered '%" + 1459 utostr(NumberedVals.size()) + "'"); 1460 1461 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI = 1462 ForwardRefValIDs.find(NameID); 1463 if (FI != ForwardRefValIDs.end()) { 1464 if (FI->second.first->getType() != Inst->getType()) 1465 return P.Error(NameLoc, "instruction forward referenced with type '" + 1466 FI->second.first->getType()->getDescription() + "'"); 1467 FI->second.first->replaceAllUsesWith(Inst); 1468 ForwardRefValIDs.erase(FI); 1469 } 1470 1471 NumberedVals.push_back(Inst); 1472 return false; 1473 } 1474 1475 // Otherwise, the instruction had a name. Resolve forward refs and set it. 1476 std::map<std::string, std::pair<Value*, LocTy> >::iterator 1477 FI = ForwardRefVals.find(NameStr); 1478 if (FI != ForwardRefVals.end()) { 1479 if (FI->second.first->getType() != Inst->getType()) 1480 return P.Error(NameLoc, "instruction forward referenced with type '" + 1481 FI->second.first->getType()->getDescription() + "'"); 1482 FI->second.first->replaceAllUsesWith(Inst); 1483 ForwardRefVals.erase(FI); 1484 } 1485 1486 // Set the name on the instruction. 1487 Inst->setName(NameStr); 1488 1489 if (Inst->getNameStr() != NameStr) 1490 return P.Error(NameLoc, "multiple definition of local value named '" + 1491 NameStr + "'"); 1492 return false; 1493} 1494 1495/// GetBB - Get a basic block with the specified name or ID, creating a 1496/// forward reference record if needed. 1497BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name, 1498 LocTy Loc) { 1499 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc)); 1500} 1501 1502BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) { 1503 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc)); 1504} 1505 1506/// DefineBB - Define the specified basic block, which is either named or 1507/// unnamed. If there is an error, this returns null otherwise it returns 1508/// the block being defined. 1509BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, 1510 LocTy Loc) { 1511 BasicBlock *BB; 1512 if (Name.empty()) 1513 BB = GetBB(NumberedVals.size(), Loc); 1514 else 1515 BB = GetBB(Name, Loc); 1516 if (BB == 0) return 0; // Already diagnosed error. 1517 1518 // Move the block to the end of the function. Forward ref'd blocks are 1519 // inserted wherever they happen to be referenced. 1520 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 1521 1522 // Remove the block from forward ref sets. 1523 if (Name.empty()) { 1524 ForwardRefValIDs.erase(NumberedVals.size()); 1525 NumberedVals.push_back(BB); 1526 } else { 1527 // BB forward references are already in the function symbol table. 1528 ForwardRefVals.erase(Name); 1529 } 1530 1531 return BB; 1532} 1533 1534//===----------------------------------------------------------------------===// 1535// Constants. 1536//===----------------------------------------------------------------------===// 1537 1538/// ParseValID - Parse an abstract value that doesn't necessarily have a 1539/// type implied. For example, if we parse "4" we don't know what integer type 1540/// it has. The value will later be combined with its type and checked for 1541/// sanity. 1542bool LLParser::ParseValID(ValID &ID) { 1543 ID.Loc = Lex.getLoc(); 1544 switch (Lex.getKind()) { 1545 default: return TokError("expected value token"); 1546 case lltok::GlobalID: // @42 1547 ID.UIntVal = Lex.getUIntVal(); 1548 ID.Kind = ValID::t_GlobalID; 1549 break; 1550 case lltok::GlobalVar: // @foo 1551 ID.StrVal = Lex.getStrVal(); 1552 ID.Kind = ValID::t_GlobalName; 1553 break; 1554 case lltok::LocalVarID: // %42 1555 ID.UIntVal = Lex.getUIntVal(); 1556 ID.Kind = ValID::t_LocalID; 1557 break; 1558 case lltok::LocalVar: // %foo 1559 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0 1560 ID.StrVal = Lex.getStrVal(); 1561 ID.Kind = ValID::t_LocalName; 1562 break; 1563 case lltok::APSInt: 1564 ID.APSIntVal = Lex.getAPSIntVal(); 1565 ID.Kind = ValID::t_APSInt; 1566 break; 1567 case lltok::APFloat: 1568 ID.APFloatVal = Lex.getAPFloatVal(); 1569 ID.Kind = ValID::t_APFloat; 1570 break; 1571 case lltok::kw_true: 1572 ID.ConstantVal = ConstantInt::getTrue(); 1573 ID.Kind = ValID::t_Constant; 1574 break; 1575 case lltok::kw_false: 1576 ID.ConstantVal = ConstantInt::getFalse(); 1577 ID.Kind = ValID::t_Constant; 1578 break; 1579 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 1580 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 1581 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 1582 1583 case lltok::lbrace: { 1584 // ValID ::= '{' ConstVector '}' 1585 Lex.Lex(); 1586 SmallVector<Constant*, 16> Elts; 1587 if (ParseGlobalValueVector(Elts) || 1588 ParseToken(lltok::rbrace, "expected end of struct constant")) 1589 return true; 1590 1591 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false); 1592 ID.Kind = ValID::t_Constant; 1593 return false; 1594 } 1595 case lltok::less: { 1596 // ValID ::= '<' ConstVector '>' --> Vector. 1597 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 1598 Lex.Lex(); 1599 bool isPackedStruct = EatIfPresent(lltok::lbrace); 1600 1601 SmallVector<Constant*, 16> Elts; 1602 LocTy FirstEltLoc = Lex.getLoc(); 1603 if (ParseGlobalValueVector(Elts) || 1604 (isPackedStruct && 1605 ParseToken(lltok::rbrace, "expected end of packed struct")) || 1606 ParseToken(lltok::greater, "expected end of constant")) 1607 return true; 1608 1609 if (isPackedStruct) { 1610 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true); 1611 ID.Kind = ValID::t_Constant; 1612 return false; 1613 } 1614 1615 if (Elts.empty()) 1616 return Error(ID.Loc, "constant vector must not be empty"); 1617 1618 if (!Elts[0]->getType()->isInteger() && 1619 !Elts[0]->getType()->isFloatingPoint()) 1620 return Error(FirstEltLoc, 1621 "vector elements must have integer or floating point type"); 1622 1623 // Verify that all the vector elements have the same type. 1624 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 1625 if (Elts[i]->getType() != Elts[0]->getType()) 1626 return Error(FirstEltLoc, 1627 "vector element #" + utostr(i) + 1628 " is not of type '" + Elts[0]->getType()->getDescription()); 1629 1630 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size()); 1631 ID.Kind = ValID::t_Constant; 1632 return false; 1633 } 1634 case lltok::lsquare: { // Array Constant 1635 Lex.Lex(); 1636 SmallVector<Constant*, 16> Elts; 1637 LocTy FirstEltLoc = Lex.getLoc(); 1638 if (ParseGlobalValueVector(Elts) || 1639 ParseToken(lltok::rsquare, "expected end of array constant")) 1640 return true; 1641 1642 // Handle empty element. 1643 if (Elts.empty()) { 1644 // Use undef instead of an array because it's inconvenient to determine 1645 // the element type at this point, there being no elements to examine. 1646 ID.Kind = ValID::t_EmptyArray; 1647 return false; 1648 } 1649 1650 if (!Elts[0]->getType()->isFirstClassType()) 1651 return Error(FirstEltLoc, "invalid array element type: " + 1652 Elts[0]->getType()->getDescription()); 1653 1654 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 1655 1656 // Verify all elements are correct type! 1657 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 1658 if (Elts[i]->getType() != Elts[0]->getType()) 1659 return Error(FirstEltLoc, 1660 "array element #" + utostr(i) + 1661 " is not of type '" +Elts[0]->getType()->getDescription()); 1662 } 1663 1664 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size()); 1665 ID.Kind = ValID::t_Constant; 1666 return false; 1667 } 1668 case lltok::kw_c: // c "foo" 1669 Lex.Lex(); 1670 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false); 1671 if (ParseToken(lltok::StringConstant, "expected string")) return true; 1672 ID.Kind = ValID::t_Constant; 1673 return false; 1674 1675 case lltok::kw_asm: { 1676 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT 1677 bool HasSideEffect; 1678 Lex.Lex(); 1679 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 1680 ParseStringConstant(ID.StrVal) || 1681 ParseToken(lltok::comma, "expected comma in inline asm expression") || 1682 ParseToken(lltok::StringConstant, "expected constraint string")) 1683 return true; 1684 ID.StrVal2 = Lex.getStrVal(); 1685 ID.UIntVal = HasSideEffect; 1686 ID.Kind = ValID::t_InlineAsm; 1687 return false; 1688 } 1689 1690 case lltok::kw_trunc: 1691 case lltok::kw_zext: 1692 case lltok::kw_sext: 1693 case lltok::kw_fptrunc: 1694 case lltok::kw_fpext: 1695 case lltok::kw_bitcast: 1696 case lltok::kw_uitofp: 1697 case lltok::kw_sitofp: 1698 case lltok::kw_fptoui: 1699 case lltok::kw_fptosi: 1700 case lltok::kw_inttoptr: 1701 case lltok::kw_ptrtoint: { 1702 unsigned Opc = Lex.getUIntVal(); 1703 PATypeHolder DestTy(Type::VoidTy); 1704 Constant *SrcVal; 1705 Lex.Lex(); 1706 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") || 1707 ParseGlobalTypeAndValue(SrcVal) || 1708 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") || 1709 ParseType(DestTy) || 1710 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 1711 return true; 1712 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 1713 return Error(ID.Loc, "invalid cast opcode for cast from '" + 1714 SrcVal->getType()->getDescription() + "' to '" + 1715 DestTy->getDescription() + "'"); 1716 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal, 1717 DestTy); 1718 ID.Kind = ValID::t_Constant; 1719 return false; 1720 } 1721 case lltok::kw_extractvalue: { 1722 Lex.Lex(); 1723 Constant *Val; 1724 SmallVector<unsigned, 4> Indices; 1725 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")|| 1726 ParseGlobalTypeAndValue(Val) || 1727 ParseIndexList(Indices) || 1728 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 1729 return true; 1730 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType())) 1731 return Error(ID.Loc, "extractvalue operand must be array or struct"); 1732 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(), 1733 Indices.end())) 1734 return Error(ID.Loc, "invalid indices for extractvalue"); 1735 ID.ConstantVal = ConstantExpr::getExtractValue(Val, 1736 &Indices[0], Indices.size()); 1737 ID.Kind = ValID::t_Constant; 1738 return false; 1739 } 1740 case lltok::kw_insertvalue: { 1741 Lex.Lex(); 1742 Constant *Val0, *Val1; 1743 SmallVector<unsigned, 4> Indices; 1744 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")|| 1745 ParseGlobalTypeAndValue(Val0) || 1746 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")|| 1747 ParseGlobalTypeAndValue(Val1) || 1748 ParseIndexList(Indices) || 1749 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 1750 return true; 1751 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType())) 1752 return Error(ID.Loc, "extractvalue operand must be array or struct"); 1753 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), 1754 Indices.end())) 1755 return Error(ID.Loc, "invalid indices for insertvalue"); 1756 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, 1757 &Indices[0], Indices.size()); 1758 ID.Kind = ValID::t_Constant; 1759 return false; 1760 } 1761 case lltok::kw_icmp: 1762 case lltok::kw_fcmp: 1763 case lltok::kw_vicmp: 1764 case lltok::kw_vfcmp: { 1765 unsigned PredVal, Opc = Lex.getUIntVal(); 1766 Constant *Val0, *Val1; 1767 Lex.Lex(); 1768 if (ParseCmpPredicate(PredVal, Opc) || 1769 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") || 1770 ParseGlobalTypeAndValue(Val0) || 1771 ParseToken(lltok::comma, "expected comma in compare constantexpr") || 1772 ParseGlobalTypeAndValue(Val1) || 1773 ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) 1774 return true; 1775 1776 if (Val0->getType() != Val1->getType()) 1777 return Error(ID.Loc, "compare operands must have the same type"); 1778 1779 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 1780 1781 if (Opc == Instruction::FCmp) { 1782 if (!Val0->getType()->isFPOrFPVector()) 1783 return Error(ID.Loc, "fcmp requires floating point operands"); 1784 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 1785 } else if (Opc == Instruction::ICmp) { 1786 if (!Val0->getType()->isIntOrIntVector() && 1787 !isa<PointerType>(Val0->getType())) 1788 return Error(ID.Loc, "icmp requires pointer or integer operands"); 1789 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 1790 } else if (Opc == Instruction::VFCmp) { 1791 // FIXME: REMOVE VFCMP Support 1792 if (!Val0->getType()->isFPOrFPVector() || 1793 !isa<VectorType>(Val0->getType())) 1794 return Error(ID.Loc, "vfcmp requires vector floating point operands"); 1795 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1); 1796 } else if (Opc == Instruction::VICmp) { 1797 // FIXME: REMOVE VICMP Support 1798 if (!Val0->getType()->isIntOrIntVector() || 1799 !isa<VectorType>(Val0->getType())) 1800 return Error(ID.Loc, "vicmp requires vector floating point operands"); 1801 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1); 1802 } 1803 ID.Kind = ValID::t_Constant; 1804 return false; 1805 } 1806 1807 // Binary Operators. 1808 case lltok::kw_add: 1809 case lltok::kw_sub: 1810 case lltok::kw_mul: 1811 case lltok::kw_udiv: 1812 case lltok::kw_sdiv: 1813 case lltok::kw_fdiv: 1814 case lltok::kw_urem: 1815 case lltok::kw_srem: 1816 case lltok::kw_frem: { 1817 unsigned Opc = Lex.getUIntVal(); 1818 Constant *Val0, *Val1; 1819 Lex.Lex(); 1820 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") || 1821 ParseGlobalTypeAndValue(Val0) || 1822 ParseToken(lltok::comma, "expected comma in binary constantexpr") || 1823 ParseGlobalTypeAndValue(Val1) || 1824 ParseToken(lltok::rparen, "expected ')' in binary constantexpr")) 1825 return true; 1826 if (Val0->getType() != Val1->getType()) 1827 return Error(ID.Loc, "operands of constexpr must have same type"); 1828 if (!Val0->getType()->isIntOrIntVector() && 1829 !Val0->getType()->isFPOrFPVector()) 1830 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands"); 1831 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 1832 ID.Kind = ValID::t_Constant; 1833 return false; 1834 } 1835 1836 // Logical Operations 1837 case lltok::kw_shl: 1838 case lltok::kw_lshr: 1839 case lltok::kw_ashr: 1840 case lltok::kw_and: 1841 case lltok::kw_or: 1842 case lltok::kw_xor: { 1843 unsigned Opc = Lex.getUIntVal(); 1844 Constant *Val0, *Val1; 1845 Lex.Lex(); 1846 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") || 1847 ParseGlobalTypeAndValue(Val0) || 1848 ParseToken(lltok::comma, "expected comma in logical constantexpr") || 1849 ParseGlobalTypeAndValue(Val1) || 1850 ParseToken(lltok::rparen, "expected ')' in logical constantexpr")) 1851 return true; 1852 if (Val0->getType() != Val1->getType()) 1853 return Error(ID.Loc, "operands of constexpr must have same type"); 1854 if (!Val0->getType()->isIntOrIntVector()) 1855 return Error(ID.Loc, 1856 "constexpr requires integer or integer vector operands"); 1857 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 1858 ID.Kind = ValID::t_Constant; 1859 return false; 1860 } 1861 1862 case lltok::kw_getelementptr: 1863 case lltok::kw_shufflevector: 1864 case lltok::kw_insertelement: 1865 case lltok::kw_extractelement: 1866 case lltok::kw_select: { 1867 unsigned Opc = Lex.getUIntVal(); 1868 SmallVector<Constant*, 16> Elts; 1869 Lex.Lex(); 1870 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") || 1871 ParseGlobalValueVector(Elts) || 1872 ParseToken(lltok::rparen, "expected ')' in constantexpr")) 1873 return true; 1874 1875 if (Opc == Instruction::GetElementPtr) { 1876 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType())) 1877 return Error(ID.Loc, "getelementptr requires pointer operand"); 1878 1879 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), 1880 (Value**)&Elts[1], Elts.size()-1)) 1881 return Error(ID.Loc, "invalid indices for getelementptr"); 1882 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], 1883 &Elts[1], Elts.size()-1); 1884 } else if (Opc == Instruction::Select) { 1885 if (Elts.size() != 3) 1886 return Error(ID.Loc, "expected three operands to select"); 1887 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 1888 Elts[2])) 1889 return Error(ID.Loc, Reason); 1890 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 1891 } else if (Opc == Instruction::ShuffleVector) { 1892 if (Elts.size() != 3) 1893 return Error(ID.Loc, "expected three operands to shufflevector"); 1894 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 1895 return Error(ID.Loc, "invalid operands to shufflevector"); 1896 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); 1897 } else if (Opc == Instruction::ExtractElement) { 1898 if (Elts.size() != 2) 1899 return Error(ID.Loc, "expected two operands to extractelement"); 1900 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 1901 return Error(ID.Loc, "invalid extractelement operands"); 1902 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 1903 } else { 1904 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 1905 if (Elts.size() != 3) 1906 return Error(ID.Loc, "expected three operands to insertelement"); 1907 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 1908 return Error(ID.Loc, "invalid insertelement operands"); 1909 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 1910 } 1911 1912 ID.Kind = ValID::t_Constant; 1913 return false; 1914 } 1915 } 1916 1917 Lex.Lex(); 1918 return false; 1919} 1920 1921/// ParseGlobalValue - Parse a global value with the specified type. 1922bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) { 1923 V = 0; 1924 ValID ID; 1925 return ParseValID(ID) || 1926 ConvertGlobalValIDToValue(Ty, ID, V); 1927} 1928 1929/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved 1930/// constant. 1931bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, 1932 Constant *&V) { 1933 if (isa<FunctionType>(Ty)) 1934 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 1935 1936 switch (ID.Kind) { 1937 default: assert(0 && "Unknown ValID!"); 1938 case ValID::t_LocalID: 1939 case ValID::t_LocalName: 1940 return Error(ID.Loc, "invalid use of function-local name"); 1941 case ValID::t_InlineAsm: 1942 return Error(ID.Loc, "inline asm can only be an operand of call/invoke"); 1943 case ValID::t_GlobalName: 1944 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc); 1945 return V == 0; 1946 case ValID::t_GlobalID: 1947 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc); 1948 return V == 0; 1949 case ValID::t_APSInt: 1950 if (!isa<IntegerType>(Ty)) 1951 return Error(ID.Loc, "integer constant must have integer type"); 1952 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 1953 V = ConstantInt::get(ID.APSIntVal); 1954 return false; 1955 case ValID::t_APFloat: 1956 if (!Ty->isFloatingPoint() || 1957 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 1958 return Error(ID.Loc, "floating point constant invalid for type"); 1959 1960 // The lexer has no type info, so builds all float and double FP constants 1961 // as double. Fix this here. Long double does not need this. 1962 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble && 1963 Ty == Type::FloatTy) { 1964 bool Ignored; 1965 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, 1966 &Ignored); 1967 } 1968 V = ConstantFP::get(ID.APFloatVal); 1969 1970 if (V->getType() != Ty) 1971 return Error(ID.Loc, "floating point constant does not have type '" + 1972 Ty->getDescription() + "'"); 1973 1974 return false; 1975 case ValID::t_Null: 1976 if (!isa<PointerType>(Ty)) 1977 return Error(ID.Loc, "null must be a pointer type"); 1978 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 1979 return false; 1980 case ValID::t_Undef: 1981 // FIXME: LabelTy should not be a first-class type. 1982 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) && 1983 !isa<OpaqueType>(Ty)) 1984 return Error(ID.Loc, "invalid type for undef constant"); 1985 V = UndefValue::get(Ty); 1986 return false; 1987 case ValID::t_EmptyArray: 1988 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0) 1989 return Error(ID.Loc, "invalid empty array initializer"); 1990 V = UndefValue::get(Ty); 1991 return false; 1992 case ValID::t_Zero: 1993 // FIXME: LabelTy should not be a first-class type. 1994 if (!Ty->isFirstClassType() || Ty == Type::LabelTy) 1995 return Error(ID.Loc, "invalid type for null constant"); 1996 V = Constant::getNullValue(Ty); 1997 return false; 1998 case ValID::t_Constant: 1999 if (ID.ConstantVal->getType() != Ty) 2000 return Error(ID.Loc, "constant expression type mismatch"); 2001 V = ID.ConstantVal; 2002 return false; 2003 } 2004} 2005 2006bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 2007 PATypeHolder Type(Type::VoidTy); 2008 return ParseType(Type) || 2009 ParseGlobalValue(Type, V); 2010} 2011 2012/// ParseGlobalValueVector 2013/// ::= /*empty*/ 2014/// ::= TypeAndValue (',' TypeAndValue)* 2015bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) { 2016 // Empty list. 2017 if (Lex.getKind() == lltok::rbrace || 2018 Lex.getKind() == lltok::rsquare || 2019 Lex.getKind() == lltok::greater || 2020 Lex.getKind() == lltok::rparen) 2021 return false; 2022 2023 Constant *C; 2024 if (ParseGlobalTypeAndValue(C)) return true; 2025 Elts.push_back(C); 2026 2027 while (EatIfPresent(lltok::comma)) { 2028 if (ParseGlobalTypeAndValue(C)) return true; 2029 Elts.push_back(C); 2030 } 2031 2032 return false; 2033} 2034 2035 2036//===----------------------------------------------------------------------===// 2037// Function Parsing. 2038//===----------------------------------------------------------------------===// 2039 2040bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V, 2041 PerFunctionState &PFS) { 2042 if (ID.Kind == ValID::t_LocalID) 2043 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); 2044 else if (ID.Kind == ValID::t_LocalName) 2045 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); 2046 else if (ID.Kind == ValID::t_InlineAsm) { 2047 const PointerType *PTy = dyn_cast<PointerType>(Ty); 2048 const FunctionType *FTy = 2049 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0; 2050 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) 2051 return Error(ID.Loc, "invalid type for inline asm constraint string"); 2052 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal); 2053 return false; 2054 } else { 2055 Constant *C; 2056 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true; 2057 V = C; 2058 return false; 2059 } 2060 2061 return V == 0; 2062} 2063 2064bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) { 2065 V = 0; 2066 ValID ID; 2067 return ParseValID(ID) || 2068 ConvertValIDToValue(Ty, ID, V, PFS); 2069} 2070 2071bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) { 2072 PATypeHolder T(Type::VoidTy); 2073 return ParseType(T) || 2074 ParseValue(T, V, PFS); 2075} 2076 2077/// FunctionHeader 2078/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs 2079/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection 2080/// OptionalAlign OptGC 2081bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 2082 // Parse the linkage. 2083 LocTy LinkageLoc = Lex.getLoc(); 2084 unsigned Linkage; 2085 2086 unsigned Visibility, CC, RetAttrs; 2087 PATypeHolder RetType(Type::VoidTy); 2088 LocTy RetTypeLoc = Lex.getLoc(); 2089 if (ParseOptionalLinkage(Linkage) || 2090 ParseOptionalVisibility(Visibility) || 2091 ParseOptionalCallingConv(CC) || 2092 ParseOptionalAttrs(RetAttrs, 1) || 2093 ParseType(RetType, RetTypeLoc, true /*void allowed*/)) 2094 return true; 2095 2096 // Verify that the linkage is ok. 2097 switch ((GlobalValue::LinkageTypes)Linkage) { 2098 case GlobalValue::ExternalLinkage: 2099 break; // always ok. 2100 case GlobalValue::DLLImportLinkage: 2101 case GlobalValue::ExternalWeakLinkage: 2102 if (isDefine) 2103 return Error(LinkageLoc, "invalid linkage for function definition"); 2104 break; 2105 case GlobalValue::PrivateLinkage: 2106 case GlobalValue::InternalLinkage: 2107 case GlobalValue::LinkOnceAnyLinkage: 2108 case GlobalValue::LinkOnceODRLinkage: 2109 case GlobalValue::WeakAnyLinkage: 2110 case GlobalValue::WeakODRLinkage: 2111 case GlobalValue::DLLExportLinkage: 2112 if (!isDefine) 2113 return Error(LinkageLoc, "invalid linkage for function declaration"); 2114 break; 2115 case GlobalValue::AppendingLinkage: 2116 case GlobalValue::GhostLinkage: 2117 case GlobalValue::CommonAnyLinkage: 2118 case GlobalValue::CommonODRLinkage: 2119 return Error(LinkageLoc, "invalid function linkage type"); 2120 } 2121 2122 if (!FunctionType::isValidReturnType(RetType) || 2123 isa<OpaqueType>(RetType)) 2124 return Error(RetTypeLoc, "invalid function return type"); 2125 2126 LocTy NameLoc = Lex.getLoc(); 2127 2128 std::string FunctionName; 2129 if (Lex.getKind() == lltok::GlobalVar) { 2130 FunctionName = Lex.getStrVal(); 2131 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 2132 unsigned NameID = Lex.getUIntVal(); 2133 2134 if (NameID != NumberedVals.size()) 2135 return TokError("function expected to be numbered '%" + 2136 utostr(NumberedVals.size()) + "'"); 2137 } else { 2138 return TokError("expected function name"); 2139 } 2140 2141 Lex.Lex(); 2142 2143 if (Lex.getKind() != lltok::lparen) 2144 return TokError("expected '(' in function argument list"); 2145 2146 std::vector<ArgInfo> ArgList; 2147 bool isVarArg; 2148 unsigned FuncAttrs; 2149 std::string Section; 2150 unsigned Alignment; 2151 std::string GC; 2152 2153 if (ParseArgumentList(ArgList, isVarArg, false) || 2154 ParseOptionalAttrs(FuncAttrs, 2) || 2155 (EatIfPresent(lltok::kw_section) && 2156 ParseStringConstant(Section)) || 2157 ParseOptionalAlignment(Alignment) || 2158 (EatIfPresent(lltok::kw_gc) && 2159 ParseStringConstant(GC))) 2160 return true; 2161 2162 // If the alignment was parsed as an attribute, move to the alignment field. 2163 if (FuncAttrs & Attribute::Alignment) { 2164 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs); 2165 FuncAttrs &= ~Attribute::Alignment; 2166 } 2167 2168 // Okay, if we got here, the function is syntactically valid. Convert types 2169 // and do semantic checks. 2170 std::vector<const Type*> ParamTypeList; 2171 SmallVector<AttributeWithIndex, 8> Attrs; 2172 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 2173 // attributes. 2174 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; 2175 if (FuncAttrs & ObsoleteFuncAttrs) { 2176 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs; 2177 FuncAttrs &= ~ObsoleteFuncAttrs; 2178 } 2179 2180 if (RetAttrs != Attribute::None) 2181 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 2182 2183 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2184 ParamTypeList.push_back(ArgList[i].Type); 2185 if (ArgList[i].Attrs != Attribute::None) 2186 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 2187 } 2188 2189 if (FuncAttrs != Attribute::None) 2190 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs)); 2191 2192 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); 2193 2194 if (PAL.paramHasAttr(1, Attribute::StructRet) && 2195 RetType != Type::VoidTy) 2196 return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 2197 2198 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg); 2199 const PointerType *PFT = PointerType::getUnqual(FT); 2200 2201 Fn = 0; 2202 if (!FunctionName.empty()) { 2203 // If this was a definition of a forward reference, remove the definition 2204 // from the forward reference table and fill in the forward ref. 2205 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI = 2206 ForwardRefVals.find(FunctionName); 2207 if (FRVI != ForwardRefVals.end()) { 2208 Fn = M->getFunction(FunctionName); 2209 ForwardRefVals.erase(FRVI); 2210 } else if ((Fn = M->getFunction(FunctionName))) { 2211 // If this function already exists in the symbol table, then it is 2212 // multiply defined. We accept a few cases for old backwards compat. 2213 // FIXME: Remove this stuff for LLVM 3.0. 2214 if (Fn->getType() != PFT || Fn->getAttributes() != PAL || 2215 (!Fn->isDeclaration() && isDefine)) { 2216 // If the redefinition has different type or different attributes, 2217 // reject it. If both have bodies, reject it. 2218 return Error(NameLoc, "invalid redefinition of function '" + 2219 FunctionName + "'"); 2220 } else if (Fn->isDeclaration()) { 2221 // Make sure to strip off any argument names so we can't get conflicts. 2222 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end(); 2223 AI != AE; ++AI) 2224 AI->setName(""); 2225 } 2226 } 2227 2228 } else if (FunctionName.empty()) { 2229 // If this is a definition of a forward referenced function, make sure the 2230 // types agree. 2231 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I 2232 = ForwardRefValIDs.find(NumberedVals.size()); 2233 if (I != ForwardRefValIDs.end()) { 2234 Fn = cast<Function>(I->second.first); 2235 if (Fn->getType() != PFT) 2236 return Error(NameLoc, "type of definition and forward reference of '@" + 2237 utostr(NumberedVals.size()) +"' disagree"); 2238 ForwardRefValIDs.erase(I); 2239 } 2240 } 2241 2242 if (Fn == 0) 2243 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M); 2244 else // Move the forward-reference to the correct spot in the module. 2245 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 2246 2247 if (FunctionName.empty()) 2248 NumberedVals.push_back(Fn); 2249 2250 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 2251 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 2252 Fn->setCallingConv(CC); 2253 Fn->setAttributes(PAL); 2254 Fn->setAlignment(Alignment); 2255 Fn->setSection(Section); 2256 if (!GC.empty()) Fn->setGC(GC.c_str()); 2257 2258 // Add all of the arguments we parsed to the function. 2259 Function::arg_iterator ArgIt = Fn->arg_begin(); 2260 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 2261 // If the argument has a name, insert it into the argument symbol table. 2262 if (ArgList[i].Name.empty()) continue; 2263 2264 // Set the name, if it conflicted, it will be auto-renamed. 2265 ArgIt->setName(ArgList[i].Name); 2266 2267 if (ArgIt->getNameStr() != ArgList[i].Name) 2268 return Error(ArgList[i].Loc, "redefinition of argument '%" + 2269 ArgList[i].Name + "'"); 2270 } 2271 2272 return false; 2273} 2274 2275 2276/// ParseFunctionBody 2277/// ::= '{' BasicBlock+ '}' 2278/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0 2279/// 2280bool LLParser::ParseFunctionBody(Function &Fn) { 2281 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin) 2282 return TokError("expected '{' in function body"); 2283 Lex.Lex(); // eat the {. 2284 2285 PerFunctionState PFS(*this, Fn); 2286 2287 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end) 2288 if (ParseBasicBlock(PFS)) return true; 2289 2290 // Eat the }. 2291 Lex.Lex(); 2292 2293 // Verify function is ok. 2294 return PFS.VerifyFunctionComplete(); 2295} 2296 2297/// ParseBasicBlock 2298/// ::= LabelStr? Instruction* 2299bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { 2300 // If this basic block starts out with a name, remember it. 2301 std::string Name; 2302 LocTy NameLoc = Lex.getLoc(); 2303 if (Lex.getKind() == lltok::LabelStr) { 2304 Name = Lex.getStrVal(); 2305 Lex.Lex(); 2306 } 2307 2308 BasicBlock *BB = PFS.DefineBB(Name, NameLoc); 2309 if (BB == 0) return true; 2310 2311 std::string NameStr; 2312 2313 // Parse the instructions in this block until we get a terminator. 2314 Instruction *Inst; 2315 do { 2316 // This instruction may have three possibilities for a name: a) none 2317 // specified, b) name specified "%foo =", c) number specified: "%4 =". 2318 LocTy NameLoc = Lex.getLoc(); 2319 int NameID = -1; 2320 NameStr = ""; 2321 2322 if (Lex.getKind() == lltok::LocalVarID) { 2323 NameID = Lex.getUIntVal(); 2324 Lex.Lex(); 2325 if (ParseToken(lltok::equal, "expected '=' after instruction id")) 2326 return true; 2327 } else if (Lex.getKind() == lltok::LocalVar || 2328 // FIXME: REMOVE IN LLVM 3.0 2329 Lex.getKind() == lltok::StringConstant) { 2330 NameStr = Lex.getStrVal(); 2331 Lex.Lex(); 2332 if (ParseToken(lltok::equal, "expected '=' after instruction name")) 2333 return true; 2334 } 2335 2336 if (ParseInstruction(Inst, BB, PFS)) return true; 2337 2338 BB->getInstList().push_back(Inst); 2339 2340 // Set the name on the instruction. 2341 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; 2342 } while (!isa<TerminatorInst>(Inst)); 2343 2344 return false; 2345} 2346 2347//===----------------------------------------------------------------------===// 2348// Instruction Parsing. 2349//===----------------------------------------------------------------------===// 2350 2351/// ParseInstruction - Parse one of the many different instructions. 2352/// 2353bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, 2354 PerFunctionState &PFS) { 2355 lltok::Kind Token = Lex.getKind(); 2356 if (Token == lltok::Eof) 2357 return TokError("found end of file when expecting more instructions"); 2358 LocTy Loc = Lex.getLoc(); 2359 unsigned KeywordVal = Lex.getUIntVal(); 2360 Lex.Lex(); // Eat the keyword. 2361 2362 switch (Token) { 2363 default: return Error(Loc, "expected instruction opcode"); 2364 // Terminator Instructions. 2365 case lltok::kw_unwind: Inst = new UnwindInst(); return false; 2366 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false; 2367 case lltok::kw_ret: return ParseRet(Inst, BB, PFS); 2368 case lltok::kw_br: return ParseBr(Inst, PFS); 2369 case lltok::kw_switch: return ParseSwitch(Inst, PFS); 2370 case lltok::kw_invoke: return ParseInvoke(Inst, PFS); 2371 // Binary Operators. 2372 case lltok::kw_add: 2373 case lltok::kw_sub: 2374 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0); 2375 2376 case lltok::kw_udiv: 2377 case lltok::kw_sdiv: 2378 case lltok::kw_urem: 2379 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1); 2380 case lltok::kw_fdiv: 2381 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2); 2382 case lltok::kw_shl: 2383 case lltok::kw_lshr: 2384 case lltok::kw_ashr: 2385 case lltok::kw_and: 2386 case lltok::kw_or: 2387 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal); 2388 case lltok::kw_icmp: 2389 case lltok::kw_fcmp: 2390 case lltok::kw_vicmp: 2391 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal); 2392 // Casts. 2393 case lltok::kw_trunc: 2394 case lltok::kw_zext: 2395 case lltok::kw_sext: 2396 case lltok::kw_fptrunc: 2397 case lltok::kw_fpext: 2398 case lltok::kw_bitcast: 2399 case lltok::kw_uitofp: 2400 case lltok::kw_sitofp: 2401 case lltok::kw_fptoui: 2402 case lltok::kw_fptosi: 2403 case lltok::kw_inttoptr: 2404 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); 2405 // Other. 2406 case lltok::kw_select: return ParseSelect(Inst, PFS); 2407 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS); 2408 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS); 2409 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS); 2410 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS); 2411 case lltok::kw_phi: return ParsePHI(Inst, PFS); 2412 case lltok::kw_call: return ParseCall(Inst, PFS, false); 2413 case lltok::kw_tail: return ParseCall(Inst, PFS, true); 2414 // Memory. 2415 case lltok::kw_alloca: 2416 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal); 2417 case lltok::kw_free: return ParseFree(Inst, PFS); 2418 case lltok::kw_load: return ParseLoad(Inst, PFS, false); 2419 case lltok::kw_store: return ParseStore(Inst, PFS, false); 2420 case lltok::kw_volatile: 2421 if (EatIfPresent(lltok::kw_load)) 2422 return ParseLoad(Inst, PFS, true); 2423 else if (EatIfPresent(lltok::kw_store)) 2424 return ParseStore(Inst, PFS, true); 2425 else 2426 return TokError("expected 'load' or 'store'"); 2427 case lltok::kw_getresult: return ParseGetResult(Inst, PFS); 2428 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS); 2429 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS); 2430 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS); 2431 } 2432} 2433 2434/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. 2435bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { 2436 // FIXME: REMOVE vicmp/vfcmp! 2437 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) { 2438 switch (Lex.getKind()) { 2439 default: TokError("expected fcmp predicate (e.g. 'oeq')"); 2440 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 2441 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 2442 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 2443 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 2444 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 2445 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 2446 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 2447 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 2448 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 2449 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 2450 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 2451 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 2452 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 2453 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 2454 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 2455 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 2456 } 2457 } else { 2458 switch (Lex.getKind()) { 2459 default: TokError("expected icmp predicate (e.g. 'eq')"); 2460 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 2461 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 2462 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 2463 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 2464 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 2465 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 2466 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 2467 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 2468 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 2469 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 2470 } 2471 } 2472 Lex.Lex(); 2473 return false; 2474} 2475 2476//===----------------------------------------------------------------------===// 2477// Terminator Instructions. 2478//===----------------------------------------------------------------------===// 2479 2480/// ParseRet - Parse a return instruction. 2481/// ::= 'ret' void 2482/// ::= 'ret' TypeAndValue 2483/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]] 2484bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, 2485 PerFunctionState &PFS) { 2486 PATypeHolder Ty(Type::VoidTy); 2487 if (ParseType(Ty, true /*void allowed*/)) return true; 2488 2489 if (Ty == Type::VoidTy) { 2490 Inst = ReturnInst::Create(); 2491 return false; 2492 } 2493 2494 Value *RV; 2495 if (ParseValue(Ty, RV, PFS)) return true; 2496 2497 // The normal case is one return value. 2498 if (Lex.getKind() == lltok::comma) { 2499 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use 2500 // of 'ret {i32,i32} {i32 1, i32 2}' 2501 SmallVector<Value*, 8> RVs; 2502 RVs.push_back(RV); 2503 2504 while (EatIfPresent(lltok::comma)) { 2505 if (ParseTypeAndValue(RV, PFS)) return true; 2506 RVs.push_back(RV); 2507 } 2508 2509 RV = UndefValue::get(PFS.getFunction().getReturnType()); 2510 for (unsigned i = 0, e = RVs.size(); i != e; ++i) { 2511 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv"); 2512 BB->getInstList().push_back(I); 2513 RV = I; 2514 } 2515 } 2516 Inst = ReturnInst::Create(RV); 2517 return false; 2518} 2519 2520 2521/// ParseBr 2522/// ::= 'br' TypeAndValue 2523/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 2524bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { 2525 LocTy Loc, Loc2; 2526 Value *Op0, *Op1, *Op2; 2527 if (ParseTypeAndValue(Op0, Loc, PFS)) return true; 2528 2529 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 2530 Inst = BranchInst::Create(BB); 2531 return false; 2532 } 2533 2534 if (Op0->getType() != Type::Int1Ty) 2535 return Error(Loc, "branch condition must have 'i1' type"); 2536 2537 if (ParseToken(lltok::comma, "expected ',' after branch condition") || 2538 ParseTypeAndValue(Op1, Loc, PFS) || 2539 ParseToken(lltok::comma, "expected ',' after true destination") || 2540 ParseTypeAndValue(Op2, Loc2, PFS)) 2541 return true; 2542 2543 if (!isa<BasicBlock>(Op1)) 2544 return Error(Loc, "true destination of branch must be a basic block"); 2545 if (!isa<BasicBlock>(Op2)) 2546 return Error(Loc2, "true destination of branch must be a basic block"); 2547 2548 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0); 2549 return false; 2550} 2551 2552/// ParseSwitch 2553/// Instruction 2554/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 2555/// JumpTable 2556/// ::= (TypeAndValue ',' TypeAndValue)* 2557bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 2558 LocTy CondLoc, BBLoc; 2559 Value *Cond, *DefaultBB; 2560 if (ParseTypeAndValue(Cond, CondLoc, PFS) || 2561 ParseToken(lltok::comma, "expected ',' after switch condition") || 2562 ParseTypeAndValue(DefaultBB, BBLoc, PFS) || 2563 ParseToken(lltok::lsquare, "expected '[' with switch table")) 2564 return true; 2565 2566 if (!isa<IntegerType>(Cond->getType())) 2567 return Error(CondLoc, "switch condition must have integer type"); 2568 if (!isa<BasicBlock>(DefaultBB)) 2569 return Error(BBLoc, "default destination must be a basic block"); 2570 2571 // Parse the jump table pairs. 2572 SmallPtrSet<Value*, 32> SeenCases; 2573 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 2574 while (Lex.getKind() != lltok::rsquare) { 2575 Value *Constant, *DestBB; 2576 2577 if (ParseTypeAndValue(Constant, CondLoc, PFS) || 2578 ParseToken(lltok::comma, "expected ',' after case value") || 2579 ParseTypeAndValue(DestBB, BBLoc, PFS)) 2580 return true; 2581 2582 if (!SeenCases.insert(Constant)) 2583 return Error(CondLoc, "duplicate case value in switch"); 2584 if (!isa<ConstantInt>(Constant)) 2585 return Error(CondLoc, "case value is not a constant integer"); 2586 if (!isa<BasicBlock>(DestBB)) 2587 return Error(BBLoc, "case destination is not a basic block"); 2588 2589 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), 2590 cast<BasicBlock>(DestBB))); 2591 } 2592 2593 Lex.Lex(); // Eat the ']'. 2594 2595 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB), 2596 Table.size()); 2597 for (unsigned i = 0, e = Table.size(); i != e; ++i) 2598 SI->addCase(Table[i].first, Table[i].second); 2599 Inst = SI; 2600 return false; 2601} 2602 2603/// ParseInvoke 2604/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 2605/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 2606bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 2607 LocTy CallLoc = Lex.getLoc(); 2608 unsigned CC, RetAttrs, FnAttrs; 2609 PATypeHolder RetType(Type::VoidTy); 2610 LocTy RetTypeLoc; 2611 ValID CalleeID; 2612 SmallVector<ParamInfo, 16> ArgList; 2613 2614 Value *NormalBB, *UnwindBB; 2615 if (ParseOptionalCallingConv(CC) || 2616 ParseOptionalAttrs(RetAttrs, 1) || 2617 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 2618 ParseValID(CalleeID) || 2619 ParseParameterList(ArgList, PFS) || 2620 ParseOptionalAttrs(FnAttrs, 2) || 2621 ParseToken(lltok::kw_to, "expected 'to' in invoke") || 2622 ParseTypeAndValue(NormalBB, PFS) || 2623 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 2624 ParseTypeAndValue(UnwindBB, PFS)) 2625 return true; 2626 2627 if (!isa<BasicBlock>(NormalBB)) 2628 return Error(CallLoc, "normal destination is not a basic block"); 2629 if (!isa<BasicBlock>(UnwindBB)) 2630 return Error(CallLoc, "unwind destination is not a basic block"); 2631 2632 // If RetType is a non-function pointer type, then this is the short syntax 2633 // for the call, which means that RetType is just the return type. Infer the 2634 // rest of the function argument types from the arguments that are present. 2635 const PointerType *PFTy = 0; 2636 const FunctionType *Ty = 0; 2637 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 2638 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 2639 // Pull out the types of all of the arguments... 2640 std::vector<const Type*> ParamTypes; 2641 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 2642 ParamTypes.push_back(ArgList[i].V->getType()); 2643 2644 if (!FunctionType::isValidReturnType(RetType)) 2645 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 2646 2647 Ty = FunctionType::get(RetType, ParamTypes, false); 2648 PFTy = PointerType::getUnqual(Ty); 2649 } 2650 2651 // Look up the callee. 2652 Value *Callee; 2653 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; 2654 2655 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional 2656 // function attributes. 2657 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; 2658 if (FnAttrs & ObsoleteFuncAttrs) { 2659 RetAttrs |= FnAttrs & ObsoleteFuncAttrs; 2660 FnAttrs &= ~ObsoleteFuncAttrs; 2661 } 2662 2663 // Set up the Attributes for the function. 2664 SmallVector<AttributeWithIndex, 8> Attrs; 2665 if (RetAttrs != Attribute::None) 2666 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 2667 2668 SmallVector<Value*, 8> Args; 2669 2670 // Loop through FunctionType's arguments and ensure they are specified 2671 // correctly. Also, gather any parameter attributes. 2672 FunctionType::param_iterator I = Ty->param_begin(); 2673 FunctionType::param_iterator E = Ty->param_end(); 2674 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2675 const Type *ExpectedTy = 0; 2676 if (I != E) { 2677 ExpectedTy = *I++; 2678 } else if (!Ty->isVarArg()) { 2679 return Error(ArgList[i].Loc, "too many arguments specified"); 2680 } 2681 2682 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 2683 return Error(ArgList[i].Loc, "argument is not of expected type '" + 2684 ExpectedTy->getDescription() + "'"); 2685 Args.push_back(ArgList[i].V); 2686 if (ArgList[i].Attrs != Attribute::None) 2687 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 2688 } 2689 2690 if (I != E) 2691 return Error(CallLoc, "not enough parameters specified for call"); 2692 2693 if (FnAttrs != Attribute::None) 2694 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); 2695 2696 // Finish off the Attributes and check them 2697 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); 2698 2699 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB), 2700 cast<BasicBlock>(UnwindBB), 2701 Args.begin(), Args.end()); 2702 II->setCallingConv(CC); 2703 II->setAttributes(PAL); 2704 Inst = II; 2705 return false; 2706} 2707 2708 2709 2710//===----------------------------------------------------------------------===// 2711// Binary Operators. 2712//===----------------------------------------------------------------------===// 2713 2714/// ParseArithmetic 2715/// ::= ArithmeticOps TypeAndValue ',' Value 2716/// 2717/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1, 2718/// then any integer operand is allowed, if it is 2, any fp operand is allowed. 2719bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 2720 unsigned Opc, unsigned OperandType) { 2721 LocTy Loc; Value *LHS, *RHS; 2722 if (ParseTypeAndValue(LHS, Loc, PFS) || 2723 ParseToken(lltok::comma, "expected ',' in arithmetic operation") || 2724 ParseValue(LHS->getType(), RHS, PFS)) 2725 return true; 2726 2727 bool Valid; 2728 switch (OperandType) { 2729 default: assert(0 && "Unknown operand type!"); 2730 case 0: // int or FP. 2731 Valid = LHS->getType()->isIntOrIntVector() || 2732 LHS->getType()->isFPOrFPVector(); 2733 break; 2734 case 1: Valid = LHS->getType()->isIntOrIntVector(); break; 2735 case 2: Valid = LHS->getType()->isFPOrFPVector(); break; 2736 } 2737 2738 if (!Valid) 2739 return Error(Loc, "invalid operand type for instruction"); 2740 2741 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2742 return false; 2743} 2744 2745/// ParseLogical 2746/// ::= ArithmeticOps TypeAndValue ',' Value { 2747bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, 2748 unsigned Opc) { 2749 LocTy Loc; Value *LHS, *RHS; 2750 if (ParseTypeAndValue(LHS, Loc, PFS) || 2751 ParseToken(lltok::comma, "expected ',' in logical operation") || 2752 ParseValue(LHS->getType(), RHS, PFS)) 2753 return true; 2754 2755 if (!LHS->getType()->isIntOrIntVector()) 2756 return Error(Loc,"instruction requires integer or integer vector operands"); 2757 2758 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2759 return false; 2760} 2761 2762 2763/// ParseCompare 2764/// ::= 'icmp' IPredicates TypeAndValue ',' Value 2765/// ::= 'fcmp' FPredicates TypeAndValue ',' Value 2766/// ::= 'vicmp' IPredicates TypeAndValue ',' Value 2767/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value 2768bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, 2769 unsigned Opc) { 2770 // Parse the integer/fp comparison predicate. 2771 LocTy Loc; 2772 unsigned Pred; 2773 Value *LHS, *RHS; 2774 if (ParseCmpPredicate(Pred, Opc) || 2775 ParseTypeAndValue(LHS, Loc, PFS) || 2776 ParseToken(lltok::comma, "expected ',' after compare value") || 2777 ParseValue(LHS->getType(), RHS, PFS)) 2778 return true; 2779 2780 if (Opc == Instruction::FCmp) { 2781 if (!LHS->getType()->isFPOrFPVector()) 2782 return Error(Loc, "fcmp requires floating point operands"); 2783 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 2784 } else if (Opc == Instruction::ICmp) { 2785 if (!LHS->getType()->isIntOrIntVector() && 2786 !isa<PointerType>(LHS->getType())) 2787 return Error(Loc, "icmp requires integer operands"); 2788 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 2789 } else if (Opc == Instruction::VFCmp) { 2790 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType())) 2791 return Error(Loc, "vfcmp requires vector floating point operands"); 2792 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 2793 } else if (Opc == Instruction::VICmp) { 2794 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType())) 2795 return Error(Loc, "vicmp requires vector floating point operands"); 2796 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 2797 } 2798 return false; 2799} 2800 2801//===----------------------------------------------------------------------===// 2802// Other Instructions. 2803//===----------------------------------------------------------------------===// 2804 2805 2806/// ParseCast 2807/// ::= CastOpc TypeAndValue 'to' Type 2808bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, 2809 unsigned Opc) { 2810 LocTy Loc; Value *Op; 2811 PATypeHolder DestTy(Type::VoidTy); 2812 if (ParseTypeAndValue(Op, Loc, PFS) || 2813 ParseToken(lltok::kw_to, "expected 'to' after cast value") || 2814 ParseType(DestTy)) 2815 return true; 2816 2817 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 2818 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 2819 return Error(Loc, "invalid cast opcode for cast from '" + 2820 Op->getType()->getDescription() + "' to '" + 2821 DestTy->getDescription() + "'"); 2822 } 2823 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 2824 return false; 2825} 2826 2827/// ParseSelect 2828/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 2829bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { 2830 LocTy Loc; 2831 Value *Op0, *Op1, *Op2; 2832 if (ParseTypeAndValue(Op0, Loc, PFS) || 2833 ParseToken(lltok::comma, "expected ',' after select condition") || 2834 ParseTypeAndValue(Op1, PFS) || 2835 ParseToken(lltok::comma, "expected ',' after select value") || 2836 ParseTypeAndValue(Op2, PFS)) 2837 return true; 2838 2839 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 2840 return Error(Loc, Reason); 2841 2842 Inst = SelectInst::Create(Op0, Op1, Op2); 2843 return false; 2844} 2845 2846/// ParseVA_Arg 2847/// ::= 'va_arg' TypeAndValue ',' Type 2848bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { 2849 Value *Op; 2850 PATypeHolder EltTy(Type::VoidTy); 2851 LocTy TypeLoc; 2852 if (ParseTypeAndValue(Op, PFS) || 2853 ParseToken(lltok::comma, "expected ',' after vaarg operand") || 2854 ParseType(EltTy, TypeLoc)) 2855 return true; 2856 2857 if (!EltTy->isFirstClassType()) 2858 return Error(TypeLoc, "va_arg requires operand with first class type"); 2859 2860 Inst = new VAArgInst(Op, EltTy); 2861 return false; 2862} 2863 2864/// ParseExtractElement 2865/// ::= 'extractelement' TypeAndValue ',' TypeAndValue 2866bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 2867 LocTy Loc; 2868 Value *Op0, *Op1; 2869 if (ParseTypeAndValue(Op0, Loc, PFS) || 2870 ParseToken(lltok::comma, "expected ',' after extract value") || 2871 ParseTypeAndValue(Op1, PFS)) 2872 return true; 2873 2874 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 2875 return Error(Loc, "invalid extractelement operands"); 2876 2877 Inst = new ExtractElementInst(Op0, Op1); 2878 return false; 2879} 2880 2881/// ParseInsertElement 2882/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 2883bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 2884 LocTy Loc; 2885 Value *Op0, *Op1, *Op2; 2886 if (ParseTypeAndValue(Op0, Loc, PFS) || 2887 ParseToken(lltok::comma, "expected ',' after insertelement value") || 2888 ParseTypeAndValue(Op1, PFS) || 2889 ParseToken(lltok::comma, "expected ',' after insertelement value") || 2890 ParseTypeAndValue(Op2, PFS)) 2891 return true; 2892 2893 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 2894 return Error(Loc, "invalid extractelement operands"); 2895 2896 Inst = InsertElementInst::Create(Op0, Op1, Op2); 2897 return false; 2898} 2899 2900/// ParseShuffleVector 2901/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 2902bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 2903 LocTy Loc; 2904 Value *Op0, *Op1, *Op2; 2905 if (ParseTypeAndValue(Op0, Loc, PFS) || 2906 ParseToken(lltok::comma, "expected ',' after shuffle mask") || 2907 ParseTypeAndValue(Op1, PFS) || 2908 ParseToken(lltok::comma, "expected ',' after shuffle value") || 2909 ParseTypeAndValue(Op2, PFS)) 2910 return true; 2911 2912 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 2913 return Error(Loc, "invalid extractelement operands"); 2914 2915 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 2916 return false; 2917} 2918 2919/// ParsePHI 2920/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')* 2921bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { 2922 PATypeHolder Ty(Type::VoidTy); 2923 Value *Op0, *Op1; 2924 LocTy TypeLoc = Lex.getLoc(); 2925 2926 if (ParseType(Ty) || 2927 ParseToken(lltok::lsquare, "expected '[' in phi value list") || 2928 ParseValue(Ty, Op0, PFS) || 2929 ParseToken(lltok::comma, "expected ',' after insertelement value") || 2930 ParseValue(Type::LabelTy, Op1, PFS) || 2931 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 2932 return true; 2933 2934 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 2935 while (1) { 2936 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 2937 2938 if (!EatIfPresent(lltok::comma)) 2939 break; 2940 2941 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || 2942 ParseValue(Ty, Op0, PFS) || 2943 ParseToken(lltok::comma, "expected ',' after insertelement value") || 2944 ParseValue(Type::LabelTy, Op1, PFS) || 2945 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 2946 return true; 2947 } 2948 2949 if (!Ty->isFirstClassType()) 2950 return Error(TypeLoc, "phi node must have first class type"); 2951 2952 PHINode *PN = PHINode::Create(Ty); 2953 PN->reserveOperandSpace(PHIVals.size()); 2954 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 2955 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 2956 Inst = PN; 2957 return false; 2958} 2959 2960/// ParseCall 2961/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value 2962/// ParameterList OptionalAttrs 2963bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, 2964 bool isTail) { 2965 unsigned CC, RetAttrs, FnAttrs; 2966 PATypeHolder RetType(Type::VoidTy); 2967 LocTy RetTypeLoc; 2968 ValID CalleeID; 2969 SmallVector<ParamInfo, 16> ArgList; 2970 LocTy CallLoc = Lex.getLoc(); 2971 2972 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) || 2973 ParseOptionalCallingConv(CC) || 2974 ParseOptionalAttrs(RetAttrs, 1) || 2975 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 2976 ParseValID(CalleeID) || 2977 ParseParameterList(ArgList, PFS) || 2978 ParseOptionalAttrs(FnAttrs, 2)) 2979 return true; 2980 2981 // If RetType is a non-function pointer type, then this is the short syntax 2982 // for the call, which means that RetType is just the return type. Infer the 2983 // rest of the function argument types from the arguments that are present. 2984 const PointerType *PFTy = 0; 2985 const FunctionType *Ty = 0; 2986 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 2987 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 2988 // Pull out the types of all of the arguments... 2989 std::vector<const Type*> ParamTypes; 2990 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 2991 ParamTypes.push_back(ArgList[i].V->getType()); 2992 2993 if (!FunctionType::isValidReturnType(RetType)) 2994 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 2995 2996 Ty = FunctionType::get(RetType, ParamTypes, false); 2997 PFTy = PointerType::getUnqual(Ty); 2998 } 2999 3000 // Look up the callee. 3001 Value *Callee; 3002 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; 3003 3004 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional 3005 // function attributes. 3006 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; 3007 if (FnAttrs & ObsoleteFuncAttrs) { 3008 RetAttrs |= FnAttrs & ObsoleteFuncAttrs; 3009 FnAttrs &= ~ObsoleteFuncAttrs; 3010 } 3011 3012 // Set up the Attributes for the function. 3013 SmallVector<AttributeWithIndex, 8> Attrs; 3014 if (RetAttrs != Attribute::None) 3015 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 3016 3017 SmallVector<Value*, 8> Args; 3018 3019 // Loop through FunctionType's arguments and ensure they are specified 3020 // correctly. Also, gather any parameter attributes. 3021 FunctionType::param_iterator I = Ty->param_begin(); 3022 FunctionType::param_iterator E = Ty->param_end(); 3023 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 3024 const Type *ExpectedTy = 0; 3025 if (I != E) { 3026 ExpectedTy = *I++; 3027 } else if (!Ty->isVarArg()) { 3028 return Error(ArgList[i].Loc, "too many arguments specified"); 3029 } 3030 3031 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 3032 return Error(ArgList[i].Loc, "argument is not of expected type '" + 3033 ExpectedTy->getDescription() + "'"); 3034 Args.push_back(ArgList[i].V); 3035 if (ArgList[i].Attrs != Attribute::None) 3036 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 3037 } 3038 3039 if (I != E) 3040 return Error(CallLoc, "not enough parameters specified for call"); 3041 3042 if (FnAttrs != Attribute::None) 3043 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); 3044 3045 // Finish off the Attributes and check them 3046 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); 3047 3048 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end()); 3049 CI->setTailCall(isTail); 3050 CI->setCallingConv(CC); 3051 CI->setAttributes(PAL); 3052 Inst = CI; 3053 return false; 3054} 3055 3056//===----------------------------------------------------------------------===// 3057// Memory Instructions. 3058//===----------------------------------------------------------------------===// 3059 3060/// ParseAlloc 3061/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)? 3062/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)? 3063bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS, 3064 unsigned Opc) { 3065 PATypeHolder Ty(Type::VoidTy); 3066 Value *Size = 0; 3067 LocTy SizeLoc = 0; 3068 unsigned Alignment = 0; 3069 if (ParseType(Ty)) return true; 3070 3071 if (EatIfPresent(lltok::comma)) { 3072 if (Lex.getKind() == lltok::kw_align) { 3073 if (ParseOptionalAlignment(Alignment)) return true; 3074 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) || 3075 ParseOptionalCommaAlignment(Alignment)) { 3076 return true; 3077 } 3078 } 3079 3080 if (Size && Size->getType() != Type::Int32Ty) 3081 return Error(SizeLoc, "element count must be i32"); 3082 3083 if (Opc == Instruction::Malloc) 3084 Inst = new MallocInst(Ty, Size, Alignment); 3085 else 3086 Inst = new AllocaInst(Ty, Size, Alignment); 3087 return false; 3088} 3089 3090/// ParseFree 3091/// ::= 'free' TypeAndValue 3092bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) { 3093 Value *Val; LocTy Loc; 3094 if (ParseTypeAndValue(Val, Loc, PFS)) return true; 3095 if (!isa<PointerType>(Val->getType())) 3096 return Error(Loc, "operand to free must be a pointer"); 3097 Inst = new FreeInst(Val); 3098 return false; 3099} 3100 3101/// ParseLoad 3102/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)? 3103bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS, 3104 bool isVolatile) { 3105 Value *Val; LocTy Loc; 3106 unsigned Alignment; 3107 if (ParseTypeAndValue(Val, Loc, PFS) || 3108 ParseOptionalCommaAlignment(Alignment)) 3109 return true; 3110 3111 if (!isa<PointerType>(Val->getType()) || 3112 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType()) 3113 return Error(Loc, "load operand must be a pointer to a first class type"); 3114 3115 Inst = new LoadInst(Val, "", isVolatile, Alignment); 3116 return false; 3117} 3118 3119/// ParseStore 3120/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)? 3121bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS, 3122 bool isVolatile) { 3123 Value *Val, *Ptr; LocTy Loc, PtrLoc; 3124 unsigned Alignment; 3125 if (ParseTypeAndValue(Val, Loc, PFS) || 3126 ParseToken(lltok::comma, "expected ',' after store operand") || 3127 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 3128 ParseOptionalCommaAlignment(Alignment)) 3129 return true; 3130 3131 if (!isa<PointerType>(Ptr->getType())) 3132 return Error(PtrLoc, "store operand must be a pointer"); 3133 if (!Val->getType()->isFirstClassType()) 3134 return Error(Loc, "store operand must be a first class value"); 3135 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 3136 return Error(Loc, "stored value and pointer type do not match"); 3137 3138 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment); 3139 return false; 3140} 3141 3142/// ParseGetResult 3143/// ::= 'getresult' TypeAndValue ',' uint 3144/// FIXME: Remove support for getresult in LLVM 3.0 3145bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) { 3146 Value *Val; LocTy ValLoc, EltLoc; 3147 unsigned Element; 3148 if (ParseTypeAndValue(Val, ValLoc, PFS) || 3149 ParseToken(lltok::comma, "expected ',' after getresult operand") || 3150 ParseUInt32(Element, EltLoc)) 3151 return true; 3152 3153 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType())) 3154 return Error(ValLoc, "getresult inst requires an aggregate operand"); 3155 if (!ExtractValueInst::getIndexedType(Val->getType(), Element)) 3156 return Error(EltLoc, "invalid getresult index for value"); 3157 Inst = ExtractValueInst::Create(Val, Element); 3158 return false; 3159} 3160 3161/// ParseGetElementPtr 3162/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)* 3163bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 3164 Value *Ptr, *Val; LocTy Loc, EltLoc; 3165 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true; 3166 3167 if (!isa<PointerType>(Ptr->getType())) 3168 return Error(Loc, "base of getelementptr must be a pointer"); 3169 3170 SmallVector<Value*, 16> Indices; 3171 while (EatIfPresent(lltok::comma)) { 3172 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; 3173 if (!isa<IntegerType>(Val->getType())) 3174 return Error(EltLoc, "getelementptr index must be an integer"); 3175 Indices.push_back(Val); 3176 } 3177 3178 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), 3179 Indices.begin(), Indices.end())) 3180 return Error(Loc, "invalid getelementptr indices"); 3181 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end()); 3182 return false; 3183} 3184 3185/// ParseExtractValue 3186/// ::= 'extractvalue' TypeAndValue (',' uint32)+ 3187bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 3188 Value *Val; LocTy Loc; 3189 SmallVector<unsigned, 4> Indices; 3190 if (ParseTypeAndValue(Val, Loc, PFS) || 3191 ParseIndexList(Indices)) 3192 return true; 3193 3194 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType())) 3195 return Error(Loc, "extractvalue operand must be array or struct"); 3196 3197 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(), 3198 Indices.end())) 3199 return Error(Loc, "invalid indices for extractvalue"); 3200 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end()); 3201 return false; 3202} 3203 3204/// ParseInsertValue 3205/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 3206bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 3207 Value *Val0, *Val1; LocTy Loc0, Loc1; 3208 SmallVector<unsigned, 4> Indices; 3209 if (ParseTypeAndValue(Val0, Loc0, PFS) || 3210 ParseToken(lltok::comma, "expected comma after insertvalue operand") || 3211 ParseTypeAndValue(Val1, Loc1, PFS) || 3212 ParseIndexList(Indices)) 3213 return true; 3214 3215 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType())) 3216 return Error(Loc0, "extractvalue operand must be array or struct"); 3217 3218 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), 3219 Indices.end())) 3220 return Error(Loc0, "invalid indices for insertvalue"); 3221 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end()); 3222 return false; 3223} 3224