LLParser.cpp revision 32811bef956e0fae4329e6515420d85f7e510660
1//===-- LLParser.cpp - Parser Class ---------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the parser class for .ll files. 11// 12//===----------------------------------------------------------------------===// 13 14#include "LLParser.h" 15#include "llvm/AutoUpgrade.h" 16#include "llvm/CallingConv.h" 17#include "llvm/Constants.h" 18#include "llvm/DerivedTypes.h" 19#include "llvm/InlineAsm.h" 20#include "llvm/Instructions.h" 21#include "llvm/Module.h" 22#include "llvm/Operator.h" 23#include "llvm/ValueSymbolTable.h" 24#include "llvm/ADT/SmallPtrSet.h" 25#include "llvm/Support/ErrorHandling.h" 26#include "llvm/Support/raw_ostream.h" 27using namespace llvm; 28 29static std::string getTypeString(Type *T) { 30 std::string Result; 31 raw_string_ostream Tmp(Result); 32 Tmp << *T; 33 return Tmp.str(); 34} 35 36/// Run: module ::= toplevelentity* 37bool LLParser::Run() { 38 // Prime the lexer. 39 Lex.Lex(); 40 41 return ParseTopLevelEntities() || 42 ValidateEndOfModule(); 43} 44 45/// ValidateEndOfModule - Do final validity and sanity checks at the end of the 46/// module. 47bool LLParser::ValidateEndOfModule() { 48 // Handle any instruction metadata forward references. 49 if (!ForwardRefInstMetadata.empty()) { 50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator 51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end(); 52 I != E; ++I) { 53 Instruction *Inst = I->first; 54 const std::vector<MDRef> &MDList = I->second; 55 56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) { 57 unsigned SlotNo = MDList[i].MDSlot; 58 59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0) 60 return Error(MDList[i].Loc, "use of undefined metadata '!" + 61 Twine(SlotNo) + "'"); 62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]); 63 } 64 } 65 ForwardRefInstMetadata.clear(); 66 } 67 68 69 // If there are entries in ForwardRefBlockAddresses at this point, they are 70 // references after the function was defined. Resolve those now. 71 while (!ForwardRefBlockAddresses.empty()) { 72 // Okay, we are referencing an already-parsed function, resolve them now. 73 Function *TheFn = 0; 74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first; 75 if (Fn.Kind == ValID::t_GlobalName) 76 TheFn = M->getFunction(Fn.StrVal); 77 else if (Fn.UIntVal < NumberedVals.size()) 78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]); 79 80 if (TheFn == 0) 81 return Error(Fn.Loc, "unknown function referenced by blockaddress"); 82 83 // Resolve all these references. 84 if (ResolveForwardRefBlockAddresses(TheFn, 85 ForwardRefBlockAddresses.begin()->second, 86 0)) 87 return true; 88 89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin()); 90 } 91 92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) 93 if (NumberedTypes[i].second.isValid()) 94 return Error(NumberedTypes[i].second, 95 "use of undefined type '%" + Twine(i) + "'"); 96 97 for (StringMap<std::pair<Type*, LocTy> >::iterator I = 98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) 99 if (I->second.second.isValid()) 100 return Error(I->second.second, 101 "use of undefined type named '" + I->getKey() + "'"); 102 103 if (!ForwardRefVals.empty()) 104 return Error(ForwardRefVals.begin()->second.second, 105 "use of undefined value '@" + ForwardRefVals.begin()->first + 106 "'"); 107 108 if (!ForwardRefValIDs.empty()) 109 return Error(ForwardRefValIDs.begin()->second.second, 110 "use of undefined value '@" + 111 Twine(ForwardRefValIDs.begin()->first) + "'"); 112 113 if (!ForwardRefMDNodes.empty()) 114 return Error(ForwardRefMDNodes.begin()->second.second, 115 "use of undefined metadata '!" + 116 Twine(ForwardRefMDNodes.begin()->first) + "'"); 117 118 119 // Look for intrinsic functions and CallInst that need to be upgraded 120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) 121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove 122 123 return false; 124} 125 126bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn, 127 std::vector<std::pair<ValID, GlobalValue*> > &Refs, 128 PerFunctionState *PFS) { 129 // Loop over all the references, resolving them. 130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) { 131 BasicBlock *Res; 132 if (PFS) { 133 if (Refs[i].first.Kind == ValID::t_LocalName) 134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc); 135 else 136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc); 137 } else if (Refs[i].first.Kind == ValID::t_LocalID) { 138 return Error(Refs[i].first.Loc, 139 "cannot take address of numeric label after the function is defined"); 140 } else { 141 Res = dyn_cast_or_null<BasicBlock>( 142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal)); 143 } 144 145 if (Res == 0) 146 return Error(Refs[i].first.Loc, 147 "referenced value is not a basic block"); 148 149 // Get the BlockAddress for this and update references to use it. 150 BlockAddress *BA = BlockAddress::get(TheFn, Res); 151 Refs[i].second->replaceAllUsesWith(BA); 152 Refs[i].second->eraseFromParent(); 153 } 154 return false; 155} 156 157 158//===----------------------------------------------------------------------===// 159// Top-Level Entities 160//===----------------------------------------------------------------------===// 161 162bool LLParser::ParseTopLevelEntities() { 163 while (1) { 164 switch (Lex.getKind()) { 165 default: return TokError("expected top-level entity"); 166 case lltok::Eof: return false; 167 case lltok::kw_declare: if (ParseDeclare()) return true; break; 168 case lltok::kw_define: if (ParseDefine()) return true; break; 169 case lltok::kw_module: if (ParseModuleAsm()) return true; break; 170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break; 171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break; 172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break; 173 case lltok::LocalVar: if (ParseNamedType()) return true; break; 174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break; 175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break; 176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break; 177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break; 178 179 // The Global variable production with no name can have many different 180 // optional leading prefixes, the production is: 181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 182 // OptionalAddrSpace OptionalUnNammedAddr 183 // ('constant'|'global') ... 184 case lltok::kw_private: // OptionalLinkage 185 case lltok::kw_linker_private: // OptionalLinkage 186 case lltok::kw_linker_private_weak: // OptionalLinkage 187 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat. 188 case lltok::kw_internal: // OptionalLinkage 189 case lltok::kw_weak: // OptionalLinkage 190 case lltok::kw_weak_odr: // OptionalLinkage 191 case lltok::kw_linkonce: // OptionalLinkage 192 case lltok::kw_linkonce_odr: // OptionalLinkage 193 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage 194 case lltok::kw_appending: // OptionalLinkage 195 case lltok::kw_dllexport: // OptionalLinkage 196 case lltok::kw_common: // OptionalLinkage 197 case lltok::kw_dllimport: // OptionalLinkage 198 case lltok::kw_extern_weak: // OptionalLinkage 199 case lltok::kw_external: { // OptionalLinkage 200 unsigned Linkage, Visibility; 201 if (ParseOptionalLinkage(Linkage) || 202 ParseOptionalVisibility(Visibility) || 203 ParseGlobal("", SMLoc(), Linkage, true, Visibility)) 204 return true; 205 break; 206 } 207 case lltok::kw_default: // OptionalVisibility 208 case lltok::kw_hidden: // OptionalVisibility 209 case lltok::kw_protected: { // OptionalVisibility 210 unsigned Visibility; 211 if (ParseOptionalVisibility(Visibility) || 212 ParseGlobal("", SMLoc(), 0, false, Visibility)) 213 return true; 214 break; 215 } 216 217 case lltok::kw_thread_local: // OptionalThreadLocal 218 case lltok::kw_addrspace: // OptionalAddrSpace 219 case lltok::kw_constant: // GlobalType 220 case lltok::kw_global: // GlobalType 221 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true; 222 break; 223 } 224 } 225} 226 227 228/// toplevelentity 229/// ::= 'module' 'asm' STRINGCONSTANT 230bool LLParser::ParseModuleAsm() { 231 assert(Lex.getKind() == lltok::kw_module); 232 Lex.Lex(); 233 234 std::string AsmStr; 235 if (ParseToken(lltok::kw_asm, "expected 'module asm'") || 236 ParseStringConstant(AsmStr)) return true; 237 238 M->appendModuleInlineAsm(AsmStr); 239 return false; 240} 241 242/// toplevelentity 243/// ::= 'target' 'triple' '=' STRINGCONSTANT 244/// ::= 'target' 'datalayout' '=' STRINGCONSTANT 245bool LLParser::ParseTargetDefinition() { 246 assert(Lex.getKind() == lltok::kw_target); 247 std::string Str; 248 switch (Lex.Lex()) { 249 default: return TokError("unknown target property"); 250 case lltok::kw_triple: 251 Lex.Lex(); 252 if (ParseToken(lltok::equal, "expected '=' after target triple") || 253 ParseStringConstant(Str)) 254 return true; 255 M->setTargetTriple(Str); 256 return false; 257 case lltok::kw_datalayout: 258 Lex.Lex(); 259 if (ParseToken(lltok::equal, "expected '=' after target datalayout") || 260 ParseStringConstant(Str)) 261 return true; 262 M->setDataLayout(Str); 263 return false; 264 } 265} 266 267/// toplevelentity 268/// ::= 'deplibs' '=' '[' ']' 269/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']' 270bool LLParser::ParseDepLibs() { 271 assert(Lex.getKind() == lltok::kw_deplibs); 272 Lex.Lex(); 273 if (ParseToken(lltok::equal, "expected '=' after deplibs") || 274 ParseToken(lltok::lsquare, "expected '=' after deplibs")) 275 return true; 276 277 if (EatIfPresent(lltok::rsquare)) 278 return false; 279 280 std::string Str; 281 if (ParseStringConstant(Str)) return true; 282 M->addLibrary(Str); 283 284 while (EatIfPresent(lltok::comma)) { 285 if (ParseStringConstant(Str)) return true; 286 M->addLibrary(Str); 287 } 288 289 return ParseToken(lltok::rsquare, "expected ']' at end of list"); 290} 291 292/// ParseUnnamedType: 293/// ::= LocalVarID '=' 'type' type 294bool LLParser::ParseUnnamedType() { 295 LocTy TypeLoc = Lex.getLoc(); 296 unsigned TypeID = Lex.getUIntVal(); 297 Lex.Lex(); // eat LocalVarID; 298 299 if (ParseToken(lltok::equal, "expected '=' after name") || 300 ParseToken(lltok::kw_type, "expected 'type' after '='")) 301 return true; 302 303 if (TypeID >= NumberedTypes.size()) 304 NumberedTypes.resize(TypeID+1); 305 306 Type *Result = 0; 307 if (ParseStructDefinition(TypeLoc, "", 308 NumberedTypes[TypeID], Result)) return true; 309 310 if (!isa<StructType>(Result)) { 311 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; 312 if (Entry.first) 313 return Error(TypeLoc, "non-struct types may not be recursive"); 314 Entry.first = Result; 315 Entry.second = SMLoc(); 316 } 317 318 return false; 319} 320 321 322/// toplevelentity 323/// ::= LocalVar '=' 'type' type 324bool LLParser::ParseNamedType() { 325 std::string Name = Lex.getStrVal(); 326 LocTy NameLoc = Lex.getLoc(); 327 Lex.Lex(); // eat LocalVar. 328 329 if (ParseToken(lltok::equal, "expected '=' after name") || 330 ParseToken(lltok::kw_type, "expected 'type' after name")) 331 return true; 332 333 Type *Result = 0; 334 if (ParseStructDefinition(NameLoc, Name, 335 NamedTypes[Name], Result)) return true; 336 337 if (!isa<StructType>(Result)) { 338 std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; 339 if (Entry.first) 340 return Error(NameLoc, "non-struct types may not be recursive"); 341 Entry.first = Result; 342 Entry.second = SMLoc(); 343 } 344 345 return false; 346} 347 348 349/// toplevelentity 350/// ::= 'declare' FunctionHeader 351bool LLParser::ParseDeclare() { 352 assert(Lex.getKind() == lltok::kw_declare); 353 Lex.Lex(); 354 355 Function *F; 356 return ParseFunctionHeader(F, false); 357} 358 359/// toplevelentity 360/// ::= 'define' FunctionHeader '{' ... 361bool LLParser::ParseDefine() { 362 assert(Lex.getKind() == lltok::kw_define); 363 Lex.Lex(); 364 365 Function *F; 366 return ParseFunctionHeader(F, true) || 367 ParseFunctionBody(*F); 368} 369 370/// ParseGlobalType 371/// ::= 'constant' 372/// ::= 'global' 373bool LLParser::ParseGlobalType(bool &IsConstant) { 374 if (Lex.getKind() == lltok::kw_constant) 375 IsConstant = true; 376 else if (Lex.getKind() == lltok::kw_global) 377 IsConstant = false; 378 else { 379 IsConstant = false; 380 return TokError("expected 'global' or 'constant'"); 381 } 382 Lex.Lex(); 383 return false; 384} 385 386/// ParseUnnamedGlobal: 387/// OptionalVisibility ALIAS ... 388/// OptionalLinkage OptionalVisibility ... -> global variable 389/// GlobalID '=' OptionalVisibility ALIAS ... 390/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable 391bool LLParser::ParseUnnamedGlobal() { 392 unsigned VarID = NumberedVals.size(); 393 std::string Name; 394 LocTy NameLoc = Lex.getLoc(); 395 396 // Handle the GlobalID form. 397 if (Lex.getKind() == lltok::GlobalID) { 398 if (Lex.getUIntVal() != VarID) 399 return Error(Lex.getLoc(), "variable expected to be numbered '%" + 400 Twine(VarID) + "'"); 401 Lex.Lex(); // eat GlobalID; 402 403 if (ParseToken(lltok::equal, "expected '=' after name")) 404 return true; 405 } 406 407 bool HasLinkage; 408 unsigned Linkage, Visibility; 409 if (ParseOptionalLinkage(Linkage, HasLinkage) || 410 ParseOptionalVisibility(Visibility)) 411 return true; 412 413 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 414 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); 415 return ParseAlias(Name, NameLoc, Visibility); 416} 417 418/// ParseNamedGlobal: 419/// GlobalVar '=' OptionalVisibility ALIAS ... 420/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable 421bool LLParser::ParseNamedGlobal() { 422 assert(Lex.getKind() == lltok::GlobalVar); 423 LocTy NameLoc = Lex.getLoc(); 424 std::string Name = Lex.getStrVal(); 425 Lex.Lex(); 426 427 bool HasLinkage; 428 unsigned Linkage, Visibility; 429 if (ParseToken(lltok::equal, "expected '=' in global variable") || 430 ParseOptionalLinkage(Linkage, HasLinkage) || 431 ParseOptionalVisibility(Visibility)) 432 return true; 433 434 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 435 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); 436 return ParseAlias(Name, NameLoc, Visibility); 437} 438 439// MDString: 440// ::= '!' STRINGCONSTANT 441bool LLParser::ParseMDString(MDString *&Result) { 442 std::string Str; 443 if (ParseStringConstant(Str)) return true; 444 Result = MDString::get(Context, Str); 445 return false; 446} 447 448// MDNode: 449// ::= '!' MDNodeNumber 450// 451/// This version of ParseMDNodeID returns the slot number and null in the case 452/// of a forward reference. 453bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) { 454 // !{ ..., !42, ... } 455 if (ParseUInt32(SlotNo)) return true; 456 457 // Check existing MDNode. 458 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0) 459 Result = NumberedMetadata[SlotNo]; 460 else 461 Result = 0; 462 return false; 463} 464 465bool LLParser::ParseMDNodeID(MDNode *&Result) { 466 // !{ ..., !42, ... } 467 unsigned MID = 0; 468 if (ParseMDNodeID(Result, MID)) return true; 469 470 // If not a forward reference, just return it now. 471 if (Result) return false; 472 473 // Otherwise, create MDNode forward reference. 474 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>()); 475 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); 476 477 if (NumberedMetadata.size() <= MID) 478 NumberedMetadata.resize(MID+1); 479 NumberedMetadata[MID] = FwdNode; 480 Result = FwdNode; 481 return false; 482} 483 484/// ParseNamedMetadata: 485/// !foo = !{ !1, !2 } 486bool LLParser::ParseNamedMetadata() { 487 assert(Lex.getKind() == lltok::MetadataVar); 488 std::string Name = Lex.getStrVal(); 489 Lex.Lex(); 490 491 if (ParseToken(lltok::equal, "expected '=' here") || 492 ParseToken(lltok::exclaim, "Expected '!' here") || 493 ParseToken(lltok::lbrace, "Expected '{' here")) 494 return true; 495 496 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); 497 if (Lex.getKind() != lltok::rbrace) 498 do { 499 if (ParseToken(lltok::exclaim, "Expected '!' here")) 500 return true; 501 502 MDNode *N = 0; 503 if (ParseMDNodeID(N)) return true; 504 NMD->addOperand(N); 505 } while (EatIfPresent(lltok::comma)); 506 507 if (ParseToken(lltok::rbrace, "expected end of metadata node")) 508 return true; 509 510 return false; 511} 512 513/// ParseStandaloneMetadata: 514/// !42 = !{...} 515bool LLParser::ParseStandaloneMetadata() { 516 assert(Lex.getKind() == lltok::exclaim); 517 Lex.Lex(); 518 unsigned MetadataID = 0; 519 520 LocTy TyLoc; 521 Type *Ty = 0; 522 SmallVector<Value *, 16> Elts; 523 if (ParseUInt32(MetadataID) || 524 ParseToken(lltok::equal, "expected '=' here") || 525 ParseType(Ty, TyLoc) || 526 ParseToken(lltok::exclaim, "Expected '!' here") || 527 ParseToken(lltok::lbrace, "Expected '{' here") || 528 ParseMDNodeVector(Elts, NULL) || 529 ParseToken(lltok::rbrace, "expected end of metadata node")) 530 return true; 531 532 MDNode *Init = MDNode::get(Context, Elts); 533 534 // See if this was forward referenced, if so, handle it. 535 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator 536 FI = ForwardRefMDNodes.find(MetadataID); 537 if (FI != ForwardRefMDNodes.end()) { 538 MDNode *Temp = FI->second.first; 539 Temp->replaceAllUsesWith(Init); 540 MDNode::deleteTemporary(Temp); 541 ForwardRefMDNodes.erase(FI); 542 543 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); 544 } else { 545 if (MetadataID >= NumberedMetadata.size()) 546 NumberedMetadata.resize(MetadataID+1); 547 548 if (NumberedMetadata[MetadataID] != 0) 549 return TokError("Metadata id is already used"); 550 NumberedMetadata[MetadataID] = Init; 551 } 552 553 return false; 554} 555 556/// ParseAlias: 557/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee 558/// Aliasee 559/// ::= TypeAndValue 560/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')' 561/// ::= 'getelementptr' 'inbounds'? '(' ... ')' 562/// 563/// Everything through visibility has already been parsed. 564/// 565bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, 566 unsigned Visibility) { 567 assert(Lex.getKind() == lltok::kw_alias); 568 Lex.Lex(); 569 unsigned Linkage; 570 LocTy LinkageLoc = Lex.getLoc(); 571 if (ParseOptionalLinkage(Linkage)) 572 return true; 573 574 if (Linkage != GlobalValue::ExternalLinkage && 575 Linkage != GlobalValue::WeakAnyLinkage && 576 Linkage != GlobalValue::WeakODRLinkage && 577 Linkage != GlobalValue::InternalLinkage && 578 Linkage != GlobalValue::PrivateLinkage && 579 Linkage != GlobalValue::LinkerPrivateLinkage && 580 Linkage != GlobalValue::LinkerPrivateWeakLinkage) 581 return Error(LinkageLoc, "invalid linkage type for alias"); 582 583 Constant *Aliasee; 584 LocTy AliaseeLoc = Lex.getLoc(); 585 if (Lex.getKind() != lltok::kw_bitcast && 586 Lex.getKind() != lltok::kw_getelementptr) { 587 if (ParseGlobalTypeAndValue(Aliasee)) return true; 588 } else { 589 // The bitcast dest type is not present, it is implied by the dest type. 590 ValID ID; 591 if (ParseValID(ID)) return true; 592 if (ID.Kind != ValID::t_Constant) 593 return Error(AliaseeLoc, "invalid aliasee"); 594 Aliasee = ID.ConstantVal; 595 } 596 597 if (!Aliasee->getType()->isPointerTy()) 598 return Error(AliaseeLoc, "alias must have pointer type"); 599 600 // Okay, create the alias but do not insert it into the module yet. 601 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), 602 (GlobalValue::LinkageTypes)Linkage, Name, 603 Aliasee); 604 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); 605 606 // See if this value already exists in the symbol table. If so, it is either 607 // a redefinition or a definition of a forward reference. 608 if (GlobalValue *Val = M->getNamedValue(Name)) { 609 // See if this was a redefinition. If so, there is no entry in 610 // ForwardRefVals. 611 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 612 I = ForwardRefVals.find(Name); 613 if (I == ForwardRefVals.end()) 614 return Error(NameLoc, "redefinition of global named '@" + Name + "'"); 615 616 // Otherwise, this was a definition of forward ref. Verify that types 617 // agree. 618 if (Val->getType() != GA->getType()) 619 return Error(NameLoc, 620 "forward reference and definition of alias have different types"); 621 622 // If they agree, just RAUW the old value with the alias and remove the 623 // forward ref info. 624 Val->replaceAllUsesWith(GA); 625 Val->eraseFromParent(); 626 ForwardRefVals.erase(I); 627 } 628 629 // Insert into the module, we know its name won't collide now. 630 M->getAliasList().push_back(GA); 631 assert(GA->getName() == Name && "Should not be a name conflict!"); 632 633 return false; 634} 635 636/// ParseGlobal 637/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal 638/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const 639/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 640/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const 641/// 642/// Everything through visibility has been parsed already. 643/// 644bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, 645 unsigned Linkage, bool HasLinkage, 646 unsigned Visibility) { 647 unsigned AddrSpace; 648 bool IsConstant, UnnamedAddr; 649 GlobalVariable::ThreadLocalMode TLM; 650 LocTy UnnamedAddrLoc; 651 LocTy TyLoc; 652 653 Type *Ty = 0; 654 if (ParseOptionalThreadLocal(TLM) || 655 ParseOptionalAddrSpace(AddrSpace) || 656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr, 657 &UnnamedAddrLoc) || 658 ParseGlobalType(IsConstant) || 659 ParseType(Ty, TyLoc)) 660 return true; 661 662 // If the linkage is specified and is external, then no initializer is 663 // present. 664 Constant *Init = 0; 665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage && 666 Linkage != GlobalValue::ExternalWeakLinkage && 667 Linkage != GlobalValue::ExternalLinkage)) { 668 if (ParseGlobalValue(Ty, Init)) 669 return true; 670 } 671 672 if (Ty->isFunctionTy() || Ty->isLabelTy()) 673 return Error(TyLoc, "invalid type for global variable"); 674 675 GlobalVariable *GV = 0; 676 677 // See if the global was forward referenced, if so, use the global. 678 if (!Name.empty()) { 679 if (GlobalValue *GVal = M->getNamedValue(Name)) { 680 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal)) 681 return Error(NameLoc, "redefinition of global '@" + Name + "'"); 682 GV = cast<GlobalVariable>(GVal); 683 } 684 } else { 685 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 686 I = ForwardRefValIDs.find(NumberedVals.size()); 687 if (I != ForwardRefValIDs.end()) { 688 GV = cast<GlobalVariable>(I->second.first); 689 ForwardRefValIDs.erase(I); 690 } 691 } 692 693 if (GV == 0) { 694 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, 695 Name, 0, GlobalVariable::NotThreadLocal, 696 AddrSpace); 697 } else { 698 if (GV->getType()->getElementType() != Ty) 699 return Error(TyLoc, 700 "forward reference and definition of global have different types"); 701 702 // Move the forward-reference to the correct spot in the module. 703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); 704 } 705 706 if (Name.empty()) 707 NumberedVals.push_back(GV); 708 709 // Set the parsed properties on the global. 710 if (Init) 711 GV->setInitializer(Init); 712 GV->setConstant(IsConstant); 713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 715 GV->setThreadLocalMode(TLM); 716 GV->setUnnamedAddr(UnnamedAddr); 717 718 // Parse attributes on the global. 719 while (Lex.getKind() == lltok::comma) { 720 Lex.Lex(); 721 722 if (Lex.getKind() == lltok::kw_section) { 723 Lex.Lex(); 724 GV->setSection(Lex.getStrVal()); 725 if (ParseToken(lltok::StringConstant, "expected global section string")) 726 return true; 727 } else if (Lex.getKind() == lltok::kw_align) { 728 unsigned Alignment; 729 if (ParseOptionalAlignment(Alignment)) return true; 730 GV->setAlignment(Alignment); 731 } else { 732 TokError("unknown global variable property!"); 733 } 734 } 735 736 return false; 737} 738 739 740//===----------------------------------------------------------------------===// 741// GlobalValue Reference/Resolution Routines. 742//===----------------------------------------------------------------------===// 743 744/// GetGlobalVal - Get a value with the specified name or ID, creating a 745/// forward reference record if needed. This can return null if the value 746/// exists but does not have the right type. 747GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty, 748 LocTy Loc) { 749 PointerType *PTy = dyn_cast<PointerType>(Ty); 750 if (PTy == 0) { 751 Error(Loc, "global variable reference must have pointer type"); 752 return 0; 753 } 754 755 // Look this name up in the normal function symbol table. 756 GlobalValue *Val = 757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 758 759 // If this is a forward reference for the value, see if we already created a 760 // forward ref record. 761 if (Val == 0) { 762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 763 I = ForwardRefVals.find(Name); 764 if (I != ForwardRefVals.end()) 765 Val = I->second.first; 766 } 767 768 // If we have the value in the symbol table or fwd-ref table, return it. 769 if (Val) { 770 if (Val->getType() == Ty) return Val; 771 Error(Loc, "'@" + Name + "' defined with type '" + 772 getTypeString(Val->getType()) + "'"); 773 return 0; 774 } 775 776 // Otherwise, create a new forward reference for this value and remember it. 777 GlobalValue *FwdVal; 778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) 779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); 780 else 781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, 782 GlobalValue::ExternalWeakLinkage, 0, Name); 783 784 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 785 return FwdVal; 786} 787 788GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) { 789 PointerType *PTy = dyn_cast<PointerType>(Ty); 790 if (PTy == 0) { 791 Error(Loc, "global variable reference must have pointer type"); 792 return 0; 793 } 794 795 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 796 797 // If this is a forward reference for the value, see if we already created a 798 // forward ref record. 799 if (Val == 0) { 800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 801 I = ForwardRefValIDs.find(ID); 802 if (I != ForwardRefValIDs.end()) 803 Val = I->second.first; 804 } 805 806 // If we have the value in the symbol table or fwd-ref table, return it. 807 if (Val) { 808 if (Val->getType() == Ty) return Val; 809 Error(Loc, "'@" + Twine(ID) + "' defined with type '" + 810 getTypeString(Val->getType()) + "'"); 811 return 0; 812 } 813 814 // Otherwise, create a new forward reference for this value and remember it. 815 GlobalValue *FwdVal; 816 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) 817 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M); 818 else 819 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, 820 GlobalValue::ExternalWeakLinkage, 0, ""); 821 822 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 823 return FwdVal; 824} 825 826 827//===----------------------------------------------------------------------===// 828// Helper Routines. 829//===----------------------------------------------------------------------===// 830 831/// ParseToken - If the current token has the specified kind, eat it and return 832/// success. Otherwise, emit the specified error and return failure. 833bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) { 834 if (Lex.getKind() != T) 835 return TokError(ErrMsg); 836 Lex.Lex(); 837 return false; 838} 839 840/// ParseStringConstant 841/// ::= StringConstant 842bool LLParser::ParseStringConstant(std::string &Result) { 843 if (Lex.getKind() != lltok::StringConstant) 844 return TokError("expected string constant"); 845 Result = Lex.getStrVal(); 846 Lex.Lex(); 847 return false; 848} 849 850/// ParseUInt32 851/// ::= uint32 852bool LLParser::ParseUInt32(unsigned &Val) { 853 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 854 return TokError("expected integer"); 855 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 856 if (Val64 != unsigned(Val64)) 857 return TokError("expected 32-bit integer (too large)"); 858 Val = Val64; 859 Lex.Lex(); 860 return false; 861} 862 863/// ParseTLSModel 864/// := 'localdynamic' 865/// := 'initialexec' 866/// := 'localexec' 867bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { 868 switch (Lex.getKind()) { 869 default: 870 return TokError("expected localdynamic, initialexec or localexec"); 871 case lltok::kw_localdynamic: 872 TLM = GlobalVariable::LocalDynamicTLSModel; 873 break; 874 case lltok::kw_initialexec: 875 TLM = GlobalVariable::InitialExecTLSModel; 876 break; 877 case lltok::kw_localexec: 878 TLM = GlobalVariable::LocalExecTLSModel; 879 break; 880 } 881 882 Lex.Lex(); 883 return false; 884} 885 886/// ParseOptionalThreadLocal 887/// := /*empty*/ 888/// := 'thread_local' 889/// := 'thread_local' '(' tlsmodel ')' 890bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { 891 TLM = GlobalVariable::NotThreadLocal; 892 if (!EatIfPresent(lltok::kw_thread_local)) 893 return false; 894 895 TLM = GlobalVariable::GeneralDynamicTLSModel; 896 if (Lex.getKind() == lltok::lparen) { 897 Lex.Lex(); 898 return ParseTLSModel(TLM) || 899 ParseToken(lltok::rparen, "expected ')' after thread local model"); 900 } 901 return false; 902} 903 904/// ParseOptionalAddrSpace 905/// := /*empty*/ 906/// := 'addrspace' '(' uint32 ')' 907bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { 908 AddrSpace = 0; 909 if (!EatIfPresent(lltok::kw_addrspace)) 910 return false; 911 return ParseToken(lltok::lparen, "expected '(' in address space") || 912 ParseUInt32(AddrSpace) || 913 ParseToken(lltok::rparen, "expected ')' in address space"); 914} 915 916/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind 917/// indicates what kind of attribute list this is: 0: function arg, 1: result, 918/// 2: function attr. 919bool LLParser::ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind) { 920 Attrs = Attribute::None; 921 LocTy AttrLoc = Lex.getLoc(); 922 923 while (1) { 924 switch (Lex.getKind()) { 925 default: // End of attributes. 926 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly)) 927 return Error(AttrLoc, "invalid use of function-only attribute"); 928 929 // As a hack, we allow "align 2" on functions as a synonym for 930 // "alignstack 2". 931 if (AttrKind == 2 && 932 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment))) 933 return Error(AttrLoc, "invalid use of attribute on a function"); 934 935 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly)) 936 return Error(AttrLoc, "invalid use of parameter-only attribute"); 937 938 return false; 939 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break; 940 case lltok::kw_signext: Attrs |= Attribute::SExt; break; 941 case lltok::kw_inreg: Attrs |= Attribute::InReg; break; 942 case lltok::kw_sret: Attrs |= Attribute::StructRet; break; 943 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break; 944 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break; 945 case lltok::kw_byval: Attrs |= Attribute::ByVal; break; 946 case lltok::kw_nest: Attrs |= Attribute::Nest; break; 947 948 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break; 949 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break; 950 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break; 951 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break; 952 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break; 953 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break; 954 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break; 955 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break; 956 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break; 957 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break; 958 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break; 959 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break; 960 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break; 961 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break; 962 case lltok::kw_naked: Attrs |= Attribute::Naked; break; 963 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break; 964 case lltok::kw_address_safety: Attrs |= Attribute::AddressSafety; break; 965 case lltok::kw_ia_nsdialect: Attrs |= Attribute::IANSDialect; break; 966 967 case lltok::kw_alignstack: { 968 unsigned Alignment; 969 if (ParseOptionalStackAlignment(Alignment)) 970 return true; 971 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment); 972 continue; 973 } 974 975 case lltok::kw_align: { 976 unsigned Alignment; 977 if (ParseOptionalAlignment(Alignment)) 978 return true; 979 Attrs |= Attribute::constructAlignmentFromInt(Alignment); 980 continue; 981 } 982 983 } 984 Lex.Lex(); 985 } 986} 987 988/// ParseOptionalLinkage 989/// ::= /*empty*/ 990/// ::= 'private' 991/// ::= 'linker_private' 992/// ::= 'linker_private_weak' 993/// ::= 'internal' 994/// ::= 'weak' 995/// ::= 'weak_odr' 996/// ::= 'linkonce' 997/// ::= 'linkonce_odr' 998/// ::= 'linkonce_odr_auto_hide' 999/// ::= 'available_externally' 1000/// ::= 'appending' 1001/// ::= 'dllexport' 1002/// ::= 'common' 1003/// ::= 'dllimport' 1004/// ::= 'extern_weak' 1005/// ::= 'external' 1006bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { 1007 HasLinkage = false; 1008 switch (Lex.getKind()) { 1009 default: Res=GlobalValue::ExternalLinkage; return false; 1010 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break; 1011 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break; 1012 case lltok::kw_linker_private_weak: 1013 Res = GlobalValue::LinkerPrivateWeakLinkage; 1014 break; 1015 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break; 1016 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break; 1017 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break; 1018 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break; 1019 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break; 1020 case lltok::kw_linkonce_odr_auto_hide: 1021 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat. 1022 Res = GlobalValue::LinkOnceODRAutoHideLinkage; 1023 break; 1024 case lltok::kw_available_externally: 1025 Res = GlobalValue::AvailableExternallyLinkage; 1026 break; 1027 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break; 1028 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break; 1029 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break; 1030 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break; 1031 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break; 1032 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break; 1033 } 1034 Lex.Lex(); 1035 HasLinkage = true; 1036 return false; 1037} 1038 1039/// ParseOptionalVisibility 1040/// ::= /*empty*/ 1041/// ::= 'default' 1042/// ::= 'hidden' 1043/// ::= 'protected' 1044/// 1045bool LLParser::ParseOptionalVisibility(unsigned &Res) { 1046 switch (Lex.getKind()) { 1047 default: Res = GlobalValue::DefaultVisibility; return false; 1048 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break; 1049 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break; 1050 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break; 1051 } 1052 Lex.Lex(); 1053 return false; 1054} 1055 1056/// ParseOptionalCallingConv 1057/// ::= /*empty*/ 1058/// ::= 'ccc' 1059/// ::= 'fastcc' 1060/// ::= 'coldcc' 1061/// ::= 'x86_stdcallcc' 1062/// ::= 'x86_fastcallcc' 1063/// ::= 'x86_thiscallcc' 1064/// ::= 'arm_apcscc' 1065/// ::= 'arm_aapcscc' 1066/// ::= 'arm_aapcs_vfpcc' 1067/// ::= 'msp430_intrcc' 1068/// ::= 'ptx_kernel' 1069/// ::= 'ptx_device' 1070/// ::= 'cc' UINT 1071/// 1072bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) { 1073 switch (Lex.getKind()) { 1074 default: CC = CallingConv::C; return false; 1075 case lltok::kw_ccc: CC = CallingConv::C; break; 1076 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 1077 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 1078 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 1079 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 1080 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; 1081 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; 1082 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; 1083 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; 1084 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; 1085 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; 1086 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; 1087 case lltok::kw_cc: { 1088 unsigned ArbitraryCC; 1089 Lex.Lex(); 1090 if (ParseUInt32(ArbitraryCC)) 1091 return true; 1092 CC = static_cast<CallingConv::ID>(ArbitraryCC); 1093 return false; 1094 } 1095 } 1096 1097 Lex.Lex(); 1098 return false; 1099} 1100 1101/// ParseInstructionMetadata 1102/// ::= !dbg !42 (',' !dbg !57)* 1103bool LLParser::ParseInstructionMetadata(Instruction *Inst, 1104 PerFunctionState *PFS) { 1105 do { 1106 if (Lex.getKind() != lltok::MetadataVar) 1107 return TokError("expected metadata after comma"); 1108 1109 std::string Name = Lex.getStrVal(); 1110 unsigned MDK = M->getMDKindID(Name); 1111 Lex.Lex(); 1112 1113 MDNode *Node; 1114 SMLoc Loc = Lex.getLoc(); 1115 1116 if (ParseToken(lltok::exclaim, "expected '!' here")) 1117 return true; 1118 1119 // This code is similar to that of ParseMetadataValue, however it needs to 1120 // have special-case code for a forward reference; see the comments on 1121 // ForwardRefInstMetadata for details. Also, MDStrings are not supported 1122 // at the top level here. 1123 if (Lex.getKind() == lltok::lbrace) { 1124 ValID ID; 1125 if (ParseMetadataListValue(ID, PFS)) 1126 return true; 1127 assert(ID.Kind == ValID::t_MDNode); 1128 Inst->setMetadata(MDK, ID.MDNodeVal); 1129 } else { 1130 unsigned NodeID = 0; 1131 if (ParseMDNodeID(Node, NodeID)) 1132 return true; 1133 if (Node) { 1134 // If we got the node, add it to the instruction. 1135 Inst->setMetadata(MDK, Node); 1136 } else { 1137 MDRef R = { Loc, MDK, NodeID }; 1138 // Otherwise, remember that this should be resolved later. 1139 ForwardRefInstMetadata[Inst].push_back(R); 1140 } 1141 } 1142 1143 // If this is the end of the list, we're done. 1144 } while (EatIfPresent(lltok::comma)); 1145 return false; 1146} 1147 1148/// ParseOptionalAlignment 1149/// ::= /* empty */ 1150/// ::= 'align' 4 1151bool LLParser::ParseOptionalAlignment(unsigned &Alignment) { 1152 Alignment = 0; 1153 if (!EatIfPresent(lltok::kw_align)) 1154 return false; 1155 LocTy AlignLoc = Lex.getLoc(); 1156 if (ParseUInt32(Alignment)) return true; 1157 if (!isPowerOf2_32(Alignment)) 1158 return Error(AlignLoc, "alignment is not a power of two"); 1159 if (Alignment > Value::MaximumAlignment) 1160 return Error(AlignLoc, "huge alignments are not supported yet"); 1161 return false; 1162} 1163 1164/// ParseOptionalCommaAlign 1165/// ::= 1166/// ::= ',' align 4 1167/// 1168/// This returns with AteExtraComma set to true if it ate an excess comma at the 1169/// end. 1170bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment, 1171 bool &AteExtraComma) { 1172 AteExtraComma = false; 1173 while (EatIfPresent(lltok::comma)) { 1174 // Metadata at the end is an early exit. 1175 if (Lex.getKind() == lltok::MetadataVar) { 1176 AteExtraComma = true; 1177 return false; 1178 } 1179 1180 if (Lex.getKind() != lltok::kw_align) 1181 return Error(Lex.getLoc(), "expected metadata or 'align'"); 1182 1183 if (ParseOptionalAlignment(Alignment)) return true; 1184 } 1185 1186 return false; 1187} 1188 1189/// ParseScopeAndOrdering 1190/// if isAtomic: ::= 'singlethread'? AtomicOrdering 1191/// else: ::= 1192/// 1193/// This sets Scope and Ordering to the parsed values. 1194bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope, 1195 AtomicOrdering &Ordering) { 1196 if (!isAtomic) 1197 return false; 1198 1199 Scope = CrossThread; 1200 if (EatIfPresent(lltok::kw_singlethread)) 1201 Scope = SingleThread; 1202 switch (Lex.getKind()) { 1203 default: return TokError("Expected ordering on atomic instruction"); 1204 case lltok::kw_unordered: Ordering = Unordered; break; 1205 case lltok::kw_monotonic: Ordering = Monotonic; break; 1206 case lltok::kw_acquire: Ordering = Acquire; break; 1207 case lltok::kw_release: Ordering = Release; break; 1208 case lltok::kw_acq_rel: Ordering = AcquireRelease; break; 1209 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break; 1210 } 1211 Lex.Lex(); 1212 return false; 1213} 1214 1215/// ParseOptionalStackAlignment 1216/// ::= /* empty */ 1217/// ::= 'alignstack' '(' 4 ')' 1218bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) { 1219 Alignment = 0; 1220 if (!EatIfPresent(lltok::kw_alignstack)) 1221 return false; 1222 LocTy ParenLoc = Lex.getLoc(); 1223 if (!EatIfPresent(lltok::lparen)) 1224 return Error(ParenLoc, "expected '('"); 1225 LocTy AlignLoc = Lex.getLoc(); 1226 if (ParseUInt32(Alignment)) return true; 1227 ParenLoc = Lex.getLoc(); 1228 if (!EatIfPresent(lltok::rparen)) 1229 return Error(ParenLoc, "expected ')'"); 1230 if (!isPowerOf2_32(Alignment)) 1231 return Error(AlignLoc, "stack alignment is not a power of two"); 1232 return false; 1233} 1234 1235/// ParseIndexList - This parses the index list for an insert/extractvalue 1236/// instruction. This sets AteExtraComma in the case where we eat an extra 1237/// comma at the end of the line and find that it is followed by metadata. 1238/// Clients that don't allow metadata can call the version of this function that 1239/// only takes one argument. 1240/// 1241/// ParseIndexList 1242/// ::= (',' uint32)+ 1243/// 1244bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices, 1245 bool &AteExtraComma) { 1246 AteExtraComma = false; 1247 1248 if (Lex.getKind() != lltok::comma) 1249 return TokError("expected ',' as start of index list"); 1250 1251 while (EatIfPresent(lltok::comma)) { 1252 if (Lex.getKind() == lltok::MetadataVar) { 1253 AteExtraComma = true; 1254 return false; 1255 } 1256 unsigned Idx = 0; 1257 if (ParseUInt32(Idx)) return true; 1258 Indices.push_back(Idx); 1259 } 1260 1261 return false; 1262} 1263 1264//===----------------------------------------------------------------------===// 1265// Type Parsing. 1266//===----------------------------------------------------------------------===// 1267 1268/// ParseType - Parse a type. 1269bool LLParser::ParseType(Type *&Result, bool AllowVoid) { 1270 SMLoc TypeLoc = Lex.getLoc(); 1271 switch (Lex.getKind()) { 1272 default: 1273 return TokError("expected type"); 1274 case lltok::Type: 1275 // Type ::= 'float' | 'void' (etc) 1276 Result = Lex.getTyVal(); 1277 Lex.Lex(); 1278 break; 1279 case lltok::lbrace: 1280 // Type ::= StructType 1281 if (ParseAnonStructType(Result, false)) 1282 return true; 1283 break; 1284 case lltok::lsquare: 1285 // Type ::= '[' ... ']' 1286 Lex.Lex(); // eat the lsquare. 1287 if (ParseArrayVectorType(Result, false)) 1288 return true; 1289 break; 1290 case lltok::less: // Either vector or packed struct. 1291 // Type ::= '<' ... '>' 1292 Lex.Lex(); 1293 if (Lex.getKind() == lltok::lbrace) { 1294 if (ParseAnonStructType(Result, true) || 1295 ParseToken(lltok::greater, "expected '>' at end of packed struct")) 1296 return true; 1297 } else if (ParseArrayVectorType(Result, true)) 1298 return true; 1299 break; 1300 case lltok::LocalVar: { 1301 // Type ::= %foo 1302 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 1303 1304 // If the type hasn't been defined yet, create a forward definition and 1305 // remember where that forward def'n was seen (in case it never is defined). 1306 if (Entry.first == 0) { 1307 Entry.first = StructType::create(Context, Lex.getStrVal()); 1308 Entry.second = Lex.getLoc(); 1309 } 1310 Result = Entry.first; 1311 Lex.Lex(); 1312 break; 1313 } 1314 1315 case lltok::LocalVarID: { 1316 // Type ::= %4 1317 if (Lex.getUIntVal() >= NumberedTypes.size()) 1318 NumberedTypes.resize(Lex.getUIntVal()+1); 1319 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 1320 1321 // If the type hasn't been defined yet, create a forward definition and 1322 // remember where that forward def'n was seen (in case it never is defined). 1323 if (Entry.first == 0) { 1324 Entry.first = StructType::create(Context); 1325 Entry.second = Lex.getLoc(); 1326 } 1327 Result = Entry.first; 1328 Lex.Lex(); 1329 break; 1330 } 1331 } 1332 1333 // Parse the type suffixes. 1334 while (1) { 1335 switch (Lex.getKind()) { 1336 // End of type. 1337 default: 1338 if (!AllowVoid && Result->isVoidTy()) 1339 return Error(TypeLoc, "void type only allowed for function results"); 1340 return false; 1341 1342 // Type ::= Type '*' 1343 case lltok::star: 1344 if (Result->isLabelTy()) 1345 return TokError("basic block pointers are invalid"); 1346 if (Result->isVoidTy()) 1347 return TokError("pointers to void are invalid - use i8* instead"); 1348 if (!PointerType::isValidElementType(Result)) 1349 return TokError("pointer to this type is invalid"); 1350 Result = PointerType::getUnqual(Result); 1351 Lex.Lex(); 1352 break; 1353 1354 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 1355 case lltok::kw_addrspace: { 1356 if (Result->isLabelTy()) 1357 return TokError("basic block pointers are invalid"); 1358 if (Result->isVoidTy()) 1359 return TokError("pointers to void are invalid; use i8* instead"); 1360 if (!PointerType::isValidElementType(Result)) 1361 return TokError("pointer to this type is invalid"); 1362 unsigned AddrSpace; 1363 if (ParseOptionalAddrSpace(AddrSpace) || 1364 ParseToken(lltok::star, "expected '*' in address space")) 1365 return true; 1366 1367 Result = PointerType::get(Result, AddrSpace); 1368 break; 1369 } 1370 1371 /// Types '(' ArgTypeListI ')' OptFuncAttrs 1372 case lltok::lparen: 1373 if (ParseFunctionType(Result)) 1374 return true; 1375 break; 1376 } 1377 } 1378} 1379 1380/// ParseParameterList 1381/// ::= '(' ')' 1382/// ::= '(' Arg (',' Arg)* ')' 1383/// Arg 1384/// ::= Type OptionalAttributes Value OptionalAttributes 1385bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 1386 PerFunctionState &PFS) { 1387 if (ParseToken(lltok::lparen, "expected '(' in call")) 1388 return true; 1389 1390 while (Lex.getKind() != lltok::rparen) { 1391 // If this isn't the first argument, we need a comma. 1392 if (!ArgList.empty() && 1393 ParseToken(lltok::comma, "expected ',' in argument list")) 1394 return true; 1395 1396 // Parse the argument. 1397 LocTy ArgLoc; 1398 Type *ArgTy = 0; 1399 Attributes ArgAttrs1; 1400 Attributes ArgAttrs2; 1401 Value *V; 1402 if (ParseType(ArgTy, ArgLoc)) 1403 return true; 1404 1405 // Otherwise, handle normal operands. 1406 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS)) 1407 return true; 1408 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2)); 1409 } 1410 1411 Lex.Lex(); // Lex the ')'. 1412 return false; 1413} 1414 1415 1416 1417/// ParseArgumentList - Parse the argument list for a function type or function 1418/// prototype. 1419/// ::= '(' ArgTypeListI ')' 1420/// ArgTypeListI 1421/// ::= /*empty*/ 1422/// ::= '...' 1423/// ::= ArgTypeList ',' '...' 1424/// ::= ArgType (',' ArgType)* 1425/// 1426bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 1427 bool &isVarArg){ 1428 isVarArg = false; 1429 assert(Lex.getKind() == lltok::lparen); 1430 Lex.Lex(); // eat the (. 1431 1432 if (Lex.getKind() == lltok::rparen) { 1433 // empty 1434 } else if (Lex.getKind() == lltok::dotdotdot) { 1435 isVarArg = true; 1436 Lex.Lex(); 1437 } else { 1438 LocTy TypeLoc = Lex.getLoc(); 1439 Type *ArgTy = 0; 1440 Attributes Attrs; 1441 std::string Name; 1442 1443 if (ParseType(ArgTy) || 1444 ParseOptionalAttrs(Attrs, 0)) return true; 1445 1446 if (ArgTy->isVoidTy()) 1447 return Error(TypeLoc, "argument can not have void type"); 1448 1449 if (Lex.getKind() == lltok::LocalVar) { 1450 Name = Lex.getStrVal(); 1451 Lex.Lex(); 1452 } 1453 1454 if (!FunctionType::isValidArgumentType(ArgTy)) 1455 return Error(TypeLoc, "invalid type for function argument"); 1456 1457 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); 1458 1459 while (EatIfPresent(lltok::comma)) { 1460 // Handle ... at end of arg list. 1461 if (EatIfPresent(lltok::dotdotdot)) { 1462 isVarArg = true; 1463 break; 1464 } 1465 1466 // Otherwise must be an argument type. 1467 TypeLoc = Lex.getLoc(); 1468 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true; 1469 1470 if (ArgTy->isVoidTy()) 1471 return Error(TypeLoc, "argument can not have void type"); 1472 1473 if (Lex.getKind() == lltok::LocalVar) { 1474 Name = Lex.getStrVal(); 1475 Lex.Lex(); 1476 } else { 1477 Name = ""; 1478 } 1479 1480 if (!ArgTy->isFirstClassType()) 1481 return Error(TypeLoc, "invalid type for function argument"); 1482 1483 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); 1484 } 1485 } 1486 1487 return ParseToken(lltok::rparen, "expected ')' at end of argument list"); 1488} 1489 1490/// ParseFunctionType 1491/// ::= Type ArgumentList OptionalAttrs 1492bool LLParser::ParseFunctionType(Type *&Result) { 1493 assert(Lex.getKind() == lltok::lparen); 1494 1495 if (!FunctionType::isValidReturnType(Result)) 1496 return TokError("invalid function return type"); 1497 1498 SmallVector<ArgInfo, 8> ArgList; 1499 bool isVarArg; 1500 if (ParseArgumentList(ArgList, isVarArg)) 1501 return true; 1502 1503 // Reject names on the arguments lists. 1504 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 1505 if (!ArgList[i].Name.empty()) 1506 return Error(ArgList[i].Loc, "argument name invalid in function type"); 1507 if (ArgList[i].Attrs) 1508 return Error(ArgList[i].Loc, 1509 "argument attributes invalid in function type"); 1510 } 1511 1512 SmallVector<Type*, 16> ArgListTy; 1513 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 1514 ArgListTy.push_back(ArgList[i].Ty); 1515 1516 Result = FunctionType::get(Result, ArgListTy, isVarArg); 1517 return false; 1518} 1519 1520/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into 1521/// other structs. 1522bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) { 1523 SmallVector<Type*, 8> Elts; 1524 if (ParseStructBody(Elts)) return true; 1525 1526 Result = StructType::get(Context, Elts, Packed); 1527 return false; 1528} 1529 1530/// ParseStructDefinition - Parse a struct in a 'type' definition. 1531bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name, 1532 std::pair<Type*, LocTy> &Entry, 1533 Type *&ResultTy) { 1534 // If the type was already defined, diagnose the redefinition. 1535 if (Entry.first && !Entry.second.isValid()) 1536 return Error(TypeLoc, "redefinition of type"); 1537 1538 // If we have opaque, just return without filling in the definition for the 1539 // struct. This counts as a definition as far as the .ll file goes. 1540 if (EatIfPresent(lltok::kw_opaque)) { 1541 // This type is being defined, so clear the location to indicate this. 1542 Entry.second = SMLoc(); 1543 1544 // If this type number has never been uttered, create it. 1545 if (Entry.first == 0) 1546 Entry.first = StructType::create(Context, Name); 1547 ResultTy = Entry.first; 1548 return false; 1549 } 1550 1551 // If the type starts with '<', then it is either a packed struct or a vector. 1552 bool isPacked = EatIfPresent(lltok::less); 1553 1554 // If we don't have a struct, then we have a random type alias, which we 1555 // accept for compatibility with old files. These types are not allowed to be 1556 // forward referenced and not allowed to be recursive. 1557 if (Lex.getKind() != lltok::lbrace) { 1558 if (Entry.first) 1559 return Error(TypeLoc, "forward references to non-struct type"); 1560 1561 ResultTy = 0; 1562 if (isPacked) 1563 return ParseArrayVectorType(ResultTy, true); 1564 return ParseType(ResultTy); 1565 } 1566 1567 // This type is being defined, so clear the location to indicate this. 1568 Entry.second = SMLoc(); 1569 1570 // If this type number has never been uttered, create it. 1571 if (Entry.first == 0) 1572 Entry.first = StructType::create(Context, Name); 1573 1574 StructType *STy = cast<StructType>(Entry.first); 1575 1576 SmallVector<Type*, 8> Body; 1577 if (ParseStructBody(Body) || 1578 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct"))) 1579 return true; 1580 1581 STy->setBody(Body, isPacked); 1582 ResultTy = STy; 1583 return false; 1584} 1585 1586 1587/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere. 1588/// StructType 1589/// ::= '{' '}' 1590/// ::= '{' Type (',' Type)* '}' 1591/// ::= '<' '{' '}' '>' 1592/// ::= '<' '{' Type (',' Type)* '}' '>' 1593bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) { 1594 assert(Lex.getKind() == lltok::lbrace); 1595 Lex.Lex(); // Consume the '{' 1596 1597 // Handle the empty struct. 1598 if (EatIfPresent(lltok::rbrace)) 1599 return false; 1600 1601 LocTy EltTyLoc = Lex.getLoc(); 1602 Type *Ty = 0; 1603 if (ParseType(Ty)) return true; 1604 Body.push_back(Ty); 1605 1606 if (!StructType::isValidElementType(Ty)) 1607 return Error(EltTyLoc, "invalid element type for struct"); 1608 1609 while (EatIfPresent(lltok::comma)) { 1610 EltTyLoc = Lex.getLoc(); 1611 if (ParseType(Ty)) return true; 1612 1613 if (!StructType::isValidElementType(Ty)) 1614 return Error(EltTyLoc, "invalid element type for struct"); 1615 1616 Body.push_back(Ty); 1617 } 1618 1619 return ParseToken(lltok::rbrace, "expected '}' at end of struct"); 1620} 1621 1622/// ParseArrayVectorType - Parse an array or vector type, assuming the first 1623/// token has already been consumed. 1624/// Type 1625/// ::= '[' APSINTVAL 'x' Types ']' 1626/// ::= '<' APSINTVAL 'x' Types '>' 1627bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) { 1628 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 1629 Lex.getAPSIntVal().getBitWidth() > 64) 1630 return TokError("expected number in address space"); 1631 1632 LocTy SizeLoc = Lex.getLoc(); 1633 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 1634 Lex.Lex(); 1635 1636 if (ParseToken(lltok::kw_x, "expected 'x' after element count")) 1637 return true; 1638 1639 LocTy TypeLoc = Lex.getLoc(); 1640 Type *EltTy = 0; 1641 if (ParseType(EltTy)) return true; 1642 1643 if (ParseToken(isVector ? lltok::greater : lltok::rsquare, 1644 "expected end of sequential type")) 1645 return true; 1646 1647 if (isVector) { 1648 if (Size == 0) 1649 return Error(SizeLoc, "zero element vector is illegal"); 1650 if ((unsigned)Size != Size) 1651 return Error(SizeLoc, "size too large for vector"); 1652 if (!VectorType::isValidElementType(EltTy)) 1653 return Error(TypeLoc, 1654 "vector element type must be fp, integer or a pointer to these types"); 1655 Result = VectorType::get(EltTy, unsigned(Size)); 1656 } else { 1657 if (!ArrayType::isValidElementType(EltTy)) 1658 return Error(TypeLoc, "invalid array element type"); 1659 Result = ArrayType::get(EltTy, Size); 1660 } 1661 return false; 1662} 1663 1664//===----------------------------------------------------------------------===// 1665// Function Semantic Analysis. 1666//===----------------------------------------------------------------------===// 1667 1668LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 1669 int functionNumber) 1670 : P(p), F(f), FunctionNumber(functionNumber) { 1671 1672 // Insert unnamed arguments into the NumberedVals list. 1673 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 1674 AI != E; ++AI) 1675 if (!AI->hasName()) 1676 NumberedVals.push_back(AI); 1677} 1678 1679LLParser::PerFunctionState::~PerFunctionState() { 1680 // If there were any forward referenced non-basicblock values, delete them. 1681 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator 1682 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I) 1683 if (!isa<BasicBlock>(I->second.first)) { 1684 I->second.first->replaceAllUsesWith( 1685 UndefValue::get(I->second.first->getType())); 1686 delete I->second.first; 1687 I->second.first = 0; 1688 } 1689 1690 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator 1691 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I) 1692 if (!isa<BasicBlock>(I->second.first)) { 1693 I->second.first->replaceAllUsesWith( 1694 UndefValue::get(I->second.first->getType())); 1695 delete I->second.first; 1696 I->second.first = 0; 1697 } 1698} 1699 1700bool LLParser::PerFunctionState::FinishFunction() { 1701 // Check to see if someone took the address of labels in this block. 1702 if (!P.ForwardRefBlockAddresses.empty()) { 1703 ValID FunctionID; 1704 if (!F.getName().empty()) { 1705 FunctionID.Kind = ValID::t_GlobalName; 1706 FunctionID.StrVal = F.getName(); 1707 } else { 1708 FunctionID.Kind = ValID::t_GlobalID; 1709 FunctionID.UIntVal = FunctionNumber; 1710 } 1711 1712 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator 1713 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID); 1714 if (FRBAI != P.ForwardRefBlockAddresses.end()) { 1715 // Resolve all these references. 1716 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this)) 1717 return true; 1718 1719 P.ForwardRefBlockAddresses.erase(FRBAI); 1720 } 1721 } 1722 1723 if (!ForwardRefVals.empty()) 1724 return P.Error(ForwardRefVals.begin()->second.second, 1725 "use of undefined value '%" + ForwardRefVals.begin()->first + 1726 "'"); 1727 if (!ForwardRefValIDs.empty()) 1728 return P.Error(ForwardRefValIDs.begin()->second.second, 1729 "use of undefined value '%" + 1730 Twine(ForwardRefValIDs.begin()->first) + "'"); 1731 return false; 1732} 1733 1734 1735/// GetVal - Get a value with the specified name or ID, creating a 1736/// forward reference record if needed. This can return null if the value 1737/// exists but does not have the right type. 1738Value *LLParser::PerFunctionState::GetVal(const std::string &Name, 1739 Type *Ty, LocTy Loc) { 1740 // Look this name up in the normal function symbol table. 1741 Value *Val = F.getValueSymbolTable().lookup(Name); 1742 1743 // If this is a forward reference for the value, see if we already created a 1744 // forward ref record. 1745 if (Val == 0) { 1746 std::map<std::string, std::pair<Value*, LocTy> >::iterator 1747 I = ForwardRefVals.find(Name); 1748 if (I != ForwardRefVals.end()) 1749 Val = I->second.first; 1750 } 1751 1752 // If we have the value in the symbol table or fwd-ref table, return it. 1753 if (Val) { 1754 if (Val->getType() == Ty) return Val; 1755 if (Ty->isLabelTy()) 1756 P.Error(Loc, "'%" + Name + "' is not a basic block"); 1757 else 1758 P.Error(Loc, "'%" + Name + "' defined with type '" + 1759 getTypeString(Val->getType()) + "'"); 1760 return 0; 1761 } 1762 1763 // Don't make placeholders with invalid type. 1764 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) { 1765 P.Error(Loc, "invalid use of a non-first-class type"); 1766 return 0; 1767 } 1768 1769 // Otherwise, create a new forward reference for this value and remember it. 1770 Value *FwdVal; 1771 if (Ty->isLabelTy()) 1772 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 1773 else 1774 FwdVal = new Argument(Ty, Name); 1775 1776 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 1777 return FwdVal; 1778} 1779 1780Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, 1781 LocTy Loc) { 1782 // Look this name up in the normal function symbol table. 1783 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 1784 1785 // If this is a forward reference for the value, see if we already created a 1786 // forward ref record. 1787 if (Val == 0) { 1788 std::map<unsigned, std::pair<Value*, LocTy> >::iterator 1789 I = ForwardRefValIDs.find(ID); 1790 if (I != ForwardRefValIDs.end()) 1791 Val = I->second.first; 1792 } 1793 1794 // If we have the value in the symbol table or fwd-ref table, return it. 1795 if (Val) { 1796 if (Val->getType() == Ty) return Val; 1797 if (Ty->isLabelTy()) 1798 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block"); 1799 else 1800 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" + 1801 getTypeString(Val->getType()) + "'"); 1802 return 0; 1803 } 1804 1805 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) { 1806 P.Error(Loc, "invalid use of a non-first-class type"); 1807 return 0; 1808 } 1809 1810 // Otherwise, create a new forward reference for this value and remember it. 1811 Value *FwdVal; 1812 if (Ty->isLabelTy()) 1813 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 1814 else 1815 FwdVal = new Argument(Ty); 1816 1817 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 1818 return FwdVal; 1819} 1820 1821/// SetInstName - After an instruction is parsed and inserted into its 1822/// basic block, this installs its name. 1823bool LLParser::PerFunctionState::SetInstName(int NameID, 1824 const std::string &NameStr, 1825 LocTy NameLoc, Instruction *Inst) { 1826 // If this instruction has void type, it cannot have a name or ID specified. 1827 if (Inst->getType()->isVoidTy()) { 1828 if (NameID != -1 || !NameStr.empty()) 1829 return P.Error(NameLoc, "instructions returning void cannot have a name"); 1830 return false; 1831 } 1832 1833 // If this was a numbered instruction, verify that the instruction is the 1834 // expected value and resolve any forward references. 1835 if (NameStr.empty()) { 1836 // If neither a name nor an ID was specified, just use the next ID. 1837 if (NameID == -1) 1838 NameID = NumberedVals.size(); 1839 1840 if (unsigned(NameID) != NumberedVals.size()) 1841 return P.Error(NameLoc, "instruction expected to be numbered '%" + 1842 Twine(NumberedVals.size()) + "'"); 1843 1844 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI = 1845 ForwardRefValIDs.find(NameID); 1846 if (FI != ForwardRefValIDs.end()) { 1847 if (FI->second.first->getType() != Inst->getType()) 1848 return P.Error(NameLoc, "instruction forward referenced with type '" + 1849 getTypeString(FI->second.first->getType()) + "'"); 1850 FI->second.first->replaceAllUsesWith(Inst); 1851 delete FI->second.first; 1852 ForwardRefValIDs.erase(FI); 1853 } 1854 1855 NumberedVals.push_back(Inst); 1856 return false; 1857 } 1858 1859 // Otherwise, the instruction had a name. Resolve forward refs and set it. 1860 std::map<std::string, std::pair<Value*, LocTy> >::iterator 1861 FI = ForwardRefVals.find(NameStr); 1862 if (FI != ForwardRefVals.end()) { 1863 if (FI->second.first->getType() != Inst->getType()) 1864 return P.Error(NameLoc, "instruction forward referenced with type '" + 1865 getTypeString(FI->second.first->getType()) + "'"); 1866 FI->second.first->replaceAllUsesWith(Inst); 1867 delete FI->second.first; 1868 ForwardRefVals.erase(FI); 1869 } 1870 1871 // Set the name on the instruction. 1872 Inst->setName(NameStr); 1873 1874 if (Inst->getName() != NameStr) 1875 return P.Error(NameLoc, "multiple definition of local value named '" + 1876 NameStr + "'"); 1877 return false; 1878} 1879 1880/// GetBB - Get a basic block with the specified name or ID, creating a 1881/// forward reference record if needed. 1882BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name, 1883 LocTy Loc) { 1884 return cast_or_null<BasicBlock>(GetVal(Name, 1885 Type::getLabelTy(F.getContext()), Loc)); 1886} 1887 1888BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) { 1889 return cast_or_null<BasicBlock>(GetVal(ID, 1890 Type::getLabelTy(F.getContext()), Loc)); 1891} 1892 1893/// DefineBB - Define the specified basic block, which is either named or 1894/// unnamed. If there is an error, this returns null otherwise it returns 1895/// the block being defined. 1896BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, 1897 LocTy Loc) { 1898 BasicBlock *BB; 1899 if (Name.empty()) 1900 BB = GetBB(NumberedVals.size(), Loc); 1901 else 1902 BB = GetBB(Name, Loc); 1903 if (BB == 0) return 0; // Already diagnosed error. 1904 1905 // Move the block to the end of the function. Forward ref'd blocks are 1906 // inserted wherever they happen to be referenced. 1907 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 1908 1909 // Remove the block from forward ref sets. 1910 if (Name.empty()) { 1911 ForwardRefValIDs.erase(NumberedVals.size()); 1912 NumberedVals.push_back(BB); 1913 } else { 1914 // BB forward references are already in the function symbol table. 1915 ForwardRefVals.erase(Name); 1916 } 1917 1918 return BB; 1919} 1920 1921//===----------------------------------------------------------------------===// 1922// Constants. 1923//===----------------------------------------------------------------------===// 1924 1925/// ParseValID - Parse an abstract value that doesn't necessarily have a 1926/// type implied. For example, if we parse "4" we don't know what integer type 1927/// it has. The value will later be combined with its type and checked for 1928/// sanity. PFS is used to convert function-local operands of metadata (since 1929/// metadata operands are not just parsed here but also converted to values). 1930/// PFS can be null when we are not parsing metadata values inside a function. 1931bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) { 1932 ID.Loc = Lex.getLoc(); 1933 switch (Lex.getKind()) { 1934 default: return TokError("expected value token"); 1935 case lltok::GlobalID: // @42 1936 ID.UIntVal = Lex.getUIntVal(); 1937 ID.Kind = ValID::t_GlobalID; 1938 break; 1939 case lltok::GlobalVar: // @foo 1940 ID.StrVal = Lex.getStrVal(); 1941 ID.Kind = ValID::t_GlobalName; 1942 break; 1943 case lltok::LocalVarID: // %42 1944 ID.UIntVal = Lex.getUIntVal(); 1945 ID.Kind = ValID::t_LocalID; 1946 break; 1947 case lltok::LocalVar: // %foo 1948 ID.StrVal = Lex.getStrVal(); 1949 ID.Kind = ValID::t_LocalName; 1950 break; 1951 case lltok::exclaim: // !42, !{...}, or !"foo" 1952 return ParseMetadataValue(ID, PFS); 1953 case lltok::APSInt: 1954 ID.APSIntVal = Lex.getAPSIntVal(); 1955 ID.Kind = ValID::t_APSInt; 1956 break; 1957 case lltok::APFloat: 1958 ID.APFloatVal = Lex.getAPFloatVal(); 1959 ID.Kind = ValID::t_APFloat; 1960 break; 1961 case lltok::kw_true: 1962 ID.ConstantVal = ConstantInt::getTrue(Context); 1963 ID.Kind = ValID::t_Constant; 1964 break; 1965 case lltok::kw_false: 1966 ID.ConstantVal = ConstantInt::getFalse(Context); 1967 ID.Kind = ValID::t_Constant; 1968 break; 1969 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 1970 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 1971 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 1972 1973 case lltok::lbrace: { 1974 // ValID ::= '{' ConstVector '}' 1975 Lex.Lex(); 1976 SmallVector<Constant*, 16> Elts; 1977 if (ParseGlobalValueVector(Elts) || 1978 ParseToken(lltok::rbrace, "expected end of struct constant")) 1979 return true; 1980 1981 ID.ConstantStructElts = new Constant*[Elts.size()]; 1982 ID.UIntVal = Elts.size(); 1983 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0])); 1984 ID.Kind = ValID::t_ConstantStruct; 1985 return false; 1986 } 1987 case lltok::less: { 1988 // ValID ::= '<' ConstVector '>' --> Vector. 1989 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 1990 Lex.Lex(); 1991 bool isPackedStruct = EatIfPresent(lltok::lbrace); 1992 1993 SmallVector<Constant*, 16> Elts; 1994 LocTy FirstEltLoc = Lex.getLoc(); 1995 if (ParseGlobalValueVector(Elts) || 1996 (isPackedStruct && 1997 ParseToken(lltok::rbrace, "expected end of packed struct")) || 1998 ParseToken(lltok::greater, "expected end of constant")) 1999 return true; 2000 2001 if (isPackedStruct) { 2002 ID.ConstantStructElts = new Constant*[Elts.size()]; 2003 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0])); 2004 ID.UIntVal = Elts.size(); 2005 ID.Kind = ValID::t_PackedConstantStruct; 2006 return false; 2007 } 2008 2009 if (Elts.empty()) 2010 return Error(ID.Loc, "constant vector must not be empty"); 2011 2012 if (!Elts[0]->getType()->isIntegerTy() && 2013 !Elts[0]->getType()->isFloatingPointTy() && 2014 !Elts[0]->getType()->isPointerTy()) 2015 return Error(FirstEltLoc, 2016 "vector elements must have integer, pointer or floating point type"); 2017 2018 // Verify that all the vector elements have the same type. 2019 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 2020 if (Elts[i]->getType() != Elts[0]->getType()) 2021 return Error(FirstEltLoc, 2022 "vector element #" + Twine(i) + 2023 " is not of type '" + getTypeString(Elts[0]->getType())); 2024 2025 ID.ConstantVal = ConstantVector::get(Elts); 2026 ID.Kind = ValID::t_Constant; 2027 return false; 2028 } 2029 case lltok::lsquare: { // Array Constant 2030 Lex.Lex(); 2031 SmallVector<Constant*, 16> Elts; 2032 LocTy FirstEltLoc = Lex.getLoc(); 2033 if (ParseGlobalValueVector(Elts) || 2034 ParseToken(lltok::rsquare, "expected end of array constant")) 2035 return true; 2036 2037 // Handle empty element. 2038 if (Elts.empty()) { 2039 // Use undef instead of an array because it's inconvenient to determine 2040 // the element type at this point, there being no elements to examine. 2041 ID.Kind = ValID::t_EmptyArray; 2042 return false; 2043 } 2044 2045 if (!Elts[0]->getType()->isFirstClassType()) 2046 return Error(FirstEltLoc, "invalid array element type: " + 2047 getTypeString(Elts[0]->getType())); 2048 2049 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 2050 2051 // Verify all elements are correct type! 2052 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 2053 if (Elts[i]->getType() != Elts[0]->getType()) 2054 return Error(FirstEltLoc, 2055 "array element #" + Twine(i) + 2056 " is not of type '" + getTypeString(Elts[0]->getType())); 2057 } 2058 2059 ID.ConstantVal = ConstantArray::get(ATy, Elts); 2060 ID.Kind = ValID::t_Constant; 2061 return false; 2062 } 2063 case lltok::kw_c: // c "foo" 2064 Lex.Lex(); 2065 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 2066 false); 2067 if (ParseToken(lltok::StringConstant, "expected string")) return true; 2068 ID.Kind = ValID::t_Constant; 2069 return false; 2070 2071 case lltok::kw_asm: { 2072 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT 2073 bool HasSideEffect, AlignStack; 2074 Lex.Lex(); 2075 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 2076 ParseOptionalToken(lltok::kw_alignstack, AlignStack) || 2077 ParseStringConstant(ID.StrVal) || 2078 ParseToken(lltok::comma, "expected comma in inline asm expression") || 2079 ParseToken(lltok::StringConstant, "expected constraint string")) 2080 return true; 2081 ID.StrVal2 = Lex.getStrVal(); 2082 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1); 2083 ID.Kind = ValID::t_InlineAsm; 2084 return false; 2085 } 2086 2087 case lltok::kw_blockaddress: { 2088 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 2089 Lex.Lex(); 2090 2091 ValID Fn, Label; 2092 LocTy FnLoc, LabelLoc; 2093 2094 if (ParseToken(lltok::lparen, "expected '(' in block address expression") || 2095 ParseValID(Fn) || 2096 ParseToken(lltok::comma, "expected comma in block address expression")|| 2097 ParseValID(Label) || 2098 ParseToken(lltok::rparen, "expected ')' in block address expression")) 2099 return true; 2100 2101 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 2102 return Error(Fn.Loc, "expected function name in blockaddress"); 2103 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 2104 return Error(Label.Loc, "expected basic block name in blockaddress"); 2105 2106 // Make a global variable as a placeholder for this reference. 2107 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), 2108 false, GlobalValue::InternalLinkage, 2109 0, ""); 2110 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef)); 2111 ID.ConstantVal = FwdRef; 2112 ID.Kind = ValID::t_Constant; 2113 return false; 2114 } 2115 2116 case lltok::kw_trunc: 2117 case lltok::kw_zext: 2118 case lltok::kw_sext: 2119 case lltok::kw_fptrunc: 2120 case lltok::kw_fpext: 2121 case lltok::kw_bitcast: 2122 case lltok::kw_uitofp: 2123 case lltok::kw_sitofp: 2124 case lltok::kw_fptoui: 2125 case lltok::kw_fptosi: 2126 case lltok::kw_inttoptr: 2127 case lltok::kw_ptrtoint: { 2128 unsigned Opc = Lex.getUIntVal(); 2129 Type *DestTy = 0; 2130 Constant *SrcVal; 2131 Lex.Lex(); 2132 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") || 2133 ParseGlobalTypeAndValue(SrcVal) || 2134 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 2135 ParseType(DestTy) || 2136 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 2137 return true; 2138 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 2139 return Error(ID.Loc, "invalid cast opcode for cast from '" + 2140 getTypeString(SrcVal->getType()) + "' to '" + 2141 getTypeString(DestTy) + "'"); 2142 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 2143 SrcVal, DestTy); 2144 ID.Kind = ValID::t_Constant; 2145 return false; 2146 } 2147 case lltok::kw_extractvalue: { 2148 Lex.Lex(); 2149 Constant *Val; 2150 SmallVector<unsigned, 4> Indices; 2151 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")|| 2152 ParseGlobalTypeAndValue(Val) || 2153 ParseIndexList(Indices) || 2154 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 2155 return true; 2156 2157 if (!Val->getType()->isAggregateType()) 2158 return Error(ID.Loc, "extractvalue operand must be aggregate type"); 2159 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 2160 return Error(ID.Loc, "invalid indices for extractvalue"); 2161 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 2162 ID.Kind = ValID::t_Constant; 2163 return false; 2164 } 2165 case lltok::kw_insertvalue: { 2166 Lex.Lex(); 2167 Constant *Val0, *Val1; 2168 SmallVector<unsigned, 4> Indices; 2169 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")|| 2170 ParseGlobalTypeAndValue(Val0) || 2171 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")|| 2172 ParseGlobalTypeAndValue(Val1) || 2173 ParseIndexList(Indices) || 2174 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 2175 return true; 2176 if (!Val0->getType()->isAggregateType()) 2177 return Error(ID.Loc, "insertvalue operand must be aggregate type"); 2178 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices)) 2179 return Error(ID.Loc, "invalid indices for insertvalue"); 2180 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 2181 ID.Kind = ValID::t_Constant; 2182 return false; 2183 } 2184 case lltok::kw_icmp: 2185 case lltok::kw_fcmp: { 2186 unsigned PredVal, Opc = Lex.getUIntVal(); 2187 Constant *Val0, *Val1; 2188 Lex.Lex(); 2189 if (ParseCmpPredicate(PredVal, Opc) || 2190 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") || 2191 ParseGlobalTypeAndValue(Val0) || 2192 ParseToken(lltok::comma, "expected comma in compare constantexpr") || 2193 ParseGlobalTypeAndValue(Val1) || 2194 ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) 2195 return true; 2196 2197 if (Val0->getType() != Val1->getType()) 2198 return Error(ID.Loc, "compare operands must have the same type"); 2199 2200 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 2201 2202 if (Opc == Instruction::FCmp) { 2203 if (!Val0->getType()->isFPOrFPVectorTy()) 2204 return Error(ID.Loc, "fcmp requires floating point operands"); 2205 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 2206 } else { 2207 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 2208 if (!Val0->getType()->isIntOrIntVectorTy() && 2209 !Val0->getType()->getScalarType()->isPointerTy()) 2210 return Error(ID.Loc, "icmp requires pointer or integer operands"); 2211 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 2212 } 2213 ID.Kind = ValID::t_Constant; 2214 return false; 2215 } 2216 2217 // Binary Operators. 2218 case lltok::kw_add: 2219 case lltok::kw_fadd: 2220 case lltok::kw_sub: 2221 case lltok::kw_fsub: 2222 case lltok::kw_mul: 2223 case lltok::kw_fmul: 2224 case lltok::kw_udiv: 2225 case lltok::kw_sdiv: 2226 case lltok::kw_fdiv: 2227 case lltok::kw_urem: 2228 case lltok::kw_srem: 2229 case lltok::kw_frem: 2230 case lltok::kw_shl: 2231 case lltok::kw_lshr: 2232 case lltok::kw_ashr: { 2233 bool NUW = false; 2234 bool NSW = false; 2235 bool Exact = false; 2236 unsigned Opc = Lex.getUIntVal(); 2237 Constant *Val0, *Val1; 2238 Lex.Lex(); 2239 LocTy ModifierLoc = Lex.getLoc(); 2240 if (Opc == Instruction::Add || Opc == Instruction::Sub || 2241 Opc == Instruction::Mul || Opc == Instruction::Shl) { 2242 if (EatIfPresent(lltok::kw_nuw)) 2243 NUW = true; 2244 if (EatIfPresent(lltok::kw_nsw)) { 2245 NSW = true; 2246 if (EatIfPresent(lltok::kw_nuw)) 2247 NUW = true; 2248 } 2249 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 2250 Opc == Instruction::LShr || Opc == Instruction::AShr) { 2251 if (EatIfPresent(lltok::kw_exact)) 2252 Exact = true; 2253 } 2254 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") || 2255 ParseGlobalTypeAndValue(Val0) || 2256 ParseToken(lltok::comma, "expected comma in binary constantexpr") || 2257 ParseGlobalTypeAndValue(Val1) || 2258 ParseToken(lltok::rparen, "expected ')' in binary constantexpr")) 2259 return true; 2260 if (Val0->getType() != Val1->getType()) 2261 return Error(ID.Loc, "operands of constexpr must have same type"); 2262 if (!Val0->getType()->isIntOrIntVectorTy()) { 2263 if (NUW) 2264 return Error(ModifierLoc, "nuw only applies to integer operations"); 2265 if (NSW) 2266 return Error(ModifierLoc, "nsw only applies to integer operations"); 2267 } 2268 // Check that the type is valid for the operator. 2269 switch (Opc) { 2270 case Instruction::Add: 2271 case Instruction::Sub: 2272 case Instruction::Mul: 2273 case Instruction::UDiv: 2274 case Instruction::SDiv: 2275 case Instruction::URem: 2276 case Instruction::SRem: 2277 case Instruction::Shl: 2278 case Instruction::AShr: 2279 case Instruction::LShr: 2280 if (!Val0->getType()->isIntOrIntVectorTy()) 2281 return Error(ID.Loc, "constexpr requires integer operands"); 2282 break; 2283 case Instruction::FAdd: 2284 case Instruction::FSub: 2285 case Instruction::FMul: 2286 case Instruction::FDiv: 2287 case Instruction::FRem: 2288 if (!Val0->getType()->isFPOrFPVectorTy()) 2289 return Error(ID.Loc, "constexpr requires fp operands"); 2290 break; 2291 default: llvm_unreachable("Unknown binary operator!"); 2292 } 2293 unsigned Flags = 0; 2294 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 2295 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 2296 if (Exact) Flags |= PossiblyExactOperator::IsExact; 2297 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 2298 ID.ConstantVal = C; 2299 ID.Kind = ValID::t_Constant; 2300 return false; 2301 } 2302 2303 // Logical Operations 2304 case lltok::kw_and: 2305 case lltok::kw_or: 2306 case lltok::kw_xor: { 2307 unsigned Opc = Lex.getUIntVal(); 2308 Constant *Val0, *Val1; 2309 Lex.Lex(); 2310 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") || 2311 ParseGlobalTypeAndValue(Val0) || 2312 ParseToken(lltok::comma, "expected comma in logical constantexpr") || 2313 ParseGlobalTypeAndValue(Val1) || 2314 ParseToken(lltok::rparen, "expected ')' in logical constantexpr")) 2315 return true; 2316 if (Val0->getType() != Val1->getType()) 2317 return Error(ID.Loc, "operands of constexpr must have same type"); 2318 if (!Val0->getType()->isIntOrIntVectorTy()) 2319 return Error(ID.Loc, 2320 "constexpr requires integer or integer vector operands"); 2321 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 2322 ID.Kind = ValID::t_Constant; 2323 return false; 2324 } 2325 2326 case lltok::kw_getelementptr: 2327 case lltok::kw_shufflevector: 2328 case lltok::kw_insertelement: 2329 case lltok::kw_extractelement: 2330 case lltok::kw_select: { 2331 unsigned Opc = Lex.getUIntVal(); 2332 SmallVector<Constant*, 16> Elts; 2333 bool InBounds = false; 2334 Lex.Lex(); 2335 if (Opc == Instruction::GetElementPtr) 2336 InBounds = EatIfPresent(lltok::kw_inbounds); 2337 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") || 2338 ParseGlobalValueVector(Elts) || 2339 ParseToken(lltok::rparen, "expected ')' in constantexpr")) 2340 return true; 2341 2342 if (Opc == Instruction::GetElementPtr) { 2343 if (Elts.size() == 0 || 2344 !Elts[0]->getType()->getScalarType()->isPointerTy()) 2345 return Error(ID.Loc, "getelementptr requires pointer operand"); 2346 2347 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2348 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices)) 2349 return Error(ID.Loc, "invalid indices for getelementptr"); 2350 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices, 2351 InBounds); 2352 } else if (Opc == Instruction::Select) { 2353 if (Elts.size() != 3) 2354 return Error(ID.Loc, "expected three operands to select"); 2355 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 2356 Elts[2])) 2357 return Error(ID.Loc, Reason); 2358 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 2359 } else if (Opc == Instruction::ShuffleVector) { 2360 if (Elts.size() != 3) 2361 return Error(ID.Loc, "expected three operands to shufflevector"); 2362 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 2363 return Error(ID.Loc, "invalid operands to shufflevector"); 2364 ID.ConstantVal = 2365 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); 2366 } else if (Opc == Instruction::ExtractElement) { 2367 if (Elts.size() != 2) 2368 return Error(ID.Loc, "expected two operands to extractelement"); 2369 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 2370 return Error(ID.Loc, "invalid extractelement operands"); 2371 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 2372 } else { 2373 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 2374 if (Elts.size() != 3) 2375 return Error(ID.Loc, "expected three operands to insertelement"); 2376 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 2377 return Error(ID.Loc, "invalid insertelement operands"); 2378 ID.ConstantVal = 2379 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 2380 } 2381 2382 ID.Kind = ValID::t_Constant; 2383 return false; 2384 } 2385 } 2386 2387 Lex.Lex(); 2388 return false; 2389} 2390 2391/// ParseGlobalValue - Parse a global value with the specified type. 2392bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) { 2393 C = 0; 2394 ValID ID; 2395 Value *V = NULL; 2396 bool Parsed = ParseValID(ID) || 2397 ConvertValIDToValue(Ty, ID, V, NULL); 2398 if (V && !(C = dyn_cast<Constant>(V))) 2399 return Error(ID.Loc, "global values must be constants"); 2400 return Parsed; 2401} 2402 2403bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 2404 Type *Ty = 0; 2405 return ParseType(Ty) || 2406 ParseGlobalValue(Ty, V); 2407} 2408 2409/// ParseGlobalValueVector 2410/// ::= /*empty*/ 2411/// ::= TypeAndValue (',' TypeAndValue)* 2412bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) { 2413 // Empty list. 2414 if (Lex.getKind() == lltok::rbrace || 2415 Lex.getKind() == lltok::rsquare || 2416 Lex.getKind() == lltok::greater || 2417 Lex.getKind() == lltok::rparen) 2418 return false; 2419 2420 Constant *C; 2421 if (ParseGlobalTypeAndValue(C)) return true; 2422 Elts.push_back(C); 2423 2424 while (EatIfPresent(lltok::comma)) { 2425 if (ParseGlobalTypeAndValue(C)) return true; 2426 Elts.push_back(C); 2427 } 2428 2429 return false; 2430} 2431 2432bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) { 2433 assert(Lex.getKind() == lltok::lbrace); 2434 Lex.Lex(); 2435 2436 SmallVector<Value*, 16> Elts; 2437 if (ParseMDNodeVector(Elts, PFS) || 2438 ParseToken(lltok::rbrace, "expected end of metadata node")) 2439 return true; 2440 2441 ID.MDNodeVal = MDNode::get(Context, Elts); 2442 ID.Kind = ValID::t_MDNode; 2443 return false; 2444} 2445 2446/// ParseMetadataValue 2447/// ::= !42 2448/// ::= !{...} 2449/// ::= !"string" 2450bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) { 2451 assert(Lex.getKind() == lltok::exclaim); 2452 Lex.Lex(); 2453 2454 // MDNode: 2455 // !{ ... } 2456 if (Lex.getKind() == lltok::lbrace) 2457 return ParseMetadataListValue(ID, PFS); 2458 2459 // Standalone metadata reference 2460 // !42 2461 if (Lex.getKind() == lltok::APSInt) { 2462 if (ParseMDNodeID(ID.MDNodeVal)) return true; 2463 ID.Kind = ValID::t_MDNode; 2464 return false; 2465 } 2466 2467 // MDString: 2468 // ::= '!' STRINGCONSTANT 2469 if (ParseMDString(ID.MDStringVal)) return true; 2470 ID.Kind = ValID::t_MDString; 2471 return false; 2472} 2473 2474 2475//===----------------------------------------------------------------------===// 2476// Function Parsing. 2477//===----------------------------------------------------------------------===// 2478 2479bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V, 2480 PerFunctionState *PFS) { 2481 if (Ty->isFunctionTy()) 2482 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 2483 2484 switch (ID.Kind) { 2485 case ValID::t_LocalID: 2486 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 2487 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc); 2488 return (V == 0); 2489 case ValID::t_LocalName: 2490 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 2491 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc); 2492 return (V == 0); 2493 case ValID::t_InlineAsm: { 2494 PointerType *PTy = dyn_cast<PointerType>(Ty); 2495 FunctionType *FTy = 2496 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0; 2497 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) 2498 return Error(ID.Loc, "invalid type for inline asm constraint string"); 2499 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1); 2500 return false; 2501 } 2502 case ValID::t_MDNode: 2503 if (!Ty->isMetadataTy()) 2504 return Error(ID.Loc, "metadata value must have metadata type"); 2505 V = ID.MDNodeVal; 2506 return false; 2507 case ValID::t_MDString: 2508 if (!Ty->isMetadataTy()) 2509 return Error(ID.Loc, "metadata value must have metadata type"); 2510 V = ID.MDStringVal; 2511 return false; 2512 case ValID::t_GlobalName: 2513 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc); 2514 return V == 0; 2515 case ValID::t_GlobalID: 2516 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc); 2517 return V == 0; 2518 case ValID::t_APSInt: 2519 if (!Ty->isIntegerTy()) 2520 return Error(ID.Loc, "integer constant must have integer type"); 2521 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 2522 V = ConstantInt::get(Context, ID.APSIntVal); 2523 return false; 2524 case ValID::t_APFloat: 2525 if (!Ty->isFloatingPointTy() || 2526 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 2527 return Error(ID.Loc, "floating point constant invalid for type"); 2528 2529 // The lexer has no type info, so builds all half, float, and double FP 2530 // constants as double. Fix this here. Long double does not need this. 2531 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) { 2532 bool Ignored; 2533 if (Ty->isHalfTy()) 2534 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, 2535 &Ignored); 2536 else if (Ty->isFloatTy()) 2537 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, 2538 &Ignored); 2539 } 2540 V = ConstantFP::get(Context, ID.APFloatVal); 2541 2542 if (V->getType() != Ty) 2543 return Error(ID.Loc, "floating point constant does not have type '" + 2544 getTypeString(Ty) + "'"); 2545 2546 return false; 2547 case ValID::t_Null: 2548 if (!Ty->isPointerTy()) 2549 return Error(ID.Loc, "null must be a pointer type"); 2550 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 2551 return false; 2552 case ValID::t_Undef: 2553 // FIXME: LabelTy should not be a first-class type. 2554 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 2555 return Error(ID.Loc, "invalid type for undef constant"); 2556 V = UndefValue::get(Ty); 2557 return false; 2558 case ValID::t_EmptyArray: 2559 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 2560 return Error(ID.Loc, "invalid empty array initializer"); 2561 V = UndefValue::get(Ty); 2562 return false; 2563 case ValID::t_Zero: 2564 // FIXME: LabelTy should not be a first-class type. 2565 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 2566 return Error(ID.Loc, "invalid type for null constant"); 2567 V = Constant::getNullValue(Ty); 2568 return false; 2569 case ValID::t_Constant: 2570 if (ID.ConstantVal->getType() != Ty) 2571 return Error(ID.Loc, "constant expression type mismatch"); 2572 2573 V = ID.ConstantVal; 2574 return false; 2575 case ValID::t_ConstantStruct: 2576 case ValID::t_PackedConstantStruct: 2577 if (StructType *ST = dyn_cast<StructType>(Ty)) { 2578 if (ST->getNumElements() != ID.UIntVal) 2579 return Error(ID.Loc, 2580 "initializer with struct type has wrong # elements"); 2581 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 2582 return Error(ID.Loc, "packed'ness of initializer and type don't match"); 2583 2584 // Verify that the elements are compatible with the structtype. 2585 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 2586 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 2587 return Error(ID.Loc, "element " + Twine(i) + 2588 " of struct initializer doesn't match struct element type"); 2589 2590 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts, 2591 ID.UIntVal)); 2592 } else 2593 return Error(ID.Loc, "constant expression type mismatch"); 2594 return false; 2595 } 2596 llvm_unreachable("Invalid ValID"); 2597} 2598 2599bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 2600 V = 0; 2601 ValID ID; 2602 return ParseValID(ID, PFS) || 2603 ConvertValIDToValue(Ty, ID, V, PFS); 2604} 2605 2606bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) { 2607 Type *Ty = 0; 2608 return ParseType(Ty) || 2609 ParseValue(Ty, V, PFS); 2610} 2611 2612bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 2613 PerFunctionState &PFS) { 2614 Value *V; 2615 Loc = Lex.getLoc(); 2616 if (ParseTypeAndValue(V, PFS)) return true; 2617 if (!isa<BasicBlock>(V)) 2618 return Error(Loc, "expected a basic block"); 2619 BB = cast<BasicBlock>(V); 2620 return false; 2621} 2622 2623 2624/// FunctionHeader 2625/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs 2626/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection 2627/// OptionalAlign OptGC 2628bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 2629 // Parse the linkage. 2630 LocTy LinkageLoc = Lex.getLoc(); 2631 unsigned Linkage; 2632 2633 unsigned Visibility; 2634 Attributes RetAttrs; 2635 CallingConv::ID CC; 2636 Type *RetType = 0; 2637 LocTy RetTypeLoc = Lex.getLoc(); 2638 if (ParseOptionalLinkage(Linkage) || 2639 ParseOptionalVisibility(Visibility) || 2640 ParseOptionalCallingConv(CC) || 2641 ParseOptionalAttrs(RetAttrs, 1) || 2642 ParseType(RetType, RetTypeLoc, true /*void allowed*/)) 2643 return true; 2644 2645 // Verify that the linkage is ok. 2646 switch ((GlobalValue::LinkageTypes)Linkage) { 2647 case GlobalValue::ExternalLinkage: 2648 break; // always ok. 2649 case GlobalValue::DLLImportLinkage: 2650 case GlobalValue::ExternalWeakLinkage: 2651 if (isDefine) 2652 return Error(LinkageLoc, "invalid linkage for function definition"); 2653 break; 2654 case GlobalValue::PrivateLinkage: 2655 case GlobalValue::LinkerPrivateLinkage: 2656 case GlobalValue::LinkerPrivateWeakLinkage: 2657 case GlobalValue::InternalLinkage: 2658 case GlobalValue::AvailableExternallyLinkage: 2659 case GlobalValue::LinkOnceAnyLinkage: 2660 case GlobalValue::LinkOnceODRLinkage: 2661 case GlobalValue::LinkOnceODRAutoHideLinkage: 2662 case GlobalValue::WeakAnyLinkage: 2663 case GlobalValue::WeakODRLinkage: 2664 case GlobalValue::DLLExportLinkage: 2665 if (!isDefine) 2666 return Error(LinkageLoc, "invalid linkage for function declaration"); 2667 break; 2668 case GlobalValue::AppendingLinkage: 2669 case GlobalValue::CommonLinkage: 2670 return Error(LinkageLoc, "invalid function linkage type"); 2671 } 2672 2673 if (!FunctionType::isValidReturnType(RetType)) 2674 return Error(RetTypeLoc, "invalid function return type"); 2675 2676 LocTy NameLoc = Lex.getLoc(); 2677 2678 std::string FunctionName; 2679 if (Lex.getKind() == lltok::GlobalVar) { 2680 FunctionName = Lex.getStrVal(); 2681 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 2682 unsigned NameID = Lex.getUIntVal(); 2683 2684 if (NameID != NumberedVals.size()) 2685 return TokError("function expected to be numbered '%" + 2686 Twine(NumberedVals.size()) + "'"); 2687 } else { 2688 return TokError("expected function name"); 2689 } 2690 2691 Lex.Lex(); 2692 2693 if (Lex.getKind() != lltok::lparen) 2694 return TokError("expected '(' in function argument list"); 2695 2696 SmallVector<ArgInfo, 8> ArgList; 2697 bool isVarArg; 2698 Attributes FuncAttrs; 2699 std::string Section; 2700 unsigned Alignment; 2701 std::string GC; 2702 bool UnnamedAddr; 2703 LocTy UnnamedAddrLoc; 2704 2705 if (ParseArgumentList(ArgList, isVarArg) || 2706 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr, 2707 &UnnamedAddrLoc) || 2708 ParseOptionalAttrs(FuncAttrs, 2) || 2709 (EatIfPresent(lltok::kw_section) && 2710 ParseStringConstant(Section)) || 2711 ParseOptionalAlignment(Alignment) || 2712 (EatIfPresent(lltok::kw_gc) && 2713 ParseStringConstant(GC))) 2714 return true; 2715 2716 // If the alignment was parsed as an attribute, move to the alignment field. 2717 if (FuncAttrs & Attribute::Alignment) { 2718 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs); 2719 FuncAttrs &= ~Attribute::Alignment; 2720 } 2721 2722 // Okay, if we got here, the function is syntactically valid. Convert types 2723 // and do semantic checks. 2724 std::vector<Type*> ParamTypeList; 2725 SmallVector<AttributeWithIndex, 8> Attrs; 2726 2727 if (RetAttrs != Attribute::None) 2728 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 2729 2730 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2731 ParamTypeList.push_back(ArgList[i].Ty); 2732 if (ArgList[i].Attrs != Attribute::None) 2733 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 2734 } 2735 2736 if (FuncAttrs != Attribute::None) 2737 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs)); 2738 2739 AttrListPtr PAL = AttrListPtr::get(Attrs); 2740 2741 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy()) 2742 return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 2743 2744 FunctionType *FT = 2745 FunctionType::get(RetType, ParamTypeList, isVarArg); 2746 PointerType *PFT = PointerType::getUnqual(FT); 2747 2748 Fn = 0; 2749 if (!FunctionName.empty()) { 2750 // If this was a definition of a forward reference, remove the definition 2751 // from the forward reference table and fill in the forward ref. 2752 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI = 2753 ForwardRefVals.find(FunctionName); 2754 if (FRVI != ForwardRefVals.end()) { 2755 Fn = M->getFunction(FunctionName); 2756 if (Fn->getType() != PFT) 2757 return Error(FRVI->second.second, "invalid forward reference to " 2758 "function '" + FunctionName + "' with wrong type!"); 2759 2760 ForwardRefVals.erase(FRVI); 2761 } else if ((Fn = M->getFunction(FunctionName))) { 2762 // Reject redefinitions. 2763 return Error(NameLoc, "invalid redefinition of function '" + 2764 FunctionName + "'"); 2765 } else if (M->getNamedValue(FunctionName)) { 2766 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 2767 } 2768 2769 } else { 2770 // If this is a definition of a forward referenced function, make sure the 2771 // types agree. 2772 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I 2773 = ForwardRefValIDs.find(NumberedVals.size()); 2774 if (I != ForwardRefValIDs.end()) { 2775 Fn = cast<Function>(I->second.first); 2776 if (Fn->getType() != PFT) 2777 return Error(NameLoc, "type of definition and forward reference of '@" + 2778 Twine(NumberedVals.size()) + "' disagree"); 2779 ForwardRefValIDs.erase(I); 2780 } 2781 } 2782 2783 if (Fn == 0) 2784 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M); 2785 else // Move the forward-reference to the correct spot in the module. 2786 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 2787 2788 if (FunctionName.empty()) 2789 NumberedVals.push_back(Fn); 2790 2791 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 2792 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 2793 Fn->setCallingConv(CC); 2794 Fn->setAttributes(PAL); 2795 Fn->setUnnamedAddr(UnnamedAddr); 2796 Fn->setAlignment(Alignment); 2797 Fn->setSection(Section); 2798 if (!GC.empty()) Fn->setGC(GC.c_str()); 2799 2800 // Add all of the arguments we parsed to the function. 2801 Function::arg_iterator ArgIt = Fn->arg_begin(); 2802 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 2803 // If the argument has a name, insert it into the argument symbol table. 2804 if (ArgList[i].Name.empty()) continue; 2805 2806 // Set the name, if it conflicted, it will be auto-renamed. 2807 ArgIt->setName(ArgList[i].Name); 2808 2809 if (ArgIt->getName() != ArgList[i].Name) 2810 return Error(ArgList[i].Loc, "redefinition of argument '%" + 2811 ArgList[i].Name + "'"); 2812 } 2813 2814 return false; 2815} 2816 2817 2818/// ParseFunctionBody 2819/// ::= '{' BasicBlock+ '}' 2820/// 2821bool LLParser::ParseFunctionBody(Function &Fn) { 2822 if (Lex.getKind() != lltok::lbrace) 2823 return TokError("expected '{' in function body"); 2824 Lex.Lex(); // eat the {. 2825 2826 int FunctionNumber = -1; 2827 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 2828 2829 PerFunctionState PFS(*this, Fn, FunctionNumber); 2830 2831 // We need at least one basic block. 2832 if (Lex.getKind() == lltok::rbrace) 2833 return TokError("function body requires at least one basic block"); 2834 2835 while (Lex.getKind() != lltok::rbrace) 2836 if (ParseBasicBlock(PFS)) return true; 2837 2838 // Eat the }. 2839 Lex.Lex(); 2840 2841 // Verify function is ok. 2842 return PFS.FinishFunction(); 2843} 2844 2845/// ParseBasicBlock 2846/// ::= LabelStr? Instruction* 2847bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { 2848 // If this basic block starts out with a name, remember it. 2849 std::string Name; 2850 LocTy NameLoc = Lex.getLoc(); 2851 if (Lex.getKind() == lltok::LabelStr) { 2852 Name = Lex.getStrVal(); 2853 Lex.Lex(); 2854 } 2855 2856 BasicBlock *BB = PFS.DefineBB(Name, NameLoc); 2857 if (BB == 0) return true; 2858 2859 std::string NameStr; 2860 2861 // Parse the instructions in this block until we get a terminator. 2862 Instruction *Inst; 2863 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst; 2864 do { 2865 // This instruction may have three possibilities for a name: a) none 2866 // specified, b) name specified "%foo =", c) number specified: "%4 =". 2867 LocTy NameLoc = Lex.getLoc(); 2868 int NameID = -1; 2869 NameStr = ""; 2870 2871 if (Lex.getKind() == lltok::LocalVarID) { 2872 NameID = Lex.getUIntVal(); 2873 Lex.Lex(); 2874 if (ParseToken(lltok::equal, "expected '=' after instruction id")) 2875 return true; 2876 } else if (Lex.getKind() == lltok::LocalVar) { 2877 NameStr = Lex.getStrVal(); 2878 Lex.Lex(); 2879 if (ParseToken(lltok::equal, "expected '=' after instruction name")) 2880 return true; 2881 } 2882 2883 switch (ParseInstruction(Inst, BB, PFS)) { 2884 default: llvm_unreachable("Unknown ParseInstruction result!"); 2885 case InstError: return true; 2886 case InstNormal: 2887 BB->getInstList().push_back(Inst); 2888 2889 // With a normal result, we check to see if the instruction is followed by 2890 // a comma and metadata. 2891 if (EatIfPresent(lltok::comma)) 2892 if (ParseInstructionMetadata(Inst, &PFS)) 2893 return true; 2894 break; 2895 case InstExtraComma: 2896 BB->getInstList().push_back(Inst); 2897 2898 // If the instruction parser ate an extra comma at the end of it, it 2899 // *must* be followed by metadata. 2900 if (ParseInstructionMetadata(Inst, &PFS)) 2901 return true; 2902 break; 2903 } 2904 2905 // Set the name on the instruction. 2906 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; 2907 } while (!isa<TerminatorInst>(Inst)); 2908 2909 return false; 2910} 2911 2912//===----------------------------------------------------------------------===// 2913// Instruction Parsing. 2914//===----------------------------------------------------------------------===// 2915 2916/// ParseInstruction - Parse one of the many different instructions. 2917/// 2918int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, 2919 PerFunctionState &PFS) { 2920 lltok::Kind Token = Lex.getKind(); 2921 if (Token == lltok::Eof) 2922 return TokError("found end of file when expecting more instructions"); 2923 LocTy Loc = Lex.getLoc(); 2924 unsigned KeywordVal = Lex.getUIntVal(); 2925 Lex.Lex(); // Eat the keyword. 2926 2927 switch (Token) { 2928 default: return Error(Loc, "expected instruction opcode"); 2929 // Terminator Instructions. 2930 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 2931 case lltok::kw_ret: return ParseRet(Inst, BB, PFS); 2932 case lltok::kw_br: return ParseBr(Inst, PFS); 2933 case lltok::kw_switch: return ParseSwitch(Inst, PFS); 2934 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS); 2935 case lltok::kw_invoke: return ParseInvoke(Inst, PFS); 2936 case lltok::kw_resume: return ParseResume(Inst, PFS); 2937 // Binary Operators. 2938 case lltok::kw_add: 2939 case lltok::kw_sub: 2940 case lltok::kw_mul: 2941 case lltok::kw_shl: { 2942 bool NUW = EatIfPresent(lltok::kw_nuw); 2943 bool NSW = EatIfPresent(lltok::kw_nsw); 2944 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 2945 2946 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true; 2947 2948 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 2949 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 2950 return false; 2951 } 2952 case lltok::kw_fadd: 2953 case lltok::kw_fsub: 2954 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2); 2955 2956 case lltok::kw_sdiv: 2957 case lltok::kw_udiv: 2958 case lltok::kw_lshr: 2959 case lltok::kw_ashr: { 2960 bool Exact = EatIfPresent(lltok::kw_exact); 2961 2962 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true; 2963 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 2964 return false; 2965 } 2966 2967 case lltok::kw_urem: 2968 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1); 2969 case lltok::kw_fdiv: 2970 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2); 2971 case lltok::kw_and: 2972 case lltok::kw_or: 2973 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal); 2974 case lltok::kw_icmp: 2975 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal); 2976 // Casts. 2977 case lltok::kw_trunc: 2978 case lltok::kw_zext: 2979 case lltok::kw_sext: 2980 case lltok::kw_fptrunc: 2981 case lltok::kw_fpext: 2982 case lltok::kw_bitcast: 2983 case lltok::kw_uitofp: 2984 case lltok::kw_sitofp: 2985 case lltok::kw_fptoui: 2986 case lltok::kw_fptosi: 2987 case lltok::kw_inttoptr: 2988 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); 2989 // Other. 2990 case lltok::kw_select: return ParseSelect(Inst, PFS); 2991 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS); 2992 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS); 2993 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS); 2994 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS); 2995 case lltok::kw_phi: return ParsePHI(Inst, PFS); 2996 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS); 2997 case lltok::kw_call: return ParseCall(Inst, PFS, false); 2998 case lltok::kw_tail: return ParseCall(Inst, PFS, true); 2999 // Memory. 3000 case lltok::kw_alloca: return ParseAlloc(Inst, PFS); 3001 case lltok::kw_load: return ParseLoad(Inst, PFS); 3002 case lltok::kw_store: return ParseStore(Inst, PFS); 3003 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS); 3004 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS); 3005 case lltok::kw_fence: return ParseFence(Inst, PFS); 3006 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS); 3007 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS); 3008 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS); 3009 } 3010} 3011 3012/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. 3013bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { 3014 if (Opc == Instruction::FCmp) { 3015 switch (Lex.getKind()) { 3016 default: TokError("expected fcmp predicate (e.g. 'oeq')"); 3017 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 3018 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 3019 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 3020 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 3021 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 3022 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 3023 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 3024 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 3025 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 3026 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 3027 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 3028 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 3029 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 3030 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 3031 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 3032 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 3033 } 3034 } else { 3035 switch (Lex.getKind()) { 3036 default: TokError("expected icmp predicate (e.g. 'eq')"); 3037 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 3038 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 3039 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 3040 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 3041 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 3042 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 3043 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 3044 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 3045 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 3046 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 3047 } 3048 } 3049 Lex.Lex(); 3050 return false; 3051} 3052 3053//===----------------------------------------------------------------------===// 3054// Terminator Instructions. 3055//===----------------------------------------------------------------------===// 3056 3057/// ParseRet - Parse a return instruction. 3058/// ::= 'ret' void (',' !dbg, !1)* 3059/// ::= 'ret' TypeAndValue (',' !dbg, !1)* 3060bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, 3061 PerFunctionState &PFS) { 3062 SMLoc TypeLoc = Lex.getLoc(); 3063 Type *Ty = 0; 3064 if (ParseType(Ty, true /*void allowed*/)) return true; 3065 3066 Type *ResType = PFS.getFunction().getReturnType(); 3067 3068 if (Ty->isVoidTy()) { 3069 if (!ResType->isVoidTy()) 3070 return Error(TypeLoc, "value doesn't match function result type '" + 3071 getTypeString(ResType) + "'"); 3072 3073 Inst = ReturnInst::Create(Context); 3074 return false; 3075 } 3076 3077 Value *RV; 3078 if (ParseValue(Ty, RV, PFS)) return true; 3079 3080 if (ResType != RV->getType()) 3081 return Error(TypeLoc, "value doesn't match function result type '" + 3082 getTypeString(ResType) + "'"); 3083 3084 Inst = ReturnInst::Create(Context, RV); 3085 return false; 3086} 3087 3088 3089/// ParseBr 3090/// ::= 'br' TypeAndValue 3091/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 3092bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { 3093 LocTy Loc, Loc2; 3094 Value *Op0; 3095 BasicBlock *Op1, *Op2; 3096 if (ParseTypeAndValue(Op0, Loc, PFS)) return true; 3097 3098 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 3099 Inst = BranchInst::Create(BB); 3100 return false; 3101 } 3102 3103 if (Op0->getType() != Type::getInt1Ty(Context)) 3104 return Error(Loc, "branch condition must have 'i1' type"); 3105 3106 if (ParseToken(lltok::comma, "expected ',' after branch condition") || 3107 ParseTypeAndBasicBlock(Op1, Loc, PFS) || 3108 ParseToken(lltok::comma, "expected ',' after true destination") || 3109 ParseTypeAndBasicBlock(Op2, Loc2, PFS)) 3110 return true; 3111 3112 Inst = BranchInst::Create(Op1, Op2, Op0); 3113 return false; 3114} 3115 3116/// ParseSwitch 3117/// Instruction 3118/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 3119/// JumpTable 3120/// ::= (TypeAndValue ',' TypeAndValue)* 3121bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 3122 LocTy CondLoc, BBLoc; 3123 Value *Cond; 3124 BasicBlock *DefaultBB; 3125 if (ParseTypeAndValue(Cond, CondLoc, PFS) || 3126 ParseToken(lltok::comma, "expected ',' after switch condition") || 3127 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 3128 ParseToken(lltok::lsquare, "expected '[' with switch table")) 3129 return true; 3130 3131 if (!Cond->getType()->isIntegerTy()) 3132 return Error(CondLoc, "switch condition must have integer type"); 3133 3134 // Parse the jump table pairs. 3135 SmallPtrSet<Value*, 32> SeenCases; 3136 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 3137 while (Lex.getKind() != lltok::rsquare) { 3138 Value *Constant; 3139 BasicBlock *DestBB; 3140 3141 if (ParseTypeAndValue(Constant, CondLoc, PFS) || 3142 ParseToken(lltok::comma, "expected ',' after case value") || 3143 ParseTypeAndBasicBlock(DestBB, PFS)) 3144 return true; 3145 3146 if (!SeenCases.insert(Constant)) 3147 return Error(CondLoc, "duplicate case value in switch"); 3148 if (!isa<ConstantInt>(Constant)) 3149 return Error(CondLoc, "case value is not a constant integer"); 3150 3151 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 3152 } 3153 3154 Lex.Lex(); // Eat the ']'. 3155 3156 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 3157 for (unsigned i = 0, e = Table.size(); i != e; ++i) 3158 SI->addCase(Table[i].first, Table[i].second); 3159 Inst = SI; 3160 return false; 3161} 3162 3163/// ParseIndirectBr 3164/// Instruction 3165/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 3166bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 3167 LocTy AddrLoc; 3168 Value *Address; 3169 if (ParseTypeAndValue(Address, AddrLoc, PFS) || 3170 ParseToken(lltok::comma, "expected ',' after indirectbr address") || 3171 ParseToken(lltok::lsquare, "expected '[' with indirectbr")) 3172 return true; 3173 3174 if (!Address->getType()->isPointerTy()) 3175 return Error(AddrLoc, "indirectbr address must have pointer type"); 3176 3177 // Parse the destination list. 3178 SmallVector<BasicBlock*, 16> DestList; 3179 3180 if (Lex.getKind() != lltok::rsquare) { 3181 BasicBlock *DestBB; 3182 if (ParseTypeAndBasicBlock(DestBB, PFS)) 3183 return true; 3184 DestList.push_back(DestBB); 3185 3186 while (EatIfPresent(lltok::comma)) { 3187 if (ParseTypeAndBasicBlock(DestBB, PFS)) 3188 return true; 3189 DestList.push_back(DestBB); 3190 } 3191 } 3192 3193 if (ParseToken(lltok::rsquare, "expected ']' at end of block list")) 3194 return true; 3195 3196 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 3197 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 3198 IBI->addDestination(DestList[i]); 3199 Inst = IBI; 3200 return false; 3201} 3202 3203 3204/// ParseInvoke 3205/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 3206/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 3207bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 3208 LocTy CallLoc = Lex.getLoc(); 3209 Attributes RetAttrs, FnAttrs; 3210 CallingConv::ID CC; 3211 Type *RetType = 0; 3212 LocTy RetTypeLoc; 3213 ValID CalleeID; 3214 SmallVector<ParamInfo, 16> ArgList; 3215 3216 BasicBlock *NormalBB, *UnwindBB; 3217 if (ParseOptionalCallingConv(CC) || 3218 ParseOptionalAttrs(RetAttrs, 1) || 3219 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 3220 ParseValID(CalleeID) || 3221 ParseParameterList(ArgList, PFS) || 3222 ParseOptionalAttrs(FnAttrs, 2) || 3223 ParseToken(lltok::kw_to, "expected 'to' in invoke") || 3224 ParseTypeAndBasicBlock(NormalBB, PFS) || 3225 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 3226 ParseTypeAndBasicBlock(UnwindBB, PFS)) 3227 return true; 3228 3229 // If RetType is a non-function pointer type, then this is the short syntax 3230 // for the call, which means that RetType is just the return type. Infer the 3231 // rest of the function argument types from the arguments that are present. 3232 PointerType *PFTy = 0; 3233 FunctionType *Ty = 0; 3234 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 3235 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 3236 // Pull out the types of all of the arguments... 3237 std::vector<Type*> ParamTypes; 3238 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 3239 ParamTypes.push_back(ArgList[i].V->getType()); 3240 3241 if (!FunctionType::isValidReturnType(RetType)) 3242 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 3243 3244 Ty = FunctionType::get(RetType, ParamTypes, false); 3245 PFTy = PointerType::getUnqual(Ty); 3246 } 3247 3248 // Look up the callee. 3249 Value *Callee; 3250 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true; 3251 3252 // Set up the Attributes for the function. 3253 SmallVector<AttributeWithIndex, 8> Attrs; 3254 if (RetAttrs != Attribute::None) 3255 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 3256 3257 SmallVector<Value*, 8> Args; 3258 3259 // Loop through FunctionType's arguments and ensure they are specified 3260 // correctly. Also, gather any parameter attributes. 3261 FunctionType::param_iterator I = Ty->param_begin(); 3262 FunctionType::param_iterator E = Ty->param_end(); 3263 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 3264 Type *ExpectedTy = 0; 3265 if (I != E) { 3266 ExpectedTy = *I++; 3267 } else if (!Ty->isVarArg()) { 3268 return Error(ArgList[i].Loc, "too many arguments specified"); 3269 } 3270 3271 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 3272 return Error(ArgList[i].Loc, "argument is not of expected type '" + 3273 getTypeString(ExpectedTy) + "'"); 3274 Args.push_back(ArgList[i].V); 3275 if (ArgList[i].Attrs != Attribute::None) 3276 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 3277 } 3278 3279 if (I != E) 3280 return Error(CallLoc, "not enough parameters specified for call"); 3281 3282 if (FnAttrs != Attribute::None) 3283 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); 3284 3285 // Finish off the Attributes and check them 3286 AttrListPtr PAL = AttrListPtr::get(Attrs); 3287 3288 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args); 3289 II->setCallingConv(CC); 3290 II->setAttributes(PAL); 3291 Inst = II; 3292 return false; 3293} 3294 3295/// ParseResume 3296/// ::= 'resume' TypeAndValue 3297bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) { 3298 Value *Exn; LocTy ExnLoc; 3299 if (ParseTypeAndValue(Exn, ExnLoc, PFS)) 3300 return true; 3301 3302 ResumeInst *RI = ResumeInst::Create(Exn); 3303 Inst = RI; 3304 return false; 3305} 3306 3307//===----------------------------------------------------------------------===// 3308// Binary Operators. 3309//===----------------------------------------------------------------------===// 3310 3311/// ParseArithmetic 3312/// ::= ArithmeticOps TypeAndValue ',' Value 3313/// 3314/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1, 3315/// then any integer operand is allowed, if it is 2, any fp operand is allowed. 3316bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 3317 unsigned Opc, unsigned OperandType) { 3318 LocTy Loc; Value *LHS, *RHS; 3319 if (ParseTypeAndValue(LHS, Loc, PFS) || 3320 ParseToken(lltok::comma, "expected ',' in arithmetic operation") || 3321 ParseValue(LHS->getType(), RHS, PFS)) 3322 return true; 3323 3324 bool Valid; 3325 switch (OperandType) { 3326 default: llvm_unreachable("Unknown operand type!"); 3327 case 0: // int or FP. 3328 Valid = LHS->getType()->isIntOrIntVectorTy() || 3329 LHS->getType()->isFPOrFPVectorTy(); 3330 break; 3331 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break; 3332 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break; 3333 } 3334 3335 if (!Valid) 3336 return Error(Loc, "invalid operand type for instruction"); 3337 3338 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 3339 return false; 3340} 3341 3342/// ParseLogical 3343/// ::= ArithmeticOps TypeAndValue ',' Value { 3344bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, 3345 unsigned Opc) { 3346 LocTy Loc; Value *LHS, *RHS; 3347 if (ParseTypeAndValue(LHS, Loc, PFS) || 3348 ParseToken(lltok::comma, "expected ',' in logical operation") || 3349 ParseValue(LHS->getType(), RHS, PFS)) 3350 return true; 3351 3352 if (!LHS->getType()->isIntOrIntVectorTy()) 3353 return Error(Loc,"instruction requires integer or integer vector operands"); 3354 3355 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 3356 return false; 3357} 3358 3359 3360/// ParseCompare 3361/// ::= 'icmp' IPredicates TypeAndValue ',' Value 3362/// ::= 'fcmp' FPredicates TypeAndValue ',' Value 3363bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, 3364 unsigned Opc) { 3365 // Parse the integer/fp comparison predicate. 3366 LocTy Loc; 3367 unsigned Pred; 3368 Value *LHS, *RHS; 3369 if (ParseCmpPredicate(Pred, Opc) || 3370 ParseTypeAndValue(LHS, Loc, PFS) || 3371 ParseToken(lltok::comma, "expected ',' after compare value") || 3372 ParseValue(LHS->getType(), RHS, PFS)) 3373 return true; 3374 3375 if (Opc == Instruction::FCmp) { 3376 if (!LHS->getType()->isFPOrFPVectorTy()) 3377 return Error(Loc, "fcmp requires floating point operands"); 3378 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 3379 } else { 3380 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 3381 if (!LHS->getType()->isIntOrIntVectorTy() && 3382 !LHS->getType()->getScalarType()->isPointerTy()) 3383 return Error(Loc, "icmp requires integer operands"); 3384 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 3385 } 3386 return false; 3387} 3388 3389//===----------------------------------------------------------------------===// 3390// Other Instructions. 3391//===----------------------------------------------------------------------===// 3392 3393 3394/// ParseCast 3395/// ::= CastOpc TypeAndValue 'to' Type 3396bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, 3397 unsigned Opc) { 3398 LocTy Loc; 3399 Value *Op; 3400 Type *DestTy = 0; 3401 if (ParseTypeAndValue(Op, Loc, PFS) || 3402 ParseToken(lltok::kw_to, "expected 'to' after cast value") || 3403 ParseType(DestTy)) 3404 return true; 3405 3406 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 3407 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 3408 return Error(Loc, "invalid cast opcode for cast from '" + 3409 getTypeString(Op->getType()) + "' to '" + 3410 getTypeString(DestTy) + "'"); 3411 } 3412 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 3413 return false; 3414} 3415 3416/// ParseSelect 3417/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 3418bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { 3419 LocTy Loc; 3420 Value *Op0, *Op1, *Op2; 3421 if (ParseTypeAndValue(Op0, Loc, PFS) || 3422 ParseToken(lltok::comma, "expected ',' after select condition") || 3423 ParseTypeAndValue(Op1, PFS) || 3424 ParseToken(lltok::comma, "expected ',' after select value") || 3425 ParseTypeAndValue(Op2, PFS)) 3426 return true; 3427 3428 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 3429 return Error(Loc, Reason); 3430 3431 Inst = SelectInst::Create(Op0, Op1, Op2); 3432 return false; 3433} 3434 3435/// ParseVA_Arg 3436/// ::= 'va_arg' TypeAndValue ',' Type 3437bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { 3438 Value *Op; 3439 Type *EltTy = 0; 3440 LocTy TypeLoc; 3441 if (ParseTypeAndValue(Op, PFS) || 3442 ParseToken(lltok::comma, "expected ',' after vaarg operand") || 3443 ParseType(EltTy, TypeLoc)) 3444 return true; 3445 3446 if (!EltTy->isFirstClassType()) 3447 return Error(TypeLoc, "va_arg requires operand with first class type"); 3448 3449 Inst = new VAArgInst(Op, EltTy); 3450 return false; 3451} 3452 3453/// ParseExtractElement 3454/// ::= 'extractelement' TypeAndValue ',' TypeAndValue 3455bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 3456 LocTy Loc; 3457 Value *Op0, *Op1; 3458 if (ParseTypeAndValue(Op0, Loc, PFS) || 3459 ParseToken(lltok::comma, "expected ',' after extract value") || 3460 ParseTypeAndValue(Op1, PFS)) 3461 return true; 3462 3463 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 3464 return Error(Loc, "invalid extractelement operands"); 3465 3466 Inst = ExtractElementInst::Create(Op0, Op1); 3467 return false; 3468} 3469 3470/// ParseInsertElement 3471/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 3472bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 3473 LocTy Loc; 3474 Value *Op0, *Op1, *Op2; 3475 if (ParseTypeAndValue(Op0, Loc, PFS) || 3476 ParseToken(lltok::comma, "expected ',' after insertelement value") || 3477 ParseTypeAndValue(Op1, PFS) || 3478 ParseToken(lltok::comma, "expected ',' after insertelement value") || 3479 ParseTypeAndValue(Op2, PFS)) 3480 return true; 3481 3482 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 3483 return Error(Loc, "invalid insertelement operands"); 3484 3485 Inst = InsertElementInst::Create(Op0, Op1, Op2); 3486 return false; 3487} 3488 3489/// ParseShuffleVector 3490/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 3491bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 3492 LocTy Loc; 3493 Value *Op0, *Op1, *Op2; 3494 if (ParseTypeAndValue(Op0, Loc, PFS) || 3495 ParseToken(lltok::comma, "expected ',' after shuffle mask") || 3496 ParseTypeAndValue(Op1, PFS) || 3497 ParseToken(lltok::comma, "expected ',' after shuffle value") || 3498 ParseTypeAndValue(Op2, PFS)) 3499 return true; 3500 3501 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 3502 return Error(Loc, "invalid shufflevector operands"); 3503 3504 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 3505 return false; 3506} 3507 3508/// ParsePHI 3509/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 3510int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { 3511 Type *Ty = 0; LocTy TypeLoc; 3512 Value *Op0, *Op1; 3513 3514 if (ParseType(Ty, TypeLoc) || 3515 ParseToken(lltok::lsquare, "expected '[' in phi value list") || 3516 ParseValue(Ty, Op0, PFS) || 3517 ParseToken(lltok::comma, "expected ',' after insertelement value") || 3518 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 3519 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 3520 return true; 3521 3522 bool AteExtraComma = false; 3523 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 3524 while (1) { 3525 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 3526 3527 if (!EatIfPresent(lltok::comma)) 3528 break; 3529 3530 if (Lex.getKind() == lltok::MetadataVar) { 3531 AteExtraComma = true; 3532 break; 3533 } 3534 3535 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || 3536 ParseValue(Ty, Op0, PFS) || 3537 ParseToken(lltok::comma, "expected ',' after insertelement value") || 3538 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 3539 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 3540 return true; 3541 } 3542 3543 if (!Ty->isFirstClassType()) 3544 return Error(TypeLoc, "phi node must have first class type"); 3545 3546 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 3547 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 3548 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 3549 Inst = PN; 3550 return AteExtraComma ? InstExtraComma : InstNormal; 3551} 3552 3553/// ParseLandingPad 3554/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 3555/// Clause 3556/// ::= 'catch' TypeAndValue 3557/// ::= 'filter' 3558/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 3559bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 3560 Type *Ty = 0; LocTy TyLoc; 3561 Value *PersFn; LocTy PersFnLoc; 3562 3563 if (ParseType(Ty, TyLoc) || 3564 ParseToken(lltok::kw_personality, "expected 'personality'") || 3565 ParseTypeAndValue(PersFn, PersFnLoc, PFS)) 3566 return true; 3567 3568 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0); 3569 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 3570 3571 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 3572 LandingPadInst::ClauseType CT; 3573 if (EatIfPresent(lltok::kw_catch)) 3574 CT = LandingPadInst::Catch; 3575 else if (EatIfPresent(lltok::kw_filter)) 3576 CT = LandingPadInst::Filter; 3577 else 3578 return TokError("expected 'catch' or 'filter' clause type"); 3579 3580 Value *V; LocTy VLoc; 3581 if (ParseTypeAndValue(V, VLoc, PFS)) { 3582 delete LP; 3583 return true; 3584 } 3585 3586 // A 'catch' type expects a non-array constant. A filter clause expects an 3587 // array constant. 3588 if (CT == LandingPadInst::Catch) { 3589 if (isa<ArrayType>(V->getType())) 3590 Error(VLoc, "'catch' clause has an invalid type"); 3591 } else { 3592 if (!isa<ArrayType>(V->getType())) 3593 Error(VLoc, "'filter' clause has an invalid type"); 3594 } 3595 3596 LP->addClause(V); 3597 } 3598 3599 Inst = LP; 3600 return false; 3601} 3602 3603/// ParseCall 3604/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value 3605/// ParameterList OptionalAttrs 3606bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, 3607 bool isTail) { 3608 Attributes RetAttrs, FnAttrs; 3609 CallingConv::ID CC; 3610 Type *RetType = 0; 3611 LocTy RetTypeLoc; 3612 ValID CalleeID; 3613 SmallVector<ParamInfo, 16> ArgList; 3614 LocTy CallLoc = Lex.getLoc(); 3615 3616 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) || 3617 ParseOptionalCallingConv(CC) || 3618 ParseOptionalAttrs(RetAttrs, 1) || 3619 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 3620 ParseValID(CalleeID) || 3621 ParseParameterList(ArgList, PFS) || 3622 ParseOptionalAttrs(FnAttrs, 2)) 3623 return true; 3624 3625 // If RetType is a non-function pointer type, then this is the short syntax 3626 // for the call, which means that RetType is just the return type. Infer the 3627 // rest of the function argument types from the arguments that are present. 3628 PointerType *PFTy = 0; 3629 FunctionType *Ty = 0; 3630 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 3631 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 3632 // Pull out the types of all of the arguments... 3633 std::vector<Type*> ParamTypes; 3634 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 3635 ParamTypes.push_back(ArgList[i].V->getType()); 3636 3637 if (!FunctionType::isValidReturnType(RetType)) 3638 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 3639 3640 Ty = FunctionType::get(RetType, ParamTypes, false); 3641 PFTy = PointerType::getUnqual(Ty); 3642 } 3643 3644 // Look up the callee. 3645 Value *Callee; 3646 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true; 3647 3648 // Set up the Attributes for the function. 3649 SmallVector<AttributeWithIndex, 8> Attrs; 3650 if (RetAttrs != Attribute::None) 3651 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 3652 3653 SmallVector<Value*, 8> Args; 3654 3655 // Loop through FunctionType's arguments and ensure they are specified 3656 // correctly. Also, gather any parameter attributes. 3657 FunctionType::param_iterator I = Ty->param_begin(); 3658 FunctionType::param_iterator E = Ty->param_end(); 3659 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 3660 Type *ExpectedTy = 0; 3661 if (I != E) { 3662 ExpectedTy = *I++; 3663 } else if (!Ty->isVarArg()) { 3664 return Error(ArgList[i].Loc, "too many arguments specified"); 3665 } 3666 3667 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 3668 return Error(ArgList[i].Loc, "argument is not of expected type '" + 3669 getTypeString(ExpectedTy) + "'"); 3670 Args.push_back(ArgList[i].V); 3671 if (ArgList[i].Attrs != Attribute::None) 3672 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 3673 } 3674 3675 if (I != E) 3676 return Error(CallLoc, "not enough parameters specified for call"); 3677 3678 if (FnAttrs != Attribute::None) 3679 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); 3680 3681 // Finish off the Attributes and check them 3682 AttrListPtr PAL = AttrListPtr::get(Attrs); 3683 3684 CallInst *CI = CallInst::Create(Callee, Args); 3685 CI->setTailCall(isTail); 3686 CI->setCallingConv(CC); 3687 CI->setAttributes(PAL); 3688 Inst = CI; 3689 return false; 3690} 3691 3692//===----------------------------------------------------------------------===// 3693// Memory Instructions. 3694//===----------------------------------------------------------------------===// 3695 3696/// ParseAlloc 3697/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)? 3698int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 3699 Value *Size = 0; 3700 LocTy SizeLoc; 3701 unsigned Alignment = 0; 3702 Type *Ty = 0; 3703 if (ParseType(Ty)) return true; 3704 3705 bool AteExtraComma = false; 3706 if (EatIfPresent(lltok::comma)) { 3707 if (Lex.getKind() == lltok::kw_align) { 3708 if (ParseOptionalAlignment(Alignment)) return true; 3709 } else if (Lex.getKind() == lltok::MetadataVar) { 3710 AteExtraComma = true; 3711 } else { 3712 if (ParseTypeAndValue(Size, SizeLoc, PFS) || 3713 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 3714 return true; 3715 } 3716 } 3717 3718 if (Size && !Size->getType()->isIntegerTy()) 3719 return Error(SizeLoc, "element count must have integer type"); 3720 3721 Inst = new AllocaInst(Ty, Size, Alignment); 3722 return AteExtraComma ? InstExtraComma : InstNormal; 3723} 3724 3725/// ParseLoad 3726/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 3727/// ::= 'load' 'atomic' 'volatile'? TypeAndValue 3728/// 'singlethread'? AtomicOrdering (',' 'align' i32)? 3729int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) { 3730 Value *Val; LocTy Loc; 3731 unsigned Alignment = 0; 3732 bool AteExtraComma = false; 3733 bool isAtomic = false; 3734 AtomicOrdering Ordering = NotAtomic; 3735 SynchronizationScope Scope = CrossThread; 3736 3737 if (Lex.getKind() == lltok::kw_atomic) { 3738 isAtomic = true; 3739 Lex.Lex(); 3740 } 3741 3742 bool isVolatile = false; 3743 if (Lex.getKind() == lltok::kw_volatile) { 3744 isVolatile = true; 3745 Lex.Lex(); 3746 } 3747 3748 if (ParseTypeAndValue(Val, Loc, PFS) || 3749 ParseScopeAndOrdering(isAtomic, Scope, Ordering) || 3750 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 3751 return true; 3752 3753 if (!Val->getType()->isPointerTy() || 3754 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType()) 3755 return Error(Loc, "load operand must be a pointer to a first class type"); 3756 if (isAtomic && !Alignment) 3757 return Error(Loc, "atomic load must have explicit non-zero alignment"); 3758 if (Ordering == Release || Ordering == AcquireRelease) 3759 return Error(Loc, "atomic load cannot use Release ordering"); 3760 3761 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope); 3762 return AteExtraComma ? InstExtraComma : InstNormal; 3763} 3764 3765/// ParseStore 3766 3767/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 3768/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 3769/// 'singlethread'? AtomicOrdering (',' 'align' i32)? 3770int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) { 3771 Value *Val, *Ptr; LocTy Loc, PtrLoc; 3772 unsigned Alignment = 0; 3773 bool AteExtraComma = false; 3774 bool isAtomic = false; 3775 AtomicOrdering Ordering = NotAtomic; 3776 SynchronizationScope Scope = CrossThread; 3777 3778 if (Lex.getKind() == lltok::kw_atomic) { 3779 isAtomic = true; 3780 Lex.Lex(); 3781 } 3782 3783 bool isVolatile = false; 3784 if (Lex.getKind() == lltok::kw_volatile) { 3785 isVolatile = true; 3786 Lex.Lex(); 3787 } 3788 3789 if (ParseTypeAndValue(Val, Loc, PFS) || 3790 ParseToken(lltok::comma, "expected ',' after store operand") || 3791 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 3792 ParseScopeAndOrdering(isAtomic, Scope, Ordering) || 3793 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 3794 return true; 3795 3796 if (!Ptr->getType()->isPointerTy()) 3797 return Error(PtrLoc, "store operand must be a pointer"); 3798 if (!Val->getType()->isFirstClassType()) 3799 return Error(Loc, "store operand must be a first class value"); 3800 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 3801 return Error(Loc, "stored value and pointer type do not match"); 3802 if (isAtomic && !Alignment) 3803 return Error(Loc, "atomic store must have explicit non-zero alignment"); 3804 if (Ordering == Acquire || Ordering == AcquireRelease) 3805 return Error(Loc, "atomic store cannot use Acquire ordering"); 3806 3807 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope); 3808 return AteExtraComma ? InstExtraComma : InstNormal; 3809} 3810 3811/// ParseCmpXchg 3812/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue 3813/// 'singlethread'? AtomicOrdering 3814int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 3815 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 3816 bool AteExtraComma = false; 3817 AtomicOrdering Ordering = NotAtomic; 3818 SynchronizationScope Scope = CrossThread; 3819 bool isVolatile = false; 3820 3821 if (EatIfPresent(lltok::kw_volatile)) 3822 isVolatile = true; 3823 3824 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 3825 ParseToken(lltok::comma, "expected ',' after cmpxchg address") || 3826 ParseTypeAndValue(Cmp, CmpLoc, PFS) || 3827 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 3828 ParseTypeAndValue(New, NewLoc, PFS) || 3829 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering)) 3830 return true; 3831 3832 if (Ordering == Unordered) 3833 return TokError("cmpxchg cannot be unordered"); 3834 if (!Ptr->getType()->isPointerTy()) 3835 return Error(PtrLoc, "cmpxchg operand must be a pointer"); 3836 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType()) 3837 return Error(CmpLoc, "compare value and pointer type do not match"); 3838 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType()) 3839 return Error(NewLoc, "new value and pointer type do not match"); 3840 if (!New->getType()->isIntegerTy()) 3841 return Error(NewLoc, "cmpxchg operand must be an integer"); 3842 unsigned Size = New->getType()->getPrimitiveSizeInBits(); 3843 if (Size < 8 || (Size & (Size - 1))) 3844 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized" 3845 " integer"); 3846 3847 AtomicCmpXchgInst *CXI = 3848 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope); 3849 CXI->setVolatile(isVolatile); 3850 Inst = CXI; 3851 return AteExtraComma ? InstExtraComma : InstNormal; 3852} 3853 3854/// ParseAtomicRMW 3855/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 3856/// 'singlethread'? AtomicOrdering 3857int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 3858 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 3859 bool AteExtraComma = false; 3860 AtomicOrdering Ordering = NotAtomic; 3861 SynchronizationScope Scope = CrossThread; 3862 bool isVolatile = false; 3863 AtomicRMWInst::BinOp Operation; 3864 3865 if (EatIfPresent(lltok::kw_volatile)) 3866 isVolatile = true; 3867 3868 switch (Lex.getKind()) { 3869 default: return TokError("expected binary operation in atomicrmw"); 3870 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 3871 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 3872 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 3873 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 3874 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 3875 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 3876 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 3877 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 3878 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 3879 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 3880 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 3881 } 3882 Lex.Lex(); // Eat the operation. 3883 3884 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 3885 ParseToken(lltok::comma, "expected ',' after atomicrmw address") || 3886 ParseTypeAndValue(Val, ValLoc, PFS) || 3887 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering)) 3888 return true; 3889 3890 if (Ordering == Unordered) 3891 return TokError("atomicrmw cannot be unordered"); 3892 if (!Ptr->getType()->isPointerTy()) 3893 return Error(PtrLoc, "atomicrmw operand must be a pointer"); 3894 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 3895 return Error(ValLoc, "atomicrmw value and pointer type do not match"); 3896 if (!Val->getType()->isIntegerTy()) 3897 return Error(ValLoc, "atomicrmw operand must be an integer"); 3898 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 3899 if (Size < 8 || (Size & (Size - 1))) 3900 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 3901 " integer"); 3902 3903 AtomicRMWInst *RMWI = 3904 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope); 3905 RMWI->setVolatile(isVolatile); 3906 Inst = RMWI; 3907 return AteExtraComma ? InstExtraComma : InstNormal; 3908} 3909 3910/// ParseFence 3911/// ::= 'fence' 'singlethread'? AtomicOrdering 3912int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) { 3913 AtomicOrdering Ordering = NotAtomic; 3914 SynchronizationScope Scope = CrossThread; 3915 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering)) 3916 return true; 3917 3918 if (Ordering == Unordered) 3919 return TokError("fence cannot be unordered"); 3920 if (Ordering == Monotonic) 3921 return TokError("fence cannot be monotonic"); 3922 3923 Inst = new FenceInst(Context, Ordering, Scope); 3924 return InstNormal; 3925} 3926 3927/// ParseGetElementPtr 3928/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 3929int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 3930 Value *Ptr = 0; 3931 Value *Val = 0; 3932 LocTy Loc, EltLoc; 3933 3934 bool InBounds = EatIfPresent(lltok::kw_inbounds); 3935 3936 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true; 3937 3938 if (!Ptr->getType()->getScalarType()->isPointerTy()) 3939 return Error(Loc, "base of getelementptr must be a pointer"); 3940 3941 SmallVector<Value*, 16> Indices; 3942 bool AteExtraComma = false; 3943 while (EatIfPresent(lltok::comma)) { 3944 if (Lex.getKind() == lltok::MetadataVar) { 3945 AteExtraComma = true; 3946 break; 3947 } 3948 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; 3949 if (!Val->getType()->getScalarType()->isIntegerTy()) 3950 return Error(EltLoc, "getelementptr index must be an integer"); 3951 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy()) 3952 return Error(EltLoc, "getelementptr index type missmatch"); 3953 if (Val->getType()->isVectorTy()) { 3954 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements(); 3955 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements(); 3956 if (ValNumEl != PtrNumEl) 3957 return Error(EltLoc, 3958 "getelementptr vector index has a wrong number of elements"); 3959 } 3960 Indices.push_back(Val); 3961 } 3962 3963 if (Val && Val->getType()->isVectorTy() && Indices.size() != 1) 3964 return Error(EltLoc, "vector getelementptrs must have a single index"); 3965 3966 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices)) 3967 return Error(Loc, "invalid getelementptr indices"); 3968 Inst = GetElementPtrInst::Create(Ptr, Indices); 3969 if (InBounds) 3970 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 3971 return AteExtraComma ? InstExtraComma : InstNormal; 3972} 3973 3974/// ParseExtractValue 3975/// ::= 'extractvalue' TypeAndValue (',' uint32)+ 3976int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 3977 Value *Val; LocTy Loc; 3978 SmallVector<unsigned, 4> Indices; 3979 bool AteExtraComma; 3980 if (ParseTypeAndValue(Val, Loc, PFS) || 3981 ParseIndexList(Indices, AteExtraComma)) 3982 return true; 3983 3984 if (!Val->getType()->isAggregateType()) 3985 return Error(Loc, "extractvalue operand must be aggregate type"); 3986 3987 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 3988 return Error(Loc, "invalid indices for extractvalue"); 3989 Inst = ExtractValueInst::Create(Val, Indices); 3990 return AteExtraComma ? InstExtraComma : InstNormal; 3991} 3992 3993/// ParseInsertValue 3994/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 3995int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 3996 Value *Val0, *Val1; LocTy Loc0, Loc1; 3997 SmallVector<unsigned, 4> Indices; 3998 bool AteExtraComma; 3999 if (ParseTypeAndValue(Val0, Loc0, PFS) || 4000 ParseToken(lltok::comma, "expected comma after insertvalue operand") || 4001 ParseTypeAndValue(Val1, Loc1, PFS) || 4002 ParseIndexList(Indices, AteExtraComma)) 4003 return true; 4004 4005 if (!Val0->getType()->isAggregateType()) 4006 return Error(Loc0, "insertvalue operand must be aggregate type"); 4007 4008 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices)) 4009 return Error(Loc0, "invalid indices for insertvalue"); 4010 Inst = InsertValueInst::Create(Val0, Val1, Indices); 4011 return AteExtraComma ? InstExtraComma : InstNormal; 4012} 4013 4014//===----------------------------------------------------------------------===// 4015// Embedded metadata. 4016//===----------------------------------------------------------------------===// 4017 4018/// ParseMDNodeVector 4019/// ::= Element (',' Element)* 4020/// Element 4021/// ::= 'null' | TypeAndValue 4022bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts, 4023 PerFunctionState *PFS) { 4024 // Check for an empty list. 4025 if (Lex.getKind() == lltok::rbrace) 4026 return false; 4027 4028 do { 4029 // Null is a special case since it is typeless. 4030 if (EatIfPresent(lltok::kw_null)) { 4031 Elts.push_back(0); 4032 continue; 4033 } 4034 4035 Value *V = 0; 4036 if (ParseTypeAndValue(V, PFS)) return true; 4037 Elts.push_back(V); 4038 } while (EatIfPresent(lltok::comma)); 4039 4040 return false; 4041} 4042