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