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