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