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