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