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