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